moxley
Using `in` or `is_nil()` for a jsonb property
I’m trying to understand the Ash filter expression syntax for working with json arrays within a jsonb column in ash_postgres.
I have a jsonb column, settings, on a table notification_settings
For a simple equality expression, I can use the == operator:
NotificationSettings
|> Ash.Query.filter(settings["foo"] == "bar")
|> Ash.read!(authorize?: false)
But for a value in enum expression:
NotificationSettings
|> Ash.Query.filter("email" in settings["dues_reminders"])
|> Ash.read!(authorize?: false)
It produces:
** (Ash.Error.Unknown)
Bread Crumbs:
> Error returned from: NotificationSettings.read
Unknown Error
* ** (Postgrex.Error) ERROR 22P02 (invalid_text_representation) malformed array literal: "["email"]". If you are trying to query a JSON field, the parameter may need to be interpolated. Instead of
p.json["field"] != "value"
do
p.json["field"] != ^"value"
"[" must introduce explicitly-specified array dimensions.
So I have to use fragment() instead:
NotificationSettings
|> Ash.Query.filter(fragment("?->'dues_reminders' \\? ?", settings, "email"))
|> Ash.read!(authorize?: false)
A very similar thing happens with is_nil() on a jsonb property:
NotificationSettings
|> Ash.Query.filter(is_nil(settings["dues_reminders"]))
|> Ash.read!(authorize?: false)
It produces:
* ** (Postgrex.Error) ERROR 22P02 (invalid_text_representation) malformed array literal: "["email"]"...
For that too, I must use fragment instead:
NotificationSettings
|> Ash.Query.filter(fragment("?->'dues_reminders' is null", settings))
|> Ash.read!(authorize?: false)
Is this correct? Is there no built-in syntax for doing jsonb value comparisons beyond the == operator?
First Post!
zachdaniel
Last Post!
moxley
Thanks @zachdaniel !
I created an ash_postgres PR that reproduces the is_nil() issue: Demonstrate failed query for is_nil on array within jsonb by moxley · Pull Request #615 · ash-project/ash_postgres · GitHub
Popular in Questions
Other popular topics
Latest Ash Threads
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









