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

New serializer columns #691

Closed
jwoertink opened this issue Jun 25, 2021 · 2 comments · Fixed by #695
Closed

New serializer columns #691

jwoertink opened this issue Jun 25, 2021 · 2 comments · Fixed by #695

Comments

@jwoertink
Copy link
Member

Working with JSON::Any columns is kind of a pain. I have no idea how this would work, or what things we would run in to, but I had this idea that would look like this:

class User < BaseModel
  table do
    serialized preferences : PreferenceSerializer
  end
end

class PreferenceSerializer
  include JSON::Serializable

  property theme : String
  property font_size : String
end

user = UserQuery.first
user.preferences.theme #=> "dark"
user.preferences.font_size #=> "XL"

My initial thought was under the hood, it would look something like:

macro serialized(type_dec)
  column {{ type_dec.var }}_data : JSON::Any = JSON::Any.new({} of String => JSON::Any)

  def {{ type_dec.var }} : {{ type_dec.type }}
    {{ type_dec.type }}.from_json({{ type_dec.var }}_data.to_json)
  end
end

There's a lot of things to consider like how does this look in forms, how does it affect queries, or operations, etc... There's also the fact that it's a pretty big performance hit to convert a JSON::Any object in to a serialized object from JSON. It would be neat if Crystal had that built-in, but until that happens, we'd have to probably just make that as the downside to an easier to work with object.

I just wanted to jot down some ideas here, and keep track of it. If anyone has some thoughts, let me know.

@robacarp
Copy link
Contributor

I'm doing something like that manually for json columns, along with a type column which indicates which "schema" the json column would conform to. My use case for the json column is that I didn't want to do have a bunch of null-able columns or try to wrangle any sort of inheritance model, so I need multiple possible schemas.

@matthewmcgarvey
Copy link
Member

This is definitely connected to will/crystal-pg#125

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 a pull request may close this issue.

3 participants