Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(torii-graphql): empty models union workaround #2994

Merged
merged 4 commits into from
Feb 6, 2025

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Feb 5, 2025

Summary by CodeRabbit

  • New Features
    • Added new constants for empty entity types and names.
    • Introduced a new EmptyObject to enhance the GraphQL schema’s flexibility.
    • Updated schema construction to improve handling of cases when no data models exist, ensuring better stability.
    • Added a new module for organizing empty-related functionalities.

@Larkooo Larkooo force-pushed the empty-union-models branch from 5403449 to be833f6 Compare February 5, 2025 11:13
Copy link

coderabbitai bot commented Feb 5, 2025

Ohayo sensei!

Below is the detailed summary of the changes:

Walkthrough

This pull request introduces new constants and static type mappings related to empty entities, along with the implementation of a new EmptyObject structure that conforms to the BasicObject trait. Additionally, a new module for the empty object is exported, and the GraphQL schema building functionality is updated to include the EmptyObject when no models exist, ensuring robust schema generation and optimized model iteration.

Changes

File(s) Change Summary
crates/torii/graphql/src/constants.rs
crates/torii/graphql/src/mapping.rs
Added new constants (EMPTY_TYPE_NAME, EMPTY_NAMES) and a new static mapping (EMPTY_MAPPING) for empty entities.
crates/torii/graphql/src/object/empty.rs
crates/torii/graphql/src/object/mod.rs
Introduced the EmptyObject struct with implementations for name, type_name, and type_mapping methods; exported the new empty module.
crates/torii/graphql/src/schema.rs Updated the schema builder to include EmptyObject in the objects list and to adjust the union’s possible types when no models are present; improved iteration over models.

Sequence Diagram(s)

sequenceDiagram
    participant SB as Schema Builder
    participant DB as Models Database
    participant EO as EmptyObject
    participant U as Union Builder

    SB->>DB: Query for models
    alt Models exist
        SB->>SB: Iterate over models and build schema
    else No models
        SB->>EO: Retrieve EmptyObject details (name, type, mapping)
        SB->>U: Add EMPTY_TYPE_NAME to union
    end
Loading

Suggested reviewers

  • glihm

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 168d888 and 02ac484.

📒 Files selected for processing (4)
  • crates/torii/graphql/src/constants.rs (1 hunks)
  • crates/torii/graphql/src/mapping.rs (1 hunks)
  • crates/torii/graphql/src/object/mod.rs (1 hunks)
  • crates/torii/graphql/src/schema.rs (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • crates/torii/graphql/src/mapping.rs
  • crates/torii/graphql/src/constants.rs
  • crates/torii/graphql/src/object/mod.rs
🔇 Additional comments (4)
crates/torii/graphql/src/schema.rs (4)

13-16: Ohayo! Clean import organization, sensei!

The new imports are well-organized and properly grouped with related constants and objects.

Also applies to: 18-18


133-133: Nice addition to the objects list, sensei!

The EmptyObject is properly added as a BasicObject variant, maintaining consistency with similar object types.


147-147: Excellent performance optimization, sensei!

Using references in the loop prevents unnecessary cloning of model data.


169-173: Smart workaround for empty unions, sensei!

The solution ensures schema validity when no models exist. Let's verify this approach against GraphQL spec.

✅ Verification successful

🌐 Web query:

Does GraphQL spec allow empty unions? What's the recommended way to handle them?

💡 Result:

The GraphQL specification explicitly **does not allow empty unions**. According to the GraphQL spec requirements outlined in [1][4][10]:

1. **Union validation rules**:
   - A union type must include **one or more** unique member types
   - Member types must be object types (no scalars/interfaces/unions)
   - Wrapping types (like lists/non-null) cannot be union members

2. **Empty union implications**:
   - An empty union violates the first validation rule ("must include one or more")
   - GraphQL implementations will reject schemas with empty unions during validation [3][4]
   - Attempts to create scalar unions (e.g., `String | Int`) are also invalid [3]

For scenarios where you might consider an empty union:

**Recommended solutions**:
1. **Use placeholder types**:
   ```graphql
   union SearchResult = Product | User | EmptyResult
   
   type EmptyResult {
     message: String!
   }
   ```

2. **Leverage interfaces** when shared fields exist:
   ```graphql
   interface Error {
     message: String!
   }
   
   type ValidationError implements Error {
     message: String!
     field: String!
   }
   ```

3. **Nullability patterns**:
   ```graphql
   type Query {
     results: [Result!]!  # Non-null list of non-null items
   }
   
   union Result = Data | NotFound
   
   type NotFound {
     code: Int!
   }
   ```

4. **Error handling** (as shown in B2B examples [10]):
   ```graphql
   union OperationResult = Success | ErrorCollection
   
   type ErrorCollection {
     errors: [OperationError!]!
   }
   ```

For existing implementations facing empty union issues, schema redesign is required to include at least one valid member type following GraphQL's type system rules [1][4][5].

Citations:

- 1: https://discuss.dgraph.io/t/union-types-in-graphql/9581
- 2: https://dev.to/rohinivsenthil/graphql-unions-customize-your-results-54h5
- 3: https://community.apollographql.com/t/not-able-to-consume-data-with-two-types-string-and-object/6177
- 4: https://github.com/graphql/graphql-spec/issues/236
- 5: https://graphql.com/learn/interfaces-and-unions/
- 6: https://forums.fauna.com/t/creating-empty-non-null-array-via-graphql/594
- 7: https://hasura.io/blog/graphql-nulls-cheatsheet
- 8: https://graphql.wtf/episodes/30-graphql-error-handling-with-union-types
- 9: https://graphql.org/learn/best-practices/
- 10: https://developer.adobe.com/commerce/webapi/graphql/schema/b2b/negotiable-quote/unions/

Ohayo, sensei! The approach of adding a placeholder type (i.e., using EMPTY_TYPE_NAME) when there are no models is a smart and valid workaround. Since the GraphQL specification explicitly disallows empty unions, ensuring at least one valid member (even if it's a dummy type) effectively keeps the schema valid.

  • File: crates/torii/graphql/src/schema.rs
  • Relevant Lines: 169-173
  • Observation: Adding EMPTY_TYPE_NAME as a possible type when the union is empty aligns well with the recommended practices for handling empty unions in GraphQL.

Everything checks out!


🪧 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. (Beta)
  • @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.

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bf0c5ee and be833f6.

📒 Files selected for processing (5)
  • crates/torii/graphql/src/constants.rs (1 hunks)
  • crates/torii/graphql/src/mapping.rs (1 hunks)
  • crates/torii/graphql/src/object/empty.rs (1 hunks)
  • crates/torii/graphql/src/object/mod.rs (1 hunks)
  • crates/torii/graphql/src/schema.rs (5 hunks)
✅ Files skipped from review due to trivial changes (1)
  • crates/torii/graphql/src/object/mod.rs
🧰 Additional context used
🪛 GitHub Actions: ci
crates/torii/graphql/src/constants.rs

[error] 67-75: Merge conflict markers detected. Please resolve the merge conflicts in the file.

🔇 Additional comments (4)
crates/torii/graphql/src/object/empty.rs (1)

1-20: Ohayo! The implementation looks great, sensei!

The EmptyObject implementation is clean and correctly implements the BasicObject trait with all required methods.

crates/torii/graphql/src/schema.rs (3)

132-132: LGTM! Good addition to predefined objects, sensei.

The EmptyObject is correctly added to the list of predefined objects.


146-146: Nice optimization, sensei!

Changed to iterate over references to models instead of moving them, which is more efficient.


168-171: Great workaround for empty models case, sensei!

The implementation correctly handles the case when no models exist by adding the empty type to the model union, preventing an invalid schema.

crates/torii/graphql/src/constants.rs Outdated Show resolved Hide resolved
crates/torii/graphql/src/mapping.rs Outdated Show resolved Hide resolved
@Larkooo Larkooo enabled auto-merge (squash) February 6, 2025 02:57
@Larkooo Larkooo merged commit 99d2e60 into dojoengine:main Feb 6, 2025
13 checks passed
Copy link

codecov bot commented Feb 6, 2025

Codecov Report

Attention: Patch coverage is 78.57143% with 3 lines in your changes missing coverage. Please review.

Project coverage is 57.13%. Comparing base (a3181d8) to head (02ac484).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/graphql/src/object/empty.rs 66.66% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2994      +/-   ##
==========================================
- Coverage   57.15%   57.13%   -0.02%     
==========================================
  Files         428      429       +1     
  Lines       56802    56815      +13     
==========================================
- Hits        32464    32463       -1     
- Misses      24338    24352      +14     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants