Skip to content

feat: custominvoicing db struct - #2679

Merged
turip merged 3 commits into
mainfrom
feat/custominvoicing-db-struct
Apr 16, 2025
Merged

turip merged 3 commits into
mainfrom
feat/custominvoicing-db-struct

Conversation

@turip

@turip turip commented Apr 16, 2025 •

Copy link
Copy Markdown
Member

Overview

Tables:

  • Customer table: to store app specific metadata
  • App table: to store app options

Summary by CodeRabbit

  • New Features
    • Introduced support for custom invoicing at the application level, including management of custom invoicing records and associated customers.
    • Added database tables and APIs for handling custom invoicing configurations and customer relationships.
    • Enabled creation, querying, updating, and deletion of custom invoicing entries and their associated customers.
    • Added pagination, filtering, and ordering capabilities for custom invoicing data.
  • Chores
    • Updated database schema and migration scripts to support new custom invoicing features.
    • Extended administrative and developer tools to manage new entities.

@turip
turip requested a review from a team as a code owner April 16, 2025 12:10
@coderabbitai

coderabbitai Bot commented Apr 16, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change introduces two new entities, AppCustomInvoicing and AppCustomInvoicingCustomer, to the codebase. It adds their schema definitions, migration scripts for table creation and removal, and full ORM support using the Ent framework. This includes entity models, mutation types, CRUD builders (create, update, delete, query), predicates, ordering, and pagination. The database client, transactional client, runtime, and hook systems are extended to support these entities. The migration scripts define the required tables, foreign keys, and indexes. All changes follow established patterns for Ent-based entity management and integrate with the existing application structure.

Changes

File(s) Change Summary
openmeter/ent/schema/appcustominvoicing.go Adds Ent schema definitions for AppCustomInvoicing and AppCustomInvoicingCustomer entities, including fields, edges, and indexes.
openmeter/ent/db/migrate/schema.go
tools/migrate/migrations/20250416191201_app-custominvoicing.up.sql
tools/migrate/migrations/20250416191201_app-custominvoicing.down.sql
Adds migration scripts and schema definitions for app_custom_invoicings and app_custom_invoicing_customers tables, including columns, indexes, and foreign key relationships. The down migration drops these tables and their indexes.
openmeter/ent/db/appcustominvoicing.go
openmeter/ent/db/appcustominvoicingcustomer.go
Adds Ent entity model structs for AppCustomInvoicing and AppCustomInvoicingCustomer, including fields, edges, scanning, assignment, query/update helpers, and stringers.
openmeter/ent/db/appcustominvoicing/appcustominvoicing.go
openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go
Adds schema constants, field/edge names, validators, default value functions, and ordering utilities for the new entities.
openmeter/ent/db/appcustominvoicing/where.go
openmeter/ent/db/appcustominvoicingcustomer/where.go
Adds comprehensive predicate functions for filtering/querying AppCustomInvoicing and AppCustomInvoicingCustomer entities, including field/edge predicates and logical combinators.
openmeter/ent/db/appcustominvoicing_create.go
openmeter/ent/db/appcustominvoicingcustomer_create.go
Implements builder patterns for creating and upserting the new entities, with support for field/edge setting, validation, defaulting, conflict handling, and bulk operations.
openmeter/ent/db/appcustominvoicing_update.go
openmeter/ent/db/appcustominvoicingcustomer_update.go
Implements update builders for the new entities, supporting field/edge updates, clearing, predicates, hooks, and error handling.
openmeter/ent/db/appcustominvoicing_delete.go
openmeter/ent/db/appcustominvoicingcustomer_delete.go
Implements deletion builders for the new entities, supporting predicate-based and single-entity deletion with error handling and hooks.
openmeter/ent/db/appcustominvoicing_query.go
openmeter/ent/db/appcustominvoicingcustomer_query.go
Implements query builders for the new entities, supporting filtering, ordering, pagination, eager loading of edges, group-by, select, and locking.
openmeter/ent/db/client.go Adds AppCustomInvoicingClient and AppCustomInvoicingCustomerClient to the main database client, with full CRUD/query methods, edge queries, hooks, and interceptors. Updates mutation dispatch to handle new entities.
openmeter/ent/db/ent.go Adds imports for new entity packages and extends the column validation map for the new tables.
openmeter/ent/db/expose.go Adds AppCustomInvoicing and AppCustomInvoicingCustomer fields to the transactional client struct.
openmeter/ent/db/hook/hook.go Adds function adapter types for mutation hooks for the new entities.
openmeter/ent/db/mutation.go Adds mutation types for AppCustomInvoicing and AppCustomInvoicingCustomer, supporting field/edge mutation tracking, old value retrieval, and predicate-based ID querying.
openmeter/ent/db/paginate.go Adds Paginate methods for the new entity queries, implementing the pagination interface and supporting paged responses.
openmeter/ent/db/predicate/predicate.go Adds new predicate function types for the new entities.
openmeter/ent/db/runtime.go Adds runtime initialization for the new entities, including field validators and default value functions.
openmeter/ent/db/setorclear.go Adds SetOrClearDeletedAt and SetOrClearMetadata methods for the new entity update types, supporting conditional field clearing/setting.
openmeter/ent/db/tx.go Adds transactional client fields and initialization for the new entities.

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
Failed executing command with 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.sql

User Error: No dialect was specified. You must configure a dialect or specify one on the command line using --dialect after the command. Available dialects:
ansi, athena, bigquery, clickhouse, databricks, db2, duckdb, exasol, greenplum, hive, impala, mariadb, materialize, mysql, oracle, postgres, redshift, snowflake, soql, sparksql, sqlite, starrocks, teradata, trino, tsql, vertica

tools/migrate/migrations/20250416191201_app-custominvoicing.up.sql

User Error: No dialect was specified. You must configure a dialect or specify one on the command line using --dialect after the command. Available dialects:
ansi, athena, bigquery, clickhouse, databricks, db2, duckdb, exasol, greenplum, hive, impala, mariadb, materialize, mysql, oracle, postgres, redshift, snowflake, soql, sparksql, sqlite, starrocks, teradata, trino, tsql, vertica

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@turip turip added the release-note/ignore Ignore this change when generating release notes label Apr 16, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (13)
openmeter/ent/db/paginate.go (1)

156-203: Leverage shared pagination logic.

These new pagination methods for AppCustomInvoicingQuery closely 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 AppCustomInvoicing schema 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 name id here is dual-purposed as both the primary key for app_custom_invoicings and a foreign key to apps. This may be intentional, but it can impede clarity. Consider clarifying or documenting why id references apps.id.


241-283: Check the overlap in naming for app_id.
The column app_id in app_custom_invoicing_customers actually references app_custom_invoicings.id. This might cause confusion if developers assume it points to the apps table. 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, including metadata.

Optional: Trim overly large map output if metadata might 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.

FieldMetadata stores 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 UpdateDefaultUpdatedAt if no explicit UpdatedAt value 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: All method
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: All method
Standard approach for retrieving multiple records. Consider using pagination for scalability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b15c9c9 and 977f9af.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is 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 entities

The import statements correctly include the new packages for AppCustomInvoicing and AppCustomInvoicingCustomer entities.


124-125: Column validation map updated correctly

The 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 entities

The 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 entities

The 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 script

The 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 clients

The 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 method

The 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 AppCustomInvoicingCustomerQuery matches 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 SetOrClearDeletedAt methods for AppCustomInvoicingUpdate and AppCustomInvoicingUpdateOne follow 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 SetOrClearDeletedAt and SetOrClearMetadata to AppCustomInvoicingCustomerUpdate and AppCustomInvoicingCustomerUpdateOne preserves 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 AppCustomInvoicingCustomer entity is well-defined, with careful edge design to avoid conflicting references to the same field. Keeping this entity minimal and referencing customer_id for the customer edge 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 AppCustomInvoicingCustomer entity, 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 AppCustomInvoicing entity, 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 the app_custom_invoicings table 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.
Incorporating AppCustomInvoicingsTable and AppCustomInvoicingCustomersTable into the global slice ensures proper migration ordering.


2498-2500: Confirm foreign key references.
These references tie app_custom_invoicings.id to apps.id and app_custom_invoicing_customers.app_id to app_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 in runtime.go or 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.
Using int for the primary key ensures auto-increment behavior. The AppID and CustomerID are properly typed as strings matching the foreign char(26) columns.


43-74: Edges structure is well-defined.
The separate references to CustomInvoicingApp and Customer edges 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 handle NullString, NullTime, []byte, etc., properly, which mitigates runtime scanning errors. The unmarshal for EAV-like metadata is 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() and QueryCustomer() 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.
AppCustomInvoicingCustomers slice 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 DeletedAt as 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 CustomerApps and App are eagerly loaded based on type checks in loadedTypes. 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, and CustomerIDValidator should 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 ByCustomInvoicingAppField and ByCustomerField rely 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.

SetMetadata and ClearMetadata let 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 id is not provided is correct. Ensure that any code path calling UpdateOne sets 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: First method
Usage of a limit of 1 and returning a NotFoundError is 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 of AppCustomInvoicingCustomerQuery
This struct’s fields and overall design adhere to Ent’s query builder patterns.


111-122: First method
The early return on no results using NotFoundError is 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 of AppCustomInvoicingUpdate
Holds mutation state and hooks, consistent with Ent’s typical update pattern.


26-31: Where method
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: AddCustomerApps logic
Accumulates foreign key IDs for the customer_apps edge. Ensure validity of these references if they come from external inputs.


127-140: Save method
Applies default values for updated_at prior to persistence. This ensures consistent timestamps.


397-495: sqlSave implementation
Executes core update logic, including handling edges for customer_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 init method 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 (Tx and BeginTx), 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 QueryCustomerApps method 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 QueryCustomInvoicingApp and QueryCustomer methods establish the bidirectional relationship between customers and the custom invoicing app, allowing for navigation from either direction.


1301-1315: Application relationship properly established.

The QueryApp method 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 the namespace, 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 OnConflict helpers 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_at and updated_at are 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 BatchCreate with 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 DeletedAtIsNil and DeletedAtNotNil predicates, indicating this entity supports soft deletion, which is a good practice for data retention and recovery.


413-421: Metadata field implemented as nullable.

The MetadataIsNil and MetadataNotNil predicates 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_app correctly 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 customer are 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, and Not functions 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 AppCustomInvoicingCustomer entity which appears to be a join table between AppCustomInvoicing and Customer entities. 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 cat

Length 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 AppCustomInvoicingCustomer entity. 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, and Customer.
  • 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.

tothandras
tothandras previously approved these changes Apr 16, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (6)
tools/migrate/migrations/20250416121718_app-custominvoicing.up.sql (2)

13-16: Index naming consistency

The indexes appcustominvoicing_id and appcustominvoicing_namespace are 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 queries

This migration defines a composite unique index (namespace, app_id, customer_id). If queries frequently filter only on customer_id, you may benefit from an additional standalone index on customer_id to improve performance.

openmeter/ent/db/appcustominvoicingcustomer/appcustominvoicingcustomer.go (1)

128-155: Add tests for edge-case ordering

The 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

SaveX and ExecX panic on failure, which can be suitable for development but risky for production code. Consider using Save and Exec with proper error handling paths in critical systems.


142-152: Default timestamps approach

defaults() sets created_at and updated_at using 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

OnConflict handling 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

📥 Commits

Reviewing files that changed from the base of the PR and between 977f9af and b16020e.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is 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 correctly

The code adds imports for the new appcustominvoicing and appcustominvoicingcustomer packages, which is consistent with the PR objective of introducing custom invoicing database structures.


80-87: Type constants correctly defined

The 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 implementation

The AppCustomInvoicingMutation implementation 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 implementation

The AppCustomInvoicingCustomerMutation implementation 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 the AppCustomInvoicing entity and the base Customer entity are correctly established.

tools/migrate/migrations/20250416121718_app-custominvoicing.up.sql (1)

1-12: Ensure referencing the correct table for foreign constraints

The app_custom_invoicings table references apps(id) using id character(26). Double-check the schema of the apps table 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 code

This 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 alignment

The Columns slice 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

AppCustomInvoicingCustomerCreate follows 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 check

This creation logic uses a bigint logic for the primary id, 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.

@turip
turip force-pushed the feat/custominvoicing-db-struct branch from b16020e to df46851 Compare April 16, 2025 19:14
@turip
turip enabled auto-merge (squash) April 16, 2025 19:17

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (6)
tools/migrate/migrations/20250416191201_app-custominvoicing.up.sql (3)

13-16: Remove redundant unique index on id and align naming
By default, the primary key (id) already creates a unique index. This explicit CREATE UNIQUE INDEX "appcustominvoicing_id" is redundant and can be safely removed to reduce clutter. Additionally, if you keep it, consider renaming to follow a consistent idx_<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_app and fk_app_invoice_cust_customer). Also, if your application frequently reads metadata, 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 the idx_<table>_<columns> convention and ensure query performance for common access patterns. For example, if you often query by app_id alone (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 readability

Inside the loop the identifier nodes is re‑used:

for _, n := range neighbors {
    nodes, ok := nodeids[n.ID] // shadows outer slice

Shadowing 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

nodes is re‑declared inside the neighbour loop, shadowing the outer slice just like in appcustominvoicing_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 builder

The 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

📥 Commits

Reviewing files that changed from the base of the PR and between b16020e and df46851.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is 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
The app_custom_invoicings table definition, including primary key, timestamps, nullable deleted_at, and cascade delete on the apps FK, aligns with the Ent schema and existing patterns.

openmeter/ent/db/mutation.go (3)

23-24: LGTM - Import statements for new entity types

The imports for the new appcustominvoicing and appcustominvoicingcustomer packages follow the existing pattern and are correctly placed within the import block.


81-82: LGTM - Type constants for new entities

The type constants for AppCustomInvoicing and AppCustomInvoicingCustomer follow 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 entities

The implementation of AppCustomInvoicingMutation and AppCustomInvoicingCustomerMutation correctly follows the Ent framework patterns for mutation handling. The code includes:

  1. Complete implementation of the ent.Mutation interface
  2. Proper field management (get, set, clear, reset)
  3. Edge relationship handling
  4. Comprehensive error handling
  5. 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 the inverse flag on the Customer edge

newCustomerStep() registers the customer edge with inverse=false even though the FK (customer_id) resides on the current table.
In most Ent schemas that means inverse should be true (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/AddCustomerApps are exposed on the bulk update builder, yet the underlying SQL spec assumes a single app_id (it takes the primary‑key of each matched AppCustomInvoicing row and updates the FK on every targeted customer row).

If the WHERE clause matches more than one AppCustomInvoicing record, every selected customer_app row will be reassigned once per source row, producing unexpected fan‑out or constraint violations.

Consider:

  1. Restricting AddCustomerApp* helpers to UpdateOne only; or
  2. Guarding with if len(ids) > 1 and returning a ValidationError.

Also applies to: 200-231


155-161:

Details

❌ Incorrect review comment

Ensure UpdateDefaultUpdatedAt is initialised to avoid panics

defaults() blindly calls the function pointer appcustominvoicing.UpdateDefaultUpdatedAt() when UpdatedAt is unset.
If this variable is not initialised (i.e. nil) anywhere in runtime‑initialisation code, the first update executed through this builder will trigger a nil pointer dereference panic.

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*=" | head

Length of output: 1399


No panic risk: UpdateDefaultUpdatedAt is already initialized

Verification shows that appcustominvoicing.UpdateDefaultUpdatedAt is assigned in openmeter/ent/db/runtime.go (line 193), ensuring it’s never nil before defaults() 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 present

This 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 pattern

This 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 patterns

The 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 associations

The code provides methods for:

  1. Setting one-to-many relationships with AppCustomInvoicingCustomer entities
  2. Setting many-to-one relationship with the App entity

These relationship setters follow the standard Ent pattern.


185-207: Default values are properly initialized

The 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 integrity

The 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 defined

The 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 configured

The 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 support

The 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.

@turip
turip merged commit 92b94c1 into main Apr 16, 2025
@turip
turip deleted the feat/custominvoicing-db-struct branch April 16, 2025 19:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants