Skip to content

Add schema_id(), handles different types with the same name#247

Merged
GREsau merged 5 commits intomasterfrom
schema_id
Sep 17, 2023
Merged

Add schema_id(), handles different types with the same name#247
GREsau merged 5 commits intomasterfrom
schema_id

Conversation

@GREsau
Copy link
Copy Markdown
Owner

@GREsau GREsau commented Sep 17, 2023

Fixes #62 by implementing #62 (comment)

Schemars currently differentiates between types using the JsonSchema::schema_name() function, which typically returns the type name (excluding the module path). This PR updates the schema generator to differentiate between types using the new function JsonSchema::schema_id(), which is similar, but includes the type's module path. This leaves schema_name() returning a clean, human-readable "friendly" name mostly free of rust details (e.g. being unaffected by module renames).

schema_id() has a default implementation (which delegates to schema_name()), so this should be a non-breaking change.

Because a vast majority of types have a statically-determined id (and name), schema_id() returns a Cow<'static, str> instead of a String - in future, I'd like to change schema_name() to return a Cow for the same reason, but that will be a breaking change so is not being done in this PR. The main reason an implementation would return a Cow::Owned(String) would be a generic type, e.g. Vec<T>, where the return value of schema_id() (and of schema_name()) depends on that of T.

In many cases, the return value of T::schema_id() will be identical to that of std::any::type_name::<T>(), so ideally we could just use that - unfortunately type_name() is unsuitable here for two reasons:

  1. the output of type_name() may change in a future rust version e.g. by excluding the module path, or including lifetime specifiers
  2. some distinct rust types have equivalent schemas, so should have identical return values of schema_id(), e.g. String/str/&str, but these will all have different return values of type_name()

Still to do:

  • Update docs
    • doc comment for schema_id()
    • web docs - will be done in a separate change
  • implement schema_id() appropriately for optional dependencies ✅
  • add tests ✅

@GREsau GREsau marked this pull request as ready for review September 17, 2023 19:36
@GREsau GREsau merged commit 342b2df into master Sep 17, 2023
@GREsau GREsau deleted the schema_id branch September 17, 2023 19:36
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.

Schemars overwrites declarations if there are structs with the same name

1 participant