-
Notifications
You must be signed in to change notification settings - Fork 269
feat(enum): add Enum type engine+python #1218
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
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -13,6 +13,8 @@ | |
| Literal, | ||
| NamedTuple, | ||
| Protocol, | ||
| Optional, | ||
| Sequence, | ||
| TypeVar, | ||
| overload, | ||
| Self, | ||
|
|
@@ -64,6 +66,19 @@ def __init__(self, key: str, value: Any): | |
| LocalDateTime = Annotated[datetime.datetime, TypeKind("LocalDateTime")] | ||
| OffsetDateTime = Annotated[datetime.datetime, TypeKind("OffsetDateTime")] | ||
|
|
||
|
|
||
| def Enum(*, variants: Optional[Sequence[str]] = None) -> Any: | ||
| """ | ||
| String-like enumerated type. Use `variants` to hint allowed values. | ||
| Example: | ||
| color: Enum(variants=["red", "green", "blue"]) | ||
| At runtime this is a plain `str`; `variants` are emitted as schema attrs. | ||
| """ | ||
| if variants is not None: | ||
| return Annotated[str, TypeKind("Enum"), TypeAttr("variants", list(variants))] | ||
| return Annotated[str, TypeKind("Enum")] | ||
|
|
||
|
|
||
|
||
| if TYPE_CHECKING: | ||
| T_co = TypeVar("T_co", covariant=True) | ||
| Dim_co = TypeVar("Dim_co", bound=int | None, covariant=True, default=None) | ||
|
|
@@ -587,6 +602,7 @@ class BasicValueType: | |
| "OffsetDateTime", | ||
| "TimeDelta", | ||
| "Json", | ||
| "Enum", | ||
| "Vector", | ||
| "Union", | ||
| ] | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| use crate::prelude::*; | ||
|
|
||
| use crate::utils::immutable::RefList; | ||
| use indexmap::IndexMap; | ||
| use schemars::schema::{ | ||
| ArrayValidation, InstanceType, ObjectValidation, Schema, SchemaObject, SingleOrVec, | ||
| SubschemaValidation, | ||
|
|
@@ -74,6 +74,9 @@ impl JsonSchemaBuilder { | |
| schema::BasicValueType::Str => { | ||
| schema.instance_type = Some(SingleOrVec::Single(Box::new(InstanceType::String))); | ||
| } | ||
| schema::BasicValueType::Enum => { | ||
| schema.instance_type = Some(SingleOrVec::Single(Box::new(InstanceType::String))); | ||
| } | ||
| schema::BasicValueType::Bytes => { | ||
| schema.instance_type = Some(SingleOrVec::Single(Box::new(InstanceType::String))); | ||
| } | ||
|
|
@@ -245,15 +248,34 @@ impl JsonSchemaBuilder { | |
| field_path.prepend(&f.name), | ||
| ); | ||
| if self.options.fields_always_required && f.value_type.nullable { | ||
| if let Some(instance_type) = &mut field_schema.instance_type { | ||
| let mut types = match instance_type { | ||
| SingleOrVec::Single(t) => vec![**t], | ||
| SingleOrVec::Vec(t) => std::mem::take(t), | ||
| if field_schema.enum_values.is_some() { | ||
| // Keep the enum as-is and support null via oneOf | ||
| let non_null = Schema::Object(field_schema); | ||
| let null_branch = Schema::Object(SchemaObject { | ||
| instance_type: Some(SingleOrVec::Single(Box::new( | ||
| InstanceType::Null, | ||
| ))), | ||
| ..Default::default() | ||
| }); | ||
| field_schema = SchemaObject { | ||
| subschemas: Some(Box::new(SubschemaValidation { | ||
| one_of: Some(vec![non_null, null_branch]), | ||
| ..Default::default() | ||
| })), | ||
| ..Default::default() | ||
| }; | ||
| types.push(InstanceType::Null); | ||
| *instance_type = SingleOrVec::Vec(types); | ||
| } else { | ||
| if let Some(instance_type) = &mut field_schema.instance_type { | ||
| let mut types = match instance_type { | ||
| SingleOrVec::Single(t) => vec![**t], | ||
| SingleOrVec::Vec(t) => std::mem::take(t), | ||
| }; | ||
| types.push(InstanceType::Null); | ||
| *instance_type = SingleOrVec::Vec(types); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| (f.name.to_string(), field_schema.into()) | ||
| }) | ||
| .collect(), | ||
|
|
@@ -298,9 +320,26 @@ impl JsonSchemaBuilder { | |
| enriched_value_type: &schema::EnrichedValueType, | ||
| field_path: RefList<'_, &'_ spec::FieldName>, | ||
| ) -> SchemaObject { | ||
| self.for_value_type(schema_base, &enriched_value_type.typ, field_path) | ||
| } | ||
| let mut out = self.for_value_type(schema_base, &enriched_value_type.typ, field_path); | ||
|
|
||
| if let schema::ValueType::Basic(schema::BasicValueType::Enum) = &enriched_value_type.typ { | ||
| if let Some(variants) = enriched_value_type.attrs.get("variants") { | ||
| if let Some(arr) = variants.as_array() { | ||
| let enum_values: Vec<serde_json::Value> = arr | ||
| .iter() | ||
| .filter_map(|v| { | ||
| v.as_str().map(|s| serde_json::Value::String(s.to_string())) | ||
| }) | ||
| .collect(); | ||
| if !enum_values.is_empty() { | ||
| out.enum_values = Some(enum_values); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| out | ||
| } | ||
| fn build_extra_instructions(&self) -> Result<Option<String>> { | ||
| if self.extra_instructions_per_field.is_empty() { | ||
| return Ok(None); | ||
|
|
@@ -458,6 +497,53 @@ mod tests { | |
| .assert_eq(&serde_json::to_string_pretty(&json_schema).unwrap()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_basic_types_enum_without_variants() { | ||
| let value_type = EnrichedValueType { | ||
| typ: ValueType::Basic(BasicValueType::Enum), | ||
| nullable: false, | ||
| attrs: Arc::new(BTreeMap::new()), | ||
| }; | ||
| let options = create_test_options(); | ||
| let result = build_json_schema(value_type, options).unwrap(); | ||
| let json_schema = schema_to_json(&result.schema); | ||
|
|
||
| expect![[r#" | ||
| { | ||
| "type": "string" | ||
| }"#]] | ||
| .assert_eq(&serde_json::to_string_pretty(&json_schema).unwrap()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_basic_types_enum_with_variants() { | ||
| let mut attrs = BTreeMap::new(); | ||
| attrs.insert( | ||
| "variants".to_string(), | ||
| serde_json::json!(["red", "green", "blue"]), | ||
| ); | ||
|
|
||
| let value_type = EnrichedValueType { | ||
| typ: ValueType::Basic(BasicValueType::Enum), | ||
| nullable: false, | ||
| attrs: Arc::new(attrs), | ||
| }; | ||
| let options = create_test_options(); | ||
| let result = build_json_schema(value_type, options).unwrap(); | ||
| let json_schema = schema_to_json(&result.schema); | ||
|
|
||
| expect![[r#" | ||
| { | ||
| "enum": [ | ||
| "red", | ||
| "green", | ||
| "blue" | ||
| ], | ||
| "type": "string" | ||
| }"#]] | ||
| .assert_eq(&serde_json::to_string_pretty(&json_schema).unwrap()); | ||
| } | ||
|
|
||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. can we add another test for enum and |
||
| #[test] | ||
| fn test_basic_types_bool() { | ||
| let value_type = EnrichedValueType { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -23,6 +23,9 @@ pub enum BasicValueType { | |
| /// String encoded in UTF-8. | ||
| Str, | ||
|
|
||
| /// Enumerated symbolic value. | ||
| Enum, | ||
|
||
|
|
||
| /// A boolean value. | ||
| Bool, | ||
|
|
||
|
|
@@ -71,6 +74,7 @@ impl std::fmt::Display for BasicValueType { | |
| match self { | ||
| BasicValueType::Bytes => write!(f, "Bytes"), | ||
| BasicValueType::Str => write!(f, "Str"), | ||
| BasicValueType::Enum => write!(f, "Enum"), | ||
| BasicValueType::Bool => write!(f, "Bool"), | ||
| BasicValueType::Int64 => write!(f, "Int64"), | ||
| BasicValueType::Float32 => write!(f, "Float32"), | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
They're imported but not used.