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

Adds in Array enums. #1009

Merged
merged 2 commits into from
Mar 23, 2024
Merged

Adds in Array enums. #1009

merged 2 commits into from
Mar 23, 2024

Conversation

jwoertink
Copy link
Member

Fixes #940

This PR adds the ability to set an array column of enums. It also adds in the ability to specify a custom column converter if you're working with custom types that aren't built in to Avram.

class Post < BaseModel
  enum Reaction
    Like
    Heart
    Shocked
    Unlike
  end

  table do
    column reactions : Array(Post::Reaction) = [] of Post::Reaction, converter: PG::EnumArrayConverter(Post::Reaction)
  end
end

@@ -233,6 +233,8 @@ abstract class Avram::Model
converter: JSONConverter({{ data_type }}),
{% elsif data_type.id == Array(Float64).id %}
converter: PG::NumericArrayFloatConverter,
{% elsif converter %}
Copy link
Member Author

Choose a reason for hiding this comment

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

Originally I was going to use

{% elsif data_type.resolve < Enum %}

This would let us pick up the type and set the converter automatically; however, once I did this, it starts to resolve ALL the types. This means that in the comment model where we have belongs_to post : Post, the Post is undefined because it's resolved before crystal requires the post.cr file. It would end up being a breaking change since any model that references another later in alphabetical order would now have to be required in that file. (or you'd just require each model one by one in the proper order)

def parse(value : T)
SuccessfulCast.new(value)
end

def to_db(values : Array(T))
encoded = values.map { |value| to_db(value) }.as(Array(String))
Copy link
Member Author

Choose a reason for hiding this comment

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

I actually don't know why this needs to be String.... but if you look at the method below, it's also converting the enum value to a string. Maybe a PQ thing? 🤔

@jwoertink jwoertink merged commit 2249315 into main Mar 23, 2024
9 checks passed
@jwoertink jwoertink deleted the issues/940 branch March 23, 2024 16:07
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.

Enum array
1 participant