Skip to content

Conversation

Nalin7parihar
Copy link

@Nalin7parihar Nalin7parihar commented Oct 2, 2025

Description

This PR adds support for lexicographic (alphabetical) sorting of GraphQL schema fields through a new sort_schema configuration option in StrawberryConfig.

By default, Strawberry generates GraphQL schemas with fields in the order they're defined in code. This makes introspection UIs (typically at /graphql) difficult to navigate because related fields (like userById, userByEmail, userByName) are scattered throughout the list rather than grouped alphabetically.

This change adds a sort_schema boolean configuration option that, when enabled, uses GraphQL Core's built-in lexicographic_sort_schema function to sort all schema elements alphabetically - including types, fields, enums, interfaces, unions, and more.

Usage Example:

import strawberry
from strawberry.schema.config import StrawberryConfig

@strawberry.type
class Query:
    user_by_name: str
    user_by_id: str
    user_by_email: str

# Enable schema sorting
schema = strawberry.Schema(
    query=Query, 
    config=StrawberryConfig(sort_schema=True)
)

# The printed schema will now have fields sorted alphabetically:
# type Query {
#   userByEmail: String!
#   userById: String!
#   userByName: String!
# }

## Summary by Sourcery

Introduce a new sort_schema configuration option that applies GraphQL Cores lexicographicSortSchema to alphabetically sort all schema elements when enabled; document the feature and add extensive tests to ensure correct behavior across schema features.

New Features:
- Add sort_schema option to StrawberryConfig to enable lexicographic (alphabetical) sorting of GraphQL schema elements

Enhancements:
- Invoke GraphQL Cores lexicographicSortSchema to reorder types, fields, enums, interfaces, unions, and other schema elements when sort_schema is enabled

Build:
- Add pre-commit configuration to project dependencies

Documentation:
- Document the sort_schema configuration in schema configurations docs and update release notes with usage examples

Tests:
- Add comprehensive tests for schema sorting behavior across queries, mutations, subscriptions, multiple types, interfaces, enums, input types, unions, camelCase compatibility, and execution integrity

Copy link
Contributor

sourcery-ai bot commented Oct 2, 2025

Reviewer's Guide

This PR introduces a new boolean sort_schema option in StrawberryConfig and updates the print_schema function to invoke GraphQL Core’s lexicographic_sort_schema when enabled; accompanying documentation and release notes are updated, a comprehensive test suite is added, and the pre-commit tool is included in development dependencies.

File-Level Changes

Change Details Files
Introduce sort_schema config and integrate lexicographic sorting in schema printer
  • Add sort_schema boolean to StrawberryConfig
  • Apply lexicographic_sort_schema when sort_schema is enabled in print_schema
strawberry/schema/config.py
strawberry/printer/printer.py
Expand documentation and release notes for the new sorting option
  • Document sort_schema in schema-configurations.md
  • Add release entry in RELEASE.md
docs/types/schema-configurations.md
RELEASE.md
Add comprehensive tests covering schema sorting behavior
  • Test default disabled and enabled sorting
  • Cover mutations, multiple types, interfaces, enums, input types, unions, subscriptions, and auto_camel_case
  • Verify functionality remains intact after sorting
tests/test_printer/test_sort_schema.py
Update development dependencies
  • Include pre-commit in project dependencies
pyproject.toml
poetry.lock

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@botberry
Copy link
Member

botberry commented Oct 2, 2025

Thanks for adding the RELEASE.md file!

Here's a preview of the changelog:


This release adds support for lexicographic (alphabetical) sorting of GraphQL
schema fields through a new configuration option.

Added a sort_schema configuration option to StrawberryConfig that allows
users to enable alphabetical sorting of schema types and fields. When enabled,
the schema uses GraphQL's built-in lexicographic_sort_schema function to sort
all types, fields, and other schema elements alphabetically, making the
introspection UI easier to navigate.

Usage Example:

import strawberry
from strawberry.schema.config import StrawberryConfig


@strawberry.type
class Query:
    user_by_name: str
    user_by_id: str
    user_by_email: str


# Enable schema sorting
schema = strawberry.Schema(query=Query, config=StrawberryConfig(sort_schema=True))

# The printed schema will now have fields sorted alphabetically:
# type Query {
#   userByEmail: String!
#   userById: String!
#   userByName: String!
# }

Features:

  • Sorts all schema elements alphabetically (types, fields, enums, etc.)
  • Disabled by default to maintain backward compatibility
  • Works with all schema features (mutations, subscriptions, interfaces, unions,
    etc.)
  • Compatible with other config options like auto_camel_case

This makes GraphQL introspection UIs (typically at /graphql) much easier to
navigate by grouping related fields together alphabetically rather than in
definition order.

Here's the tweet text:

🆕 Release (next) is out! Thanks to Nalin Parihar for the PR 👏

Get it here 👉 https://strawberry.rocks/release/(next)

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Overview

Summary

This PR introduces a new `sort_schema` configuration option to `StrawberryConfig` that enables lexicographic (alphabetical) sorting of GraphQL schema elements. The feature addresses a common developer pain point with GraphQL introspection UIs where related fields (like `userById`, `userByEmail`, `userByName`) are scattered throughout the interface based on their definition order in code rather than being grouped alphabetically for easier navigation.

The implementation leverages GraphQL Core's built-in lexicographic_sort_schema function to sort all schema elements including types, fields, enums, interfaces, unions, and more. The feature is disabled by default (sort_schema: bool = False) to maintain backward compatibility, allowing existing schemas to continue working unchanged while giving developers the option to enable alphabetical sorting when desired.

The changes integrate cleanly with Strawberry's existing configuration system and schema printing functionality. When enabled, the sorting is applied during the schema printing phase in the print_schema function, ensuring it only affects the printed representation without changing runtime behavior or execution semantics. The feature works seamlessly with other configuration options like auto_camel_case and supports all GraphQL constructs including mutations, subscriptions, interfaces, and unions.

Important Files Changed

Changed Files
Filename Score Overview
strawberry/schema/config.py 5/5 Added sort_schema: bool = False configuration option to StrawberryConfig class
strawberry/printer/printer.py 5/5 Imported lexicographic_sort_schema and applied sorting when config option is enabled
pyproject.toml 5/5 Added pre-commit = "^4.3.0" development dependency for code quality tooling
tests/test_printer/test_sort_schema.py 5/5 Comprehensive test suite validating schema sorting across all GraphQL constructs
RELEASE.md 5/5 Well-structured release notes documenting the new feature with examples
docs/types/schema-configurations.md 5/5 Added thorough documentation for the sort_schema configuration option

Confidence score: 5/5

  • This PR is safe to merge with minimal risk as it adds an optional feature with comprehensive testing
  • Score reflects well-tested implementation using GraphQL Core's standard functionality and backward compatibility preservation
  • No files require special attention as all changes follow established patterns and include proper testing

Sequence Diagram

sequenceDiagram
    participant User
    participant StrawberrySchema
    participant StrawberryConfig
    participant Printer
    participant GraphQLCore

    User->>StrawberryConfig: "Create config with sort_schema=True"
    User->>StrawberrySchema: "Create schema with config"
    StrawberrySchema->>StrawberryConfig: "Store configuration"
    
    User->>Printer: "Call print_schema(schema)"
    Printer->>StrawberrySchema: "Get _schema (GraphQL Core schema)"
    Printer->>StrawberryConfig: "Check config.sort_schema"
    
    alt sort_schema is True
        Printer->>GraphQLCore: "Call lexicographic_sort_schema(schema)"
        GraphQLCore-->>Printer: "Return sorted schema"
    else sort_schema is False
        Printer->>Printer: "Use original schema order"
    end
    
    Printer->>Printer: "Generate schema string with sorted types and fields"
    Printer-->>User: "Return formatted GraphQL schema string"
Loading

Context used:

Context from dashboard - When documenting features, ensure that explanations are clear and provide context on why certain fun... (source)

6 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Copy link
Member

@patrick91 patrick91 left a comment

Choose a reason for hiding this comment

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

This looks dope!

I wonder if we should make sorted schemas by default? and add "breaking change" notice for people?

I like the idea of doing the right thing by default, but maybe it's not that big of a deal in this case?

/cc @bellini666 @DoctorJohn @erikwrede

Copy link

codecov bot commented Oct 2, 2025

Codecov Report

❌ Patch coverage is 97.64706% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.27%. Comparing base (19ecb92) to head (03a43f6).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4006      +/-   ##
==========================================
+ Coverage   94.24%   94.27%   +0.02%     
==========================================
  Files         531      532       +1     
  Lines       34829    34998     +169     
  Branches     1847     1848       +1     
==========================================
+ Hits        32826    32993     +167     
- Misses       1698     1701       +3     
+ Partials      305      304       -1     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

codspeed-hq bot commented Oct 2, 2025

CodSpeed Performance Report

Merging #4006 will not alter performance

Comparing Nalin7parihar:sortSchema (03a43f6) with main (19ecb92)

Summary

✅ 26 untouched

@Nalin7parihar
Copy link
Author

This looks dope!

I wonder if we should make sorted schemas by default? and add "breaking change" notice for people?

I like the idea of doing the right thing by default, but maybe it's not that big of a deal in this case?

/cc @bellini666 @DoctorJohn @erikwrede

thanks for the feedback!! I agree on making sorted schemas as default since it makes most sense. I am ready to tweak my PR depending on what your team decides.

@patrick91
Copy link
Member

@Nalin7parihar let's make it the default!

@Nalin7parihar
Copy link
Author

@Nalin7parihar let's make it the default!

Sounds Great! ill start working on my PR but do I need to do any doc changes along with this? Please let me know.

@DoctorJohn
Copy link
Member

@Nalin7parihar let's make it the default!

Sounds Great! ill start working on my PR but do I need to do any doc changes along with this? Please let me know.

Kinda. It would be nice if you updated the new docs from your PR to mention that lexicographic sorting is the default. It would also be nice to have a new breaking change entry in this directory: https://github.com/strawberry-graphql/strawberry/tree/main/docs/breaking-changes

@Nalin7parihar
Copy link
Author

Hey! Quick question before I finalize the PR:

While implementing the default sorting change, I noticed that lexicographic_sort_schema from graphql-core seems to strip directives applied to enum values.

Test test_print_directive_on_enum_value was failing because the @sensitive directive completely disappeared when sorting was enabled. I fixed it by adding sort_schema=False to that specific test.

Is this a known limitation? Should I document this caveat anywhere, or is it rare enough to ignore?

@patrick91
Copy link
Member

While implementing the default sorting change, I noticed that lexicographic_sort_schema from graphql-core seems to strip directives applied to enum values.

that feels like a bug? 👀

Maybe we can fix it in graphql-core itself /cc @erikwrede

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants