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

added ability to override federation version on export schema command #3697

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions RELEASE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Release type: patch

Added option for the export_schema command to override the output federation version.
usage example: strawberry export-schema --federation-version=2.5

This change ONLY affects "strawberry export-schema" command and is fully backward-compatible without any logic change.

Warning: Please use with caution!!

If the schema define directives that are not supported by the specified version (in the override parameter) the schema
will still generate the output using the value from the override, and may break at runtime.
12 changes: 12 additions & 0 deletions docs/guides/schema-export.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,15 @@ Alternatively, the `--output` option can be used:
```bash
strawberry export-schema package.module:schema --output schema.graphql
```

You can override the output directive to have specific federation schema (e.g:
schema @link(url: "https://specs.apollo.dev/federation/v2.5"):

```bash
strawberry export-schema package.module:schema --federation-version=2.5 --output schema.graphql
```

> [!WARNING] \
> If the schema define directives that are not supported by the specified
> version (in the override parameter) the schema will still generate the output
> using the value from the override, and may break at runtime.
13 changes: 13 additions & 0 deletions strawberry/cli/commands/export_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,20 @@ def export_schema(
"-o",
help="File to save the exported schema. If not provided, prints to console.",
),
federation_version: float = typer.Option(
None,
"--federation-version",
"-e",
help=(
"Override the output federation schema version. please use with care!"
"schema may break if it have directives that are not supported by the defined federation version."
"(for directive version compatibility please see: https://www.apollographql.com/docs/graphos/reference/federation/directives)"
),
min=1,
),
) -> None:
if federation_version:
app.__setattr__("federation_version_override", federation_version)
schema_symbol = load_schema(schema, app_dir)

schema_text = print_schema(schema_symbol)
Expand Down
20 changes: 20 additions & 0 deletions strawberry/federation/schema_directives.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import typing
from dataclasses import dataclass
from typing import ClassVar, List, Optional

from strawberry import directive_field
from strawberry.cli import app
from strawberry.schema_directive import Location, schema_directive
from strawberry.types.unset import UNSET

Expand All @@ -11,12 +13,30 @@
LinkPurpose,
)

FEDERATION_VERSION_BASE_URL = "https://specs.apollo.dev/federation/v"


@dataclass
class ImportedFrom:
name: str
url: str = "https://specs.apollo.dev/federation/v2.7"

def __init__(self, **kwargs: typing.Dict[str, typing.Any]) -> None:
if hasattr(self, "__dataclass_fields__"):
args = self.__dataclass_fields__
for key, value in kwargs.items():
if key in args and type(value) is args.get(key).type:
self.__setattr__(key, value)
if (
hasattr(app, "federation_version_override")
and type(value) is str
and str(value).startswith("https://specs.apollo.dev/federation/")
):
self.__setattr__(
key,
f"{FEDERATION_VERSION_BASE_URL}{app.federation_version_override!s}",
)


class FederationDirective:
imported_from: ClassVar[ImportedFrom]
Expand Down
45 changes: 45 additions & 0 deletions tests/cli/test_export_schema.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,25 @@
import typing

from click.testing import Result
from typer import Typer
from typer.testing import CliRunner


def check_generated_schema(
cli_app: Typer,
cli_runner: CliRunner,
schema_override: typing.Optional[float] = None,
) -> Result:
selector = "tests.fixtures.sample_package.sample_module_federated:schema"
args = [
"export-schema",
selector,
]
if schema_override:
args.append(f"--federation-version={schema_override!s}")
return cli_runner.invoke(cli_app, args)


def test_schema_export(cli_app: Typer, cli_runner: CliRunner):
selector = "tests.fixtures.sample_package.sample_module:schema"
result = cli_runner.invoke(cli_app, ["export-schema", selector])
Expand All @@ -19,6 +37,33 @@ def test_schema_export(cli_app: Typer, cli_runner: CliRunner):
)
sourcery-ai[bot] marked this conversation as resolved.
Show resolved Hide resolved


def test_schema_export_with_federation_version_override(
cli_app: Typer, cli_runner: CliRunner
):
result = check_generated_schema(cli_app, cli_runner, 2.5)
assert result.exit_code == 0
assert result.stdout.startswith(
'schema @link(url: "https://specs.apollo.dev/federation/v2.5"'
)


def test_schema_export_without_federation_version_override(
cli_app: Typer, cli_runner: CliRunner
):
result = check_generated_schema(cli_app, cli_runner)
assert result.exit_code == 0
assert result.stdout.startswith(
'schema @link(url: "https://specs.apollo.dev/federation/v2.7"'
)


def test_invalid_schema_export_federation_version_override(
cli_app: Typer, cli_runner: CliRunner
):
result = check_generated_schema(cli_app, cli_runner, 0.2)
assert result.exit_code == 2


def test_default_schema_symbol_name(cli_app: Typer, cli_runner: CliRunner):
selector = "tests.fixtures.sample_package.sample_module"
result = cli_runner.invoke(cli_app, ["export-schema", selector])
Expand Down
65 changes: 65 additions & 0 deletions tests/fixtures/sample_package/sample_module_federated.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import typing

import strawberry
from strawberry.federation.schema_directives import Key


@strawberry.federation.type(directives=[Key(fields="id", resolvable=False)])
class User:
id: strawberry.ID


async def get_user(root: "Organization", info: strawberry.Info) -> User:
return User(id=root._owner)


@strawberry.federation.type(keys=["id"])
class Organization:
id: strawberry.ID
name: str
_owner: strawberry.Private[User]
owner: User = strawberry.field(resolver=get_user)

@classmethod
async def resolve_reference(
cls, id: strawberry.ID
) -> typing.Optional["Organization"]:
return await get_organization_by_id(id=id)


async def get_organizations():
return [
Organization(
id=strawberry.ID("org1"),
name="iotflow",
_owner="abcdert1",
),
Organization(
id=strawberry.ID("org2"),
name="ibrag",
_owner="abdfr2",
),
]


async def get_organization_by_id(id: strawberry.ID) -> typing.Optional[Organization]:
for organization in await get_organizations():
if organization.id == id:
return organization
return None


@strawberry.type
class Query:
organizations: typing.List[Organization] = strawberry.field(
resolver=get_organizations
)

@strawberry.field
async def organization(self, id: strawberry.ID) -> typing.Optional[Organization]:
return await get_organization_by_id(id)


schema = strawberry.federation.Schema(
query=Query, types=[Organization, User], enable_federation_2=True
)
Loading