Repository navigation
feat: custominvoicing db struct - #2679
Conversation
📝 WalkthroughWalkthroughThis change introduces two new entities, Changes
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (1.64.8)Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2 🔧 SQLFluff (3.3.0)tools/migrate/migrations/20250416191201_app-custominvoicing.down.sqlUser Error: No dialect was specified. You must configure a dialect or specify one on the command line using --dialect after the command. Available dialects: tools/migrate/migrations/20250416191201_app-custominvoicing.up.sqlUser Error: No dialect was specified. You must configure a dialect or specify one on the command line using --dialect after the command. Available dialects: Tip ⚡💬 Agentic Chat (Pro Plan, General Availability)
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (13)
openmeter/ent/db/paginate.go (1)
156-203: Leverage shared pagination logic.These new pagination methods for
AppCustomInvoicingQueryclosely mirror the existing pattern in the file, resetting the offset/limit, counting the results in a cloned query, and subsequently fetching the page. While this is correct and consistent, consider extracting the common pagination steps into a reusable helper function to reduce duplication and minimize errors across multiple query types.openmeter/ent/schema/appcustominvoicing.go (1)
1-49: Minor comment typos and overall schema clarity.The
AppCustomInvoicingschema definition and mixins look solid. However, in the multiline comment on lines 41–42, the word "othwerwise" can be corrected to "otherwise," and "ent generate breaks" can be rephrased to "Ent code generation breaks." This minor nitpick will improve readability.- // We need to set StorageKey instead of Field, othwerwise ent generate breaks. + // We need to set StorageKey instead of Field, otherwise Ent code generation breaks.openmeter/ent/db/migrate/schema.go (2)
205-214: Ensure naming consistency for the referencing column.
The column nameidhere is dual-purposed as both the primary key forapp_custom_invoicingsand a foreign key toapps. This may be intentional, but it can impede clarity. Consider clarifying or documenting whyidreferencesapps.id.
241-283: Check the overlap in naming forapp_id.
The columnapp_idinapp_custom_invoicing_customersactually referencesapp_custom_invoicings.id. This might cause confusion if developers assume it points to theappstable. Consider renaming it or adding internal documentation.openmeter/ent/db/appcustominvoicingcustomer.go (1)
196-226: String method.
Useful for debugging. Nicely structured to display all critical fields, includingmetadata.Optional: Trim overly large map output if
metadatamight be huge in real usage.openmeter/ent/db/appcustominvoicing.go (1)
180-206: Check if indexing is sufficient.The string fields
[namespace]or timestamps might benefit from being indexed, especially if large volumes of data are expected.openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (1)
29-30: Assess JSON storage for metadata.
FieldMetadatastores a map in JSON format. Ensure that the data size remains manageable and consider potential constraints or validations if you expect large or nested structures.openmeter/ent/db/appcustominvoicingcustomer_update.go (1)
102-108: Automatic timestamps.You rely on
UpdateDefaultUpdatedAtif no explicitUpdatedAtvalue is set. Confirm that this default logic properly covers all update paths and use cases.openmeter/ent/db/appcustominvoicing_query.go (3)
37-66: Incremental builder methods
The chained methods (Where, Limit, Offset, Unique, Order) align well with typical Ent patterns. Consider verifying performance impact when using large offsets in production.
212-229:Allmethod
Retrieves all matching records without pagination. For large datasets, adding pagination or a streaming approach may improve performance.
652-676: GroupBy aggregator
This implementation follows a typical Ent pattern. Ensure that adequate indexing exists for columns involved in heavy aggregations.openmeter/ent/db/appcustominvoicingcustomer_query.go (2)
36-66: Builder methods (Where, Limit, Offset, Unique, Order)
Functionality is consistent and straightforward. As a minor note, large offsets can be costly, so consider using keyset pagination where possible.
211-228:Allmethod
Standard approach for retrieving multiple records. Consider using pagination for scalability.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
tools/migrate/migrations/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (28)
openmeter/ent/db/appcustominvoicing.go(1 hunks)openmeter/ent/db/appcustominvoicing/appcustominvoicing.go(1 hunks)openmeter/ent/db/appcustominvoicing/where.go(1 hunks)openmeter/ent/db/appcustominvoicing_create.go(1 hunks)openmeter/ent/db/appcustominvoicing_delete.go(1 hunks)openmeter/ent/db/appcustominvoicing_query.go(1 hunks)openmeter/ent/db/appcustominvoicing_update.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer/where.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer_create.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer_delete.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer_query.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer_update.go(1 hunks)openmeter/ent/db/client.go(11 hunks)openmeter/ent/db/ent.go(2 hunks)openmeter/ent/db/expose.go(1 hunks)openmeter/ent/db/hook/hook.go(1 hunks)openmeter/ent/db/migrate/schema.go(3 hunks)openmeter/ent/db/mutation.go(3 hunks)openmeter/ent/db/paginate.go(1 hunks)openmeter/ent/db/predicate/predicate.go(1 hunks)openmeter/ent/db/runtime.go(2 hunks)openmeter/ent/db/setorclear.go(1 hunks)openmeter/ent/db/tx.go(2 hunks)openmeter/ent/schema/appcustominvoicing.go(1 hunks)tools/migrate/migrations/20250416120917_app-custominvoicing.down.sql(1 hunks)tools/migrate/migrations/20250416120917_app-custominvoicing.up.sql(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (7)
openmeter/ent/db/ent.go (2)
openmeter/ent/db/appcustominvoicing/appcustominvoicing.go (2)
Table(34-34)ValidColumn(63-70)openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (2)
Table(36-36)ValidColumn(66-73)
openmeter/ent/db/appcustominvoicing_delete.go (6)
openmeter/ent/db/ent.go (4)
Hook(66-66)IsConstraintError(367-373)ConstraintError(351-354)NotFoundError(284-286)openmeter/ent/db/mutation.go (1)
AppCustomInvoicingMutation(4628-4648)openmeter/ent/db/appcustominvoicing.go (2)
AppCustomInvoicing(17-37)AppCustomInvoicing(71-86)openmeter/ent/db/predicate/predicate.go (1)
AppCustomInvoicing(41-41)openmeter/ent/schema/appcustominvoicing.go (5)
AppCustomInvoicing(14-16)AppCustomInvoicing(18-24)AppCustomInvoicing(26-31)AppCustomInvoicing(33-35)AppCustomInvoicing(37-48)openmeter/ent/db/appcustominvoicing/appcustominvoicing.go (3)
Table(34-34)FieldID(16-16)Label(14-14)
openmeter/ent/db/appcustominvoicingcustomer_delete.go (6)
openmeter/ent/db/ent.go (3)
IsConstraintError(367-373)ConstraintError(351-354)NotFoundError(284-286)openmeter/ent/db/mutation.go (1)
AppCustomInvoicingCustomerMutation(5404-5422)openmeter/ent/db/appcustominvoicingcustomer.go (2)
AppCustomInvoicingCustomer(19-41)AppCustomInvoicingCustomer(77-94)openmeter/ent/db/predicate/predicate.go (1)
AppCustomInvoicingCustomer(44-44)openmeter/ent/schema/appcustominvoicing.go (5)
AppCustomInvoicingCustomer(51-53)AppCustomInvoicingCustomer(55-60)AppCustomInvoicingCustomer(62-72)AppCustomInvoicingCustomer(74-79)AppCustomInvoicingCustomer(81-100)openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (3)
Table(36-36)FieldID(16-16)Label(14-14)
openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (1)
openmeter/ent/db/appcustominvoicing/appcustominvoicing.go (14)
FieldID(16-16)FieldNamespace(18-18)FieldCreatedAt(20-20)FieldUpdatedAt(22-22)FieldDeletedAt(24-24)ValidColumn(63-70)Columns(52-60)ByID(93-95)OrderOption(90-90)ByNamespace(98-100)ByCreatedAt(103-105)ByUpdatedAt(108-110)ByDeletedAt(113-115)Table(34-34)
openmeter/ent/db/appcustominvoicingcustomer.go (9)
openmeter/ent/db/appcustominvoicingcustomer/where.go (7)
ID(14-16)Namespace(59-61)CreatedAt(64-66)UpdatedAt(69-71)DeletedAt(74-76)AppID(79-81)CustomerID(84-86)openmeter/ent/db/appcustominvoicing.go (2)
AppCustomInvoicing(17-37)AppCustomInvoicing(71-86)openmeter/ent/schema/appcustominvoicing.go (10)
AppCustomInvoicing(14-16)AppCustomInvoicing(18-24)AppCustomInvoicing(26-31)AppCustomInvoicing(33-35)AppCustomInvoicing(37-48)AppCustomInvoicingCustomer(51-53)AppCustomInvoicingCustomer(55-60)AppCustomInvoicingCustomer(62-72)AppCustomInvoicingCustomer(74-79)AppCustomInvoicingCustomer(81-100)openmeter/ent/db/ent.go (3)
NotFoundError(284-286)NotLoadedError(330-332)Value(67-67)openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (9)
Label(14-14)FieldMetadata(30-30)FieldID(16-16)FieldNamespace(18-18)FieldAppID(26-26)FieldCustomerID(28-28)FieldCreatedAt(20-20)FieldUpdatedAt(22-22)FieldDeletedAt(24-24)openmeter/ent/db/appcustominvoicing_query.go (1)
AppCustomInvoicingQuery(23-35)openmeter/ent/db/client.go (1)
NewAppCustomInvoicingCustomerClient(1348-1350)openmeter/ent/db/customer_query.go (1)
CustomerQuery(26-41)openmeter/ent/db/appcustominvoicingcustomer_update.go (1)
AppCustomInvoicingCustomerUpdateOne(161-166)
openmeter/ent/db/setorclear.go (2)
openmeter/ent/db/appcustominvoicing_update.go (2)
AppCustomInvoicingUpdate(20-24)AppCustomInvoicingUpdateOne(245-250)openmeter/ent/db/appcustominvoicingcustomer_update.go (2)
AppCustomInvoicingCustomerUpdate(19-23)AppCustomInvoicingCustomerUpdateOne(161-166)
openmeter/ent/db/appcustominvoicing/appcustominvoicing.go (1)
openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (14)
FieldID(16-16)FieldNamespace(18-18)FieldCreatedAt(20-20)FieldUpdatedAt(22-22)FieldDeletedAt(24-24)ValidColumn(66-73)Columns(54-63)ByID(94-96)OrderOption(91-91)ByNamespace(99-101)ByCreatedAt(104-106)ByUpdatedAt(109-111)ByDeletedAt(114-116)Table(36-36)
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: E2E
- GitHub Check: Quickstart
- GitHub Check: CI
- GitHub Check: Lint
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Test
- GitHub Check: Build
- GitHub Check: Analyze (go)
🔇 Additional comments (104)
openmeter/ent/db/ent.go (2)
20-21: New imports for custom invoicing entitiesThe import statements correctly include the new packages for AppCustomInvoicing and AppCustomInvoicingCustomer entities.
124-125: Column validation map updated correctlyThe checkColumn function's columnCheck map is properly extended to include validation for the new tables, ensuring that column names are properly validated when used in queries.
openmeter/ent/db/predicate/predicate.go (1)
40-44: New predicate types for custom invoicing entitiesThe predicate types for the new entities follow the established pattern of other entity predicates in the codebase. These predicates will be used for filtering queries on the new entities.
openmeter/ent/db/expose.go (1)
98-100: Transaction client initialization for new entitiesThe new entity clients are properly initialized in the transaction client factory, enabling transactional operations on these entities. The changes maintain alphabetical ordering consistent with the rest of the file.
tools/migrate/migrations/20250416120917_app-custominvoicing.down.sql (1)
1-12: Well-structured down migration scriptThe down migration correctly drops indexes before dropping tables, following best practices for dependency management in database schema changes. The script is properly documented with comments indicating what is being reversed.
openmeter/ent/db/tx.go (2)
23-26: Transaction struct fields for new entity clientsThe Tx struct is appropriately extended with fields for the new entity clients, maintaining the alphabetical ordering and documentation style consistent with other fields.
237-238: Client initialization in transaction init methodThe transaction initialization method properly initializes the new entity clients with the transaction configuration, ensuring they participate correctly in transaction operations.
openmeter/ent/db/runtime.go (3)
13-14: New imports added for custom invoicing entities.These imports are correctly added to support the new AppCustomInvoicing and AppCustomInvoicingCustomer entities being introduced to the codebase.
173-207: Runtime initialization for AppCustomInvoicing entity.The code follows the established pattern for entity initialization in the codebase:
- Properly extracts mixin and schema field descriptors
- Sets up validators for namespace field
- Configures default values for timestamps
- Sets default values for boolean flags (skip_draft_sync_hook, skip_issuing_sync_hook)
- Configures ID generation
The implementation is consistent with other entities and correctly handles all needed runtime initialization.
208-236: Runtime initialization for AppCustomInvoicingCustomer entity.The code correctly:
- Extracts field descriptors from mixins
- Sets up validators for namespace, app_id, and customer_id fields
- Configures default values and update handlers for timestamp fields
Implementation follows the same patterns used for other entities in the system and integrates well with the existing codebase.
openmeter/ent/db/hook/hook.go (2)
48-58: Added AppCustomInvoicingFunc hook adapter.This hook adapter correctly implements the pattern used throughout the codebase:
- Defines a function type that accepts AppCustomInvoicingMutation
- Implements Mutate method to validate mutation type and invoke the function
- Provides proper error handling for unexpected mutation types
This addition enables custom mutation hooks for the new AppCustomInvoicing entity.
60-70: Added AppCustomInvoicingCustomerFunc hook adapter.This hook adapter follows the established pattern:
- Defines a function type for AppCustomInvoicingCustomer mutations
- Implements the Mutate method for the db.Hook interface
- Provides appropriate type checking and error handling
The implementation is consistent with other hook adapters and enables hook functionality for the new entity.
tools/migrate/migrations/20250416120917_app-custominvoicing.up.sql (2)
1-16: Schema creation for app_custom_invoicings table.The migration correctly:
- Creates a table with appropriate columns and data types
- Sets up a primary key on the "id" field
- Establishes a foreign key constraint to the "apps" table with cascade delete
- Creates appropriate indexes for query performance
- Sets default values for boolean flags (skip_draft_sync_hook, skip_issuing_sync_hook)
The schema design follows database best practices and integrates well with the existing schema.
17-34: Schema creation for app_custom_invoicing_customers table.The migration properly:
- Creates a table with auto-incrementing ID and appropriate columns
- Sets up primary key constraint
- Establishes foreign key constraints to both app_custom_invoicings and customers tables
- Includes cascade delete behavior for proper referential integrity
- Creates a standard index on namespace and a unique composite index for (namespace, app_id, customer_id)
- Supports optional JSONB metadata for flexibility
The table design follows sound database principles and supports the entity relationship model.
openmeter/ent/db/paginate.go (1)
204-251: Consistent pagination approach.The pagination logic for
AppCustomInvoicingCustomerQuerymatches the existing pattern in this file, ensuring uniformity across the codebase. The approach to unset offsets/limits before counting and then fetching the paged results remains consistent. No immediate issues observed; looks good.openmeter/ent/db/setorclear.go (2)
282-295: Well-aligned with existing patterns.The new
SetOrClearDeletedAtmethods forAppCustomInvoicingUpdateandAppCustomInvoicingUpdateOnefollow the same idiomatic approach used elsewhere (e.g., checking nil to clear the field). This ensures consistency and clarity across update builders. Looks good.
296-323: Appropriate usage of SetOrClear for nullable fields.Adding
SetOrClearDeletedAtandSetOrClearMetadatatoAppCustomInvoicingCustomerUpdateandAppCustomInvoicingCustomerUpdateOnepreserves consistency with the rest of the codebase. It provides a clear, conditional approach to updating nullable fields. No concerns here.openmeter/ent/schema/appcustominvoicing.go (1)
50-101: Edge handling rationale is reasonable.The
AppCustomInvoicingCustomerentity is well-defined, with careful edge design to avoid conflicting references to the same field. Keeping this entity minimal and referencingcustomer_idfor thecustomeredge is appropriate. No structural issues noted.openmeter/ent/db/appcustominvoicingcustomer_delete.go (1)
1-89: Generated code follows Ent ORM patterns correctly.This file provides deletion builders for the
AppCustomInvoicingCustomerentity, correctly implementing both bulk delete (AppCustomInvoicingCustomerDelete) and single-entity delete operations (AppCustomInvoicingCustomerDeleteOne) with appropriate error handling, predicate filtering, and hook support. The implementation aligns with Ent ORM standards and properly integrates with the overall database structure.openmeter/ent/db/appcustominvoicing_delete.go (1)
1-89: Generated code follows Ent ORM patterns correctly.This file implements deletion builders for the
AppCustomInvoicingentity, following the same pattern as the customer deletion builder. The implementation correctly uses string-typed IDs (as opposed to int-typed IDs in the customer entity), maintains proper error handling for constraint violations, and includes hook support. This aligns with the PR objective of creating database structures for custom invoicing.openmeter/ent/db/mutation.go (8)
23-24: Imports properly added for new custom invoicing modules.The imports for the newly created packages for AppCustomInvoicing and AppCustomInvoicingCustomer are correctly added, maintaining the import structure pattern of the codebase.
83-84: Type constants properly defined for the new entities.The constants for the new entities follow the proper naming convention and style used throughout the codebase, ensuring consistency with other entity type definitions.
4627-4648: AppCustomInvoicingMutation struct properly defined.The struct definition for AppCustomInvoicingMutation includes all required fields for tracking mutations, following the codebase's established pattern. The inclusion of fields for namespace, timestamps, hook flags, and relationship tracking aligns with the entity's requirements.
4649-4702: Helper functions properly implemented for AppCustomInvoicingMutation.The implementation includes the functional option pattern for mutation configuration and proper old value retrieval mechanisms, maintaining consistency with other entity implementations in the codebase.
4703-5401: Complete set of CRUD methods implemented for AppCustomInvoicingMutation.All necessary methods for field access, edge management, and mutation operations are properly implemented, providing a comprehensive API for manipulating AppCustomInvoicing entities. The implementation follows the established patterns of the Ent framework.
5403-5423: AppCustomInvoicingCustomerMutation struct properly defined.The struct definition includes all necessary fields for the AppCustomInvoicingCustomer entity, including metadata field which supports the application-specific metadata storage mentioned in the PR objectives.
5424-5473: Helper functions properly implemented for AppCustomInvoicingCustomerMutation.The implementation includes appropriate setup for mutation configuration and old value retrieval, maintaining consistency with the AppCustomInvoicing entity and other entities in the codebase.
5474-6205: Complete set of CRUD methods implemented for AppCustomInvoicingCustomerMutation.All necessary methods for field access, edge management, and mutation operations are properly implemented, providing a comprehensive API for manipulating AppCustomInvoicingCustomer entities. The implementation includes proper support for the metadata field and relationship management.
openmeter/ent/db/migrate/schema.go (3)
215-240: Verify indexes and constraints match business needs.
The current indexes on theapp_custom_invoicingstable appear correct, but ensure you don’t need coverage on the two boolean fields (skip_draft_sync_hook,skip_issuing_sync_hook) if you filter by them frequently.
2450-2451: Great addition of new tables to the schema.
IncorporatingAppCustomInvoicingsTableandAppCustomInvoicingCustomersTableinto the global slice ensures proper migration ordering.
2498-2500: Confirm foreign key references.
These references tieapp_custom_invoicings.idtoapps.idandapp_custom_invoicing_customers.app_idtoapp_custom_invoicings.id. Verify that this cascading logic aligns with your domain model and data-lifecycle needs.openmeter/ent/db/appcustominvoicing/appcustominvoicing.go (6)
1-2: Auto-generated code acknowledgment.
No significant user-written logic here; just confirming these lines are standard Ent boilerplate.
3-49: Field naming and edges are consistent.
The definitions for fields (FieldID,FieldNamespace, etc.) and edges (customer_apps,app) match the schema’s intent. Good clarity in labeling.
51-70: Column validation function.
ValidColumn(column string)is straightforward and consistent with Ent’s approach. It lowers the risk of referencing non-existent columns.
72-87: Defaults and validation.
The placeholders (e.g.,NamespaceValidator) accommodate customization and hooking into your application’s domain logic. Make sure they’re initialized inruntime.goor another relevant place before use.
89-146: Ordering definitions appear correct.
The ordering by neighbor terms (e.g.,ByCustomerApps,ByAppField) leverages Ent’s standard pattern for sorting across edges.
147-160: Neighbor step logic is aligned with the ent graph structure.
These steps ensure correct join conditions for related edges. Implementation follows ent best practices.openmeter/ent/db/appcustominvoicingcustomer.go (11)
1-2: Ent code generation header.
No custom logic here. Standard generated annotation.
3-16: Package and imports.
Everything is aligned with your ent codebase structure, referencing sibling packages for extended queries.
18-41: Core fields and their types look correct.
Usingintfor the primary key ensures auto-increment behavior. TheAppIDandCustomerIDare properly typed as strings matching the foreignchar(26)columns.
43-74: Edges structure is well-defined.
The separate references toCustomInvoicingAppandCustomeredges are consistent with your schema definitions.
76-94: Scanning logic.
The switch cases for each field type are correct, ensuring date/time columns and JSON columns are parsed properly.
96-160: Value assignment.
You handleNullString,NullTime,[]byte, etc., properly, which mitigates runtime scanning errors. The unmarshal for EAV-likemetadatais also robust.
162-166: Select values.
Allows dynamic retrieval of extra columns if someone modifies the query or uses custom projection. Good extensibility.
168-176: Query methods.
QueryCustomInvoicingApp()andQueryCustomer()use the correct client pattern for fetching related entities.
178-183: Update method usage.
Update()returns a strongly typed builder. This is standard Ent usage and straightforward.
185-194: Transaction unwrap logic.
Maintains referential correctness for entities used within a transaction. The panic if not transactional is direct and clarifies usage constraints.
227-229: Parsable slice definition.
AppCustomInvoicingCustomersslice is consistent with typical ent code.openmeter/ent/db/appcustominvoicing.go (3)
1-2: Generated code acknowledgment.The file is auto-generated by Ent. Direct modifications may be overwritten. Instead, configuration or logic changes should be made in the schema definitions or custom code files to ensure they persist across regenerations.
28-32: Consider verifying nullable vs. zero-value usage for DeletedAt.Storing
DeletedAtas a pointer is correct for soft-deletion semantics, but ensure your queries or business logic handle both non-nil and nil states consistently.
39-48: Eager-loading correctness.Edges for
CustomerAppsandAppare eagerly loaded based on type checks inloadedTypes. Confirm that this is aligned with your business requirements (e.g., partial loading vs. full loading).openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (2)
65-73: Validator usage check.Validators
NamespaceValidator,AppIDValidator, andCustomerIDValidatorshould be set before build time. Confirm they are properly defined and tested in your code to ensure data integrity.
128-133: Validate ordering relationships.Methods like
ByCustomInvoicingAppFieldandByCustomerFieldrely on correct edge definitions. Double-check that these match the actual relationships in the schema, especially if you require different ordering criteria or constraints.openmeter/ent/db/appcustominvoicingcustomer_update.go (3)
112-117: Required unique edges constraints.Clearing a required unique edge while also setting it to another value can lead to logical conflicts. The checks here are good, but ensure that external callers handle these errors gracefully.
57-67: Conditional clearing vs. setting fields.
SetMetadataandClearMetadatalet you toggle the JSON field. Ensure that partial updates or merges are handled in the application layer if needed.
274-279: Validation for missing ID.Returning an error when
idis not provided is correct. Ensure that any code path callingUpdateOnesets the mandatory ID or gracefully handles a missing ID scenario.openmeter/ent/db/appcustominvoicing_query.go (3)
22-35: Well-structured query builder initialization
All fields and references appear consistent. No major improvements needed.
112-123:Firstmethod
Usage of a limit of 1 and returning aNotFoundErroris appropriate for retrieving a single record.
603-614: ForUpdate usage
Row-level locking looks correct. Confirm that your database dialect fully supports these row locks if you plan to switch from Postgres.openmeter/ent/db/appcustominvoicingcustomer_query.go (4)
21-34: Definition ofAppCustomInvoicingCustomerQuery
This struct’s fields and overall design adhere to Ent’s query builder patterns.
111-122:Firstmethod
The early return on no results usingNotFoundErroris correctly implemented.
604-615: ForUpdate locking
Ent’s row-level locking is properly handled. If non-Postgres dialects are in use, confirm lock behavior.
652-676: GroupBy aggregator
Aggregations and grouping logic conform to Ent norms. No issues noted.openmeter/ent/db/appcustominvoicing_update.go (6)
19-24: Definition ofAppCustomInvoicingUpdate
Holds mutation state and hooks, consistent with Ent’s typical update pattern.
26-31:Wheremethod
Adds predicates for selective updating. Straightforward and well-implemented.
32-50: Set/Clear “deleted_at”
Optional timestamp handling looks standard. These convenience methods match Ent best practices.
86-100:AddCustomerAppslogic
Accumulates foreign key IDs for thecustomer_appsedge. Ensure validity of these references if they come from external inputs.
127-140:Savemethod
Applies default values forupdated_atprior to persistence. This ensures consistent timestamps.
397-495:sqlSaveimplementation
Executes core update logic, including handling edges forcustomer_apps. Typical of Ent’s auto-generated code, and appears correct.openmeter/ent/db/client.go (13)
22-23: Imports properly added for the new custom invoicing entities.The two new imports for the custom invoicing database entities are properly added. These imports allow the client.go file to reference the schema definitions and types for the new entities.
76-79: New client fields correctly added to main Client struct.The struct additions for the new custom invoicing entities follow the established pattern in the codebase. The documentation comments are also properly formatted and descriptive of the purpose of each client.
170-171: Client initialization properly implemented.The initialization of the new clients in the
initmethod follows the consistent pattern used for other entity clients. This ensures the clients are ready to use immediately after creating a new Client instance.
305-306: Transaction support correctly implemented for new entities.The new entity clients are properly included in both transaction methods (
TxandBeginTx), ensuring transactional consistency when working with these new entities.Also applies to: 367-368
436-448: Hook and interceptor support properly implemented.The code correctly adds the new entity clients to the slice of interfaces that receive hooks and interceptors. The restructured layout improves readability while maintaining the functionality.
Also applies to: 458-470
485-488: Mutation handling properly implemented for new entities.The mutation switch statement includes the new mutation types, allowing the main Client to route mutations to the appropriate entity client for processing.
1177-1340: AppCustomInvoicingClient implementation is complete and follows established patterns.The implementation includes all necessary methods for CRUD operations, query building, hooks, interceptors, and relationships. This follows the consistent pattern used throughout the codebase for entity clients.
1342-1505: AppCustomInvoicingCustomerClient implementation is complete and follows established patterns.This client correctly implements all the required methods and relationship queries. The relationship between customers and the custom invoicing app is properly established through the query methods.
8020-8037: Hooks and interceptors structs properly updated.The hooks and interceptors structs are correctly updated to include fields for the new entity types, ensuring that hooks and interceptors can be applied specifically to the new entities.
1285-1315: Relationship between AppCustomInvoicing and AppCustomInvoicingCustomer properly defined.The
QueryCustomerAppsmethod correctly implements the relationship query from the custom invoicing app to its associated customers. This allows for efficient querying of customer-specific settings for a custom invoicing app.
1449-1480: Bidirectional relationship between Customer and AppCustomInvoicing properly implemented.The
QueryCustomInvoicingAppandQueryCustomermethods establish the bidirectional relationship between customers and the custom invoicing app, allowing for navigation from either direction.
1301-1315: Application relationship properly established.The
QueryAppmethod correctly establishes the relationship between the custom invoicing entity and the underlying app entity, allowing for access to general app properties from the custom invoicing context.
1-8074: Overall assessment of generated code changes.The changes to client.go properly integrate the new custom invoicing entities into the Ent client framework. The code is machine-generated and follows the established patterns consistently throughout. The changes align perfectly with the PR description of adding database structures for custom invoicing, with specific tables for customer metadata and application options.
Since this is generated code, the focus should be on ensuring the schema definitions are correctly designed, but the generated client code itself is correct and complete.
openmeter/ent/db/appcustominvoicing_create.go (5)
1-26: Auto-generated builder and configuration appear standard.This block provides the type definition, imports, and basic struct setup reflecting typical Ent patterns. No issues spotted here.
27-120: Well-structured setter methods for all fields and edges.All setters, including the nillable variants, follow Ent best practices. The approach for ensuring required fields and optional fields is clean and unambiguous.
157-207: Save logic and defaults are correct.The
defaults()method ensures required timestamps and boolean fields are set properly before persistence. The usage of hooks,SaveX(), and panics are consistent with Ent’s patterns.
209-232: Validation checks ensure required fields and edges.The
check()function ensures thenamespace,created_at,updated_at, and other fields are validated, reducing the risk of partially valid records.
234-583: Upsert logic and conflict handling.The various
OnConflicthelpers and bulk creation paths provide flexible insert-or-update handling. This is standard Ent code, and everything looks consistent.openmeter/ent/db/appcustominvoicingcustomer_create.go (7)
1-26: Standard Ent scaffolding.Similar structure as the other create builder. All required imports and struct definitions are in place with no issues.
27-116: Field setters are consistent with the schema.Setters for timestamps,
metadata, and IDs match expected usage. Good incorporation of nillable fields.
142-152: Defaulting logic.This ensures
created_atandupdated_atare set if not explicitly provided. Typical pattern.
154-193: Validation checking for required fields and edges.The presence of
namespace,app_id,customer_id, and edges is enforced, preventing orphan records or incomplete data.
195-281: SQL insertion and specification logic.No irregularities in how the node is created, assigned an ID, or in how edges are set.
312-424: Upsert handling.Well-structured approach to conflict resolution. The usage of
UpdateNewValues, among others, covers typical upsert scenarios.
516-604: Bulk creation logic implemented correctly.The loop populates create specs and executes
BatchCreatewith consistent error handling. Looks solid for large-scale inserts.openmeter/ent/db/appcustominvoicing/where.go (1)
1-373: Comprehensive predicate definitions.These predicates cover all possible filter operations, including edge-based checks. This is standard Ent code enabling flexible queries.
openmeter/ent/db/appcustominvoicingcustomer/where.go (9)
1-2: Properly marked as generated code.The file correctly includes the comment indicating it's generated by ent and should not be edited manually, following best practices for generated code.
5-11: Appropriate imports for Ent ORM framework.The imports include all necessary packages for SQL operations, graph relationships, and time handling which are required for the predicate functions. This aligns with the Ent framework's expected structure.
13-56: Complete ID field predicates implemented correctly.The code properly implements all standard predicates for the ID field including equality, inequality, collections, and comparisons, providing a comprehensive query interface for this primary key field.
273-281: Proper handling of soft delete with nullable field.The implementation includes
DeletedAtIsNilandDeletedAtNotNilpredicates, indicating this entity supports soft deletion, which is a good practice for data retention and recovery.
413-421: Metadata field implemented as nullable.The
MetadataIsNilandMetadataNotNilpredicates indicate that the metadata field is optional, which provides flexibility for storing additional customer-specific information when needed.
423-444: M2O relationship to AppCustomInvoicing properly defined.The edge predicates for
custom_invoicing_appcorrectly implement a many-to-one relationship (M2O) with appropriate neighbor filtering capabilities, allowing queries to traverse the relationship graph.
446-467: M2O relationship to Customer properly defined.The edge predicates for
customerare correctly implemented as a many-to-one relationship, providing the ability to query entities based on their associated customer properties.
469-482: Logical combinators for complex query composition.The implementation provides
And,Or, andNotfunctions for combining predicates, which enables the construction of complex queries with compound conditions - essential for flexible data filtering.
1-483:Details
❓ Verification inconclusive
Verify the entity schema design and foreign key constraints.
The code correctly implements predicates for the
AppCustomInvoicingCustomerentity which appears to be a join table betweenAppCustomInvoicingandCustomerentities. Ensure that your database schema has appropriate foreign key constraints and indexes for these relationships to maintain data integrity and query performance.To verify the relationship design and constraints, you might want to check:
🏁 Script executed:
#!/bin/bash # Verify schema definitions and migrations for the related entities echo "Checking schema definitions for AppCustomInvoicingCustomer and related entities:" fd "appcustominvoicing.*schema\\.go" | xargs cat echo -e "\nChecking migration files:" fd ".*custom_invoicing.*\\.sql" | xargs catLength of output: 332
Action: Verify entity schema design and related migration files manually.
The generated predicates in the file appear to correctly implement the filtering functions expected by the Ent framework for the
AppCustomInvoicingCustomerentity. However, the automated schema and migration file search did not return any files. Please ensure that:
- The database schema correctly defines foreign key constraints and indexes for the relationships between
AppCustomInvoicingCustomer,AppCustomInvoicing, andCustomer.- The expected schema and migration files are using the appropriate naming conventions or are located in a different directory that wasn’t captured by the script.
Confirm that these elements are in place to maintain data integrity and query performance.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (6)
tools/migrate/migrations/20250416121718_app-custominvoicing.up.sql (2)
13-16: Index naming consistencyThe indexes
appcustominvoicing_idandappcustominvoicing_namespaceare readable, but verify they match your desired naming conventions (e.g.,idx_app_custom_invoicings_id) for uniformity across the schema.
17-35: Consider single-column indexing for common queriesThis migration defines a composite unique index
(namespace, app_id, customer_id). If queries frequently filter only oncustomer_id, you may benefit from an additional standalone index oncustomer_idto improve performance.openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (1)
128-155: Add tests for edge-case orderingThe ordering utilities (e.g.,
ByCustomInvoicingAppField) help with advanced sorting. Consider adding unit or integration tests to confirm they behave as expected with various edge cases.openmeter/ent/db/appcustominvoicingcustomer_create.go (3)
114-127: Potential panics in production
SaveXandExecXpanic on failure, which can be suitable for development but risky for production code. Consider usingSaveandExecwith proper error handling paths in critical systems.
142-152: Default timestamps approach
defaults()setscreated_atandupdated_atusing application time. Verify if the time source should be your application or database. Relying on DB defaults can sometimes yield more consistent audit logs.
606-692: Conflict resolution in bulk creation
OnConflicthandling with bulk inserts is powerful. Confirm the bulk conflict resolution strategy (e.g., ignoring duplicates or updating fields) is consistent with your business requirements for(namespace, app_id, customer_id)collisions.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
tools/migrate/migrations/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (9)
openmeter/ent/db/appcustominvoicingcustomer.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer/where.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer_create.go(1 hunks)openmeter/ent/db/migrate/schema.go(3 hunks)openmeter/ent/db/mutation.go(3 hunks)openmeter/ent/schema/appcustominvoicing.go(1 hunks)tools/migrate/migrations/20250416121718_app-custominvoicing.down.sql(1 hunks)tools/migrate/migrations/20250416121718_app-custominvoicing.up.sql(1 hunks)
✅ Files skipped from review due to trivial changes (2)
- tools/migrate/migrations/20250416121718_app-custominvoicing.down.sql
- openmeter/ent/db/appcustominvoicingcustomer.go
🚧 Files skipped from review as they are similar to previous changes (3)
- openmeter/ent/schema/appcustominvoicing.go
- openmeter/ent/db/migrate/schema.go
- openmeter/ent/db/appcustominvoicingcustomer/where.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (1)
openmeter/ent/db/appcustominvoicing/appcustominvoicing.go (14)
FieldID(16-16)FieldNamespace(18-18)FieldCreatedAt(20-20)FieldUpdatedAt(22-22)FieldDeletedAt(24-24)ValidColumn(63-70)Columns(52-60)ByID(93-95)OrderOption(90-90)ByNamespace(98-100)ByCreatedAt(103-105)ByUpdatedAt(108-110)ByDeletedAt(113-115)Table(34-34)
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: CI
- GitHub Check: Quickstart
- GitHub Check: E2E
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Test
- GitHub Check: Lint
- GitHub Check: Build
- GitHub Check: Analyze (go)
🔇 Additional comments (9)
openmeter/ent/db/mutation.go (4)
20-27: New entity imports added correctlyThe code adds imports for the new
appcustominvoicingandappcustominvoicingcustomerpackages, which is consistent with the PR objective of introducing custom invoicing database structures.
80-87: Type constants correctly definedThe addition of type constants for the new entities follows the existing pattern in the codebase and will allow proper type identification within the ORM framework.
4627-5401: Well-structured AppCustomInvoicing mutation implementationThe
AppCustomInvoicingMutationimplementation is comprehensive and follows the Ent framework patterns correctly. It provides complete CRUD operation support with proper field management, edge handling, transaction support, and predicate filtering. The implementation correctly handles the entity's fields (namespace, timestamps, hook flags) and relationships (customer_apps, app).
5403-6206: Well-structured AppCustomInvoicingCustomer mutation implementationThe
AppCustomInvoicingCustomerMutationimplementation is properly structured according to Ent framework patterns. It provides comprehensive mutation operations for the customer entity, including metadata management which aligns with the PR objective of "a Customer table designed to store application-specific metadata." The relationship mappings to both theAppCustomInvoicingentity and the baseCustomerentity are correctly established.tools/migrate/migrations/20250416121718_app-custominvoicing.up.sql (1)
1-12: Ensure referencing the correct table for foreign constraintsThe
app_custom_invoicingstable referencesapps(id)usingid character(26). Double-check the schema of theappstable to confirm it aligns with a 26-character ID and that this foreign key usage is indeed correct.openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (2)
1-15: Respect auto-generated codeThis file is automatically generated by Ent. Avoid directly editing it because changes will be overridden. For custom logic or validations, place them in the Ent schema definitions or custom hooks.
53-63: Columns slice alignmentThe
Columnsslice matches the field constants, ensuring runtime validation. Double-check there's no frequently accessed or newly added field missing from this slice if the schema evolves further.openmeter/ent/db/appcustominvoicingcustomer_create.go (2)
19-25: Builder pattern usage
AppCustomInvoicingCustomerCreatefollows Ent’s canonical builder approach. Ensure that any supplemental validations or hooks are declared in your schema or hooks to maintain correctness during entity creation.
195-211: ID type consistency checkThis creation logic uses a
bigintlogic for the primaryid, while other tables may store a 26-character key. Confirm that this discrepancy between integer and character-based IDs is intentional and will not cause integration issues.
b16020e to
df46851
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (6)
tools/migrate/migrations/20250416191201_app-custominvoicing.up.sql (3)
13-16: Remove redundant unique index onidand align naming
By default, the primary key (id) already creates a unique index. This explicitCREATE UNIQUE INDEX "appcustominvoicing_id"is redundant and can be safely removed to reduce clutter. Additionally, if you keep it, consider renaming to follow a consistentidx_<table>_<column>pattern.- CREATE UNIQUE INDEX "appcustominvoicing_id" ON "app_custom_invoicings" ("id");
17-30: Shorten foreign key constraint names and set JSONB defaults
The FK constraint names exceed 63 characters and risk being truncated by PostgreSQL. Consider using concise names (e.g.,fk_app_invoice_cust_appandfk_app_invoice_cust_customer). Also, if your application frequently readsmetadata, you may want to default it to an empty JSON object (DEFAULT '{}') and mark it non-null to simplify queries and code.CREATE TABLE "app_custom_invoicing_customers" ( "id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "namespace" character varying NOT NULL, "created_at" timestamptz NOT NULL, "updated_at" timestamptz NOT NULL, - "deleted_at" timestamptz NULL, - "metadata" jsonb NULL, + "deleted_at" timestamptz NULL, + "metadata" jsonb DEFAULT '{}' NOT NULL, "app_id" character(26) NOT NULL, "customer_id" character(26) NOT NULL, PRIMARY KEY ("id"), - CONSTRAINT "app_custom_invoicing_customers_app_custom_invoicings_customer_a" FOREIGN KEY ("app_id") REFERENCES "app_custom_invoicings" ("id") ON UPDATE NO ACTION ON DELETE CASCADE, - CONSTRAINT "app_custom_invoicing_customers_customers_customer" FOREIGN KEY ("customer_id") REFERENCES "customers" ("id") ON UPDATE NO ACTION ON DELETE CASCADE + CONSTRAINT "fk_app_invoice_cust_app" FOREIGN KEY ("app_id") REFERENCES "app_custom_invoicings" ("id") ON DELETE CASCADE, + CONSTRAINT "fk_app_invoice_cust_customer" FOREIGN KEY ("customer_id") REFERENCES "customers" ("id") ON DELETE CASCADE );
31-34: Improve index naming and consider additional indexes
Rename indexes to match theidx_<table>_<columns>convention and ensure query performance for common access patterns. For example, if you often query byapp_idalone (across namespaces), consider adding an index on that column.- CREATE INDEX "appcustominvoicingcustomer_namespace" ON "app_custom_invoicing_customers" ("namespace"); - CREATE UNIQUE INDEX "appcustominvoicingcustomer_namespace_app_id_customer_id" ON "app_custom_invoicing_customers" ("namespace", "app_id", "customer_id"); + CREATE INDEX "idx_app_custom_invoicing_customers_namespace" ON "app_custom_invoicing_customers" ("namespace"); + CREATE UNIQUE INDEX "ux_app_custom_invoicing_customers_namespace_app_id_customer_id" ON "app_custom_invoicing_customers" ("namespace", "app_id", "customer_id"); + CREATE INDEX "idx_app_custom_invoicing_customers_app_id" ON "app_custom_invoicing_customers" ("app_id");openmeter/ent/db/appcustominvoicing_query.go (1)
476-484: Minor: slice variable shadowing hampers readabilityInside the loop the identifier
nodesis re‑used:for _, n := range neighbors { nodes, ok := nodeids[n.ID] // shadows outer sliceShadowing a slice with a map entry makes the code harder to follow.
Consider renaming the inner variable (owners,mapped) to avoid confusion.openmeter/ent/db/appcustominvoicingcustomer_query.go (1)
452-478: Variable shadowing in eager‑loader
nodesis re‑declared inside the neighbour loop, shadowing the outer slice just like inappcustominvoicing_query.go.
While harmless, renaming improves clarity and prevents accidental misuse.openmeter/ent/db/appcustominvoicing_update.go (1)
347-351: Doc‑string mismatch references wrong builderThe comment says “appends a list predicates to the AppCustomInvoicingUpdate builder” but this method belongs to the UpdateOne builder.
Tiny, but worth correcting to keep IntelliSense / generated docs accurate.-// Where appends a list predicates to the AppCustomInvoicingUpdate builder. +// Where appends predicates to the AppCustomInvoicingUpdateOne builder.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
tools/migrate/migrations/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (28)
openmeter/ent/db/appcustominvoicing.go(1 hunks)openmeter/ent/db/appcustominvoicing/appcustominvoicing.go(1 hunks)openmeter/ent/db/appcustominvoicing/where.go(1 hunks)openmeter/ent/db/appcustominvoicing_create.go(1 hunks)openmeter/ent/db/appcustominvoicing_delete.go(1 hunks)openmeter/ent/db/appcustominvoicing_query.go(1 hunks)openmeter/ent/db/appcustominvoicing_update.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer/where.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer_create.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer_delete.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer_query.go(1 hunks)openmeter/ent/db/appcustominvoicingcustomer_update.go(1 hunks)openmeter/ent/db/client.go(11 hunks)openmeter/ent/db/ent.go(2 hunks)openmeter/ent/db/expose.go(1 hunks)openmeter/ent/db/hook/hook.go(1 hunks)openmeter/ent/db/migrate/schema.go(3 hunks)openmeter/ent/db/mutation.go(3 hunks)openmeter/ent/db/paginate.go(1 hunks)openmeter/ent/db/predicate/predicate.go(1 hunks)openmeter/ent/db/runtime.go(2 hunks)openmeter/ent/db/setorclear.go(1 hunks)openmeter/ent/db/tx.go(2 hunks)openmeter/ent/schema/appcustominvoicing.go(1 hunks)tools/migrate/migrations/20250416191201_app-custominvoicing.down.sql(1 hunks)tools/migrate/migrations/20250416191201_app-custominvoicing.up.sql(1 hunks)
✅ Files skipped from review due to trivial changes (6)
- tools/migrate/migrations/20250416191201_app-custominvoicing.down.sql
- openmeter/ent/db/predicate/predicate.go
- openmeter/ent/db/runtime.go
- openmeter/ent/db/appcustominvoicing.go
- openmeter/ent/db/appcustominvoicing/appcustominvoicing.go
- openmeter/ent/db/appcustominvoicingcustomer_update.go
🚧 Files skipped from review as they are similar to previous changes (14)
- openmeter/ent/db/expose.go
- openmeter/ent/db/ent.go
- openmeter/ent/db/tx.go
- openmeter/ent/db/hook/hook.go
- openmeter/ent/db/paginate.go
- openmeter/ent/db/appcustominvoicingcustomer_delete.go
- openmeter/ent/schema/appcustominvoicing.go
- openmeter/ent/db/appcustominvoicing_delete.go
- openmeter/ent/db/appcustominvoicingcustomer.go
- openmeter/ent/db/migrate/schema.go
- openmeter/ent/db/setorclear.go
- openmeter/ent/db/appcustominvoicingcustomer_create.go
- openmeter/ent/db/appcustominvoicing/where.go
- openmeter/ent/db/appcustominvoicingcustomer/where.go
🧰 Additional context used
🧬 Code Graph Analysis (2)
openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (1)
openmeter/ent/db/appcustominvoicing/appcustominvoicing.go (14)
FieldID(16-16)FieldNamespace(18-18)FieldCreatedAt(20-20)FieldUpdatedAt(22-22)FieldDeletedAt(24-24)ValidColumn(63-70)Columns(52-60)ByID(93-95)OrderOption(90-90)ByNamespace(98-100)ByCreatedAt(103-105)ByUpdatedAt(108-110)ByDeletedAt(113-115)Table(34-34)
openmeter/ent/db/appcustominvoicing_update.go (10)
openmeter/ent/db/ent.go (7)
Hook(64-64)Mutation(76-76)NotFoundError(280-282)IsConstraintError(363-369)ConstraintError(347-350)ValidationError(255-258)Value(65-65)openmeter/ent/db/mutation.go (1)
AppCustomInvoicingMutation(4539-4559)openmeter/ent/schema/appcustominvoicing.go (10)
AppCustomInvoicing(15-17)AppCustomInvoicing(19-25)AppCustomInvoicing(27-32)AppCustomInvoicing(34-36)AppCustomInvoicing(38-49)AppCustomInvoicingCustomer(52-54)AppCustomInvoicingCustomer(56-62)AppCustomInvoicingCustomer(64-73)AppCustomInvoicingCustomer(75-80)AppCustomInvoicingCustomer(82-101)openmeter/ent/db/appcustominvoicing.go (2)
AppCustomInvoicing(17-37)AppCustomInvoicing(71-86)openmeter/ent/db/predicate/predicate.go (2)
AppCustomInvoicing(41-41)AppCustomInvoicingCustomer(44-44)openmeter/ent/db/appcustominvoicingcustomer.go (2)
AppCustomInvoicingCustomer(19-41)AppCustomInvoicingCustomer(77-94)openmeter/ent/db/appcustominvoicingcustomer/where.go (3)
ID(14-16)UpdatedAt(69-71)DeletedAt(74-76)openmeter/ent/db/appcustominvoicing/where.go (5)
ID(14-16)UpdatedAt(79-81)DeletedAt(84-86)SkipDraftSyncHook(89-91)SkipIssuingSyncHook(94-96)openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (8)
UpdateDefaultUpdatedAt(83-83)Table(36-36)Columns(54-63)FieldID(16-16)FieldUpdatedAt(22-22)FieldDeletedAt(24-24)Label(14-14)ValidColumn(66-73)openmeter/ent/db/appcustominvoicing/appcustominvoicing.go (12)
UpdateDefaultUpdatedAt(80-80)Table(34-34)Columns(52-60)FieldID(16-16)FieldUpdatedAt(22-22)FieldDeletedAt(24-24)FieldSkipDraftSyncHook(26-26)FieldSkipIssuingSyncHook(28-28)CustomerAppsTable(36-36)CustomerAppsColumn(41-41)Label(14-14)ValidColumn(63-70)
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: E2E
- GitHub Check: CI
- GitHub Check: Quickstart
- GitHub Check: Lint
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Test
- GitHub Check: Build
- GitHub Check: Analyze (go)
🔇 Additional comments (27)
tools/migrate/migrations/20250416191201_app-custominvoicing.up.sql (1)
1-12: Confirm primary table schema and constraints
Theapp_custom_invoicingstable definition, including primary key, timestamps, nullabledeleted_at, and cascade delete on theappsFK, aligns with the Ent schema and existing patterns.openmeter/ent/db/mutation.go (3)
23-24: LGTM - Import statements for new entity typesThe imports for the new
appcustominvoicingandappcustominvoicingcustomerpackages follow the existing pattern and are correctly placed within the import block.
81-82: LGTM - Type constants for new entitiesThe type constants for
AppCustomInvoicingandAppCustomInvoicingCustomerfollow the existing naming conventions and are appropriately placed in alphabetical order within the type constants block.
4538-6117: LGTM - Well-structured mutation types for new entitiesThe implementation of
AppCustomInvoicingMutationandAppCustomInvoicingCustomerMutationcorrectly follows the Ent framework patterns for mutation handling. The code includes:
- Complete implementation of the
ent.Mutationinterface- Proper field management (get, set, clear, reset)
- Edge relationship handling
- Comprehensive error handling
- Field and edge tracking for updates
Both implementations align with existing mutation types in the file and provide full CRUD operation support for the new entities.
openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (1)
148-153: Double‑check theinverseflag on the Customer edge
newCustomerStep()registers thecustomeredge withinverse=falseeven though the FK (customer_id) resides on the current table.
In most Ent schemas that meansinverseshould betrue(current table → M2O owner).
A wrong flag silently breaks ordering / filtering through neighbour traversals.openmeter/ent/db/appcustominvoicing_update.go (2)
86-99: Adding edges in a multi‑update can yield ambiguous results
AddCustomerAppIDs/AddCustomerAppsare exposed on the bulk update builder, yet the underlying SQL spec assumes a singleapp_id(it takes the primary‑key of each matchedAppCustomInvoicingrow and updates the FK on every targeted customer row).If the
WHEREclause matches more than oneAppCustomInvoicingrecord, every selectedcustomer_approw will be reassigned once per source row, producing unexpected fan‑out or constraint violations.Consider:
- Restricting
AddCustomerApp*helpers toUpdateOneonly; or- Guarding with
if len(ids) > 1and returning aValidationError.Also applies to: 200-231
155-161:Details
❌ Incorrect review comment
Ensure
UpdateDefaultUpdatedAtis initialised to avoid panics
defaults()blindly calls the function pointerappcustominvoicing.UpdateDefaultUpdatedAt()whenUpdatedAtis unset.
If this variable is not initialised (i.e.nil) anywhere in runtime‑initialisation code, the first update executed through this builder will trigger anil pointer dereferencepanic.If the grep returns nothing, add an initialiser (e.g. in
runtime.go) similar to:appcustominvoicing.UpdateDefaultUpdatedAt = func() time.Time { return time.Now().UTC() }
🏁 Script executed:
#!/bin/bash # Verify that the default hook is set somewhere in the generated / handwritten code. rg --line-number "UpdateDefaultUpdatedAt\s*=" | headLength of output: 1399
No panic risk:
UpdateDefaultUpdatedAtis already initializedVerification shows that
appcustominvoicing.UpdateDefaultUpdatedAtis assigned inopenmeter/ent/db/runtime.go(line 193), ensuring it’s never nil beforedefaults()is called. No changes are necessary.Likely an incorrect or invalid review comment.
openmeter/ent/db/client.go (11)
22-23: New imports for custom invoicing entities properly added.These imports provide access to the new entity packages that were created for the custom invoicing feature.
74-77: New client fields properly integrated into the main Client struct.The AppCustomInvoicing and AppCustomInvoicingCustomer clients are correctly declared with appropriate documentation comments, matching the pattern used for other entity clients.
164-165: Client initialization correctly implemented in init() method.The new clients are properly initialized, maintaining consistency with the existing pattern for client initialization.
297-298: Transaction support properly implemented for new entities.The clients are correctly initialized in both transaction methods (Tx and BeginTx), ensuring transactional operations will work with the new entities.
Also applies to: 357-358
424-436: Hook and interceptor integration complete and correctly implemented.The new entities are properly included in the hooks and interceptors list, maintaining good formatting with appropriate line breaks to keep line lengths reasonable.
Also applies to: 445-457
471-474: Mutation support properly added for new entities.The Mutate method is correctly extended to handle mutations for the new entity types, following the established pattern for other entities.
1143-1306: AppCustomInvoicingClient implementation is comprehensive and follows established patterns.The implementation includes all necessary methods (CRUD operations, query builders, hooks, interceptors) and maintains consistency with other client implementations. The entity relationships are properly defined, showing that AppCustomInvoicing has connections to both App entities and AppCustomInvoicingCustomer entities.
1308-1471: AppCustomInvoicingCustomerClient implementation is complete and consistent.The implementation includes all required methods and correctly establishes relationships with both AppCustomInvoicing and Customer entities, enabling the many-to-many relationship between Apps and Customers through the custom invoicing feature.
7608-7609: Hooks and interceptors structures properly updated.The hooks and interceptors structs correctly include the new entities, maintaining good formatting and alphabetical order.
Also applies to: 7622-7623
1251-1265: Query methods properly implement relationship navigation.The QueryCustomerApps and QueryCustomInvoicingApp/QueryCustomer methods correctly implement bidirectional navigation between the related entities, allowing for efficient query building across the relationships.
Also applies to: 1416-1446
1293-1305: Mutation methods properly implemented for both entities.The mutate methods correctly handle all operation types (Create, Update, UpdateOne, Delete/DeleteOne) and return appropriate builders, ensuring complete CRUD functionality for the new entities.
Also applies to: 1458-1470
openmeter/ent/db/appcustominvoicing_create.go (9)
1-2: Auto-generated code notation presentThis file is auto-generated by the Ent framework. It should not be manually modified as noted in the header comment.
20-26: Implementation follows Ent framework's builder patternThis is a standard Ent builder implementation for creating AppCustomInvoicing entities. The struct includes configuration, mutation state tracking, hooks, and conflict resolution options.
28-116: Well-structured field setters follow Ent patternsThe implementation provides both direct setters and nullable variants for all fields including:
- namespace (string)
- timestamps (created_at, updated_at, deleted_at)
- boolean flags (skip_draft_sync_hook, skip_issuing_sync_hook)
- entity ID
This adheres to the Ent framework's fluent builder pattern.
118-150: Relationship setters properly handle entity associationsThe code provides methods for:
- Setting one-to-many relationships with AppCustomInvoicingCustomer entities
- Setting many-to-one relationship with the App entity
These relationship setters follow the standard Ent pattern.
185-207: Default values are properly initializedThe
defaults()method ensures all required fields have reasonable defaults:
- Timestamps are set to current time
- Boolean flags have appropriate defaults
- ID gets a default value (likely a UUID)
This ensures entities are always created with valid initial state.
209-232: Validation logic ensures data integrityThe
check()method properly validates:
- Required fields are present
- Field-specific validators are applied (e.g., namespace validation)
This prevents invalid entities from being persisted to the database.
291-306: One-to-many relationship mapping correctly definedThe customer_apps relationship is properly configured as a one-to-many relationship (O2M) without bidirectionality, targeting the AppCustomInvoicingCustomer entity.
307-323: Many-to-one relationship with App entity properly configuredThe app relationship is correctly defined as a many-to-one (M2O) relationship. The code properly sets up the foreign key and target specification.
585-852: Bulk operations with proper transaction supportThe bulk create and upsert operations follow Ent's pattern for efficient batch processing with:
- Proper error handling
- Hook execution
- Transaction management
- Conflict resolution strategies
This enables efficient batch operations for the AppCustomInvoicing entity.
Overview
Tables:
Summary by CodeRabbit