johnnyicon

johnnyicon

Hi all,

I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage.

I’m trying to use Postgres’ JSONB via the :map datatype.

Here’s my migration to add it to my table:

defmodule MyApp.Repo.Migrations.AddMapFieldToUser do
  use Ecto.Migration

  def change do
    alter table(:users) do
      add :data, :map
    end
  end
end

Here’s my schema:

defmodule MyApp.User do
  use MyApp.Web, :model
  use Coherence.Schema

  schema "users" do
    field :first_name, :string
    field :last_name, :string
    field :email, :string
    field :data, :map

    coherence_schema()

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:first_name, :last_name, :email] ++ coherence_fields)
    |> unique_constraint(:email)
    |> validate_required([:first_name, :last_name, :email])
    |> validate_coherence(params)
  end
end

I’ve been trying to set values into the data map using a changeset, but I haven’t had any luck. I’ve tried using both a JSON string and a map.

JSON string:

changeset = User.changeset(retrieved_user, %{data: "{test:'awesome'}"})
#Ecto.Changeset<action: nil, changes: %{}, errors: [],
 data: #MyApp.User<>, valid?: true>

Map:

changeset = User.changeset(john, %{data: %{test: "awesome"}})
#Ecto.Changeset<action: nil, changes: %{}, errors: [],
 data: #PodioBackup.User<>, valid?: true>

You’ll see that the changes map is empty.

Which leads me to believe that I am clearly missing something! :sweat_smile: And I’m thinking maybe I need to add this JSON extension that many websites are referring to: postgrex/lib/postgrex/extensions/json.ex at master · elixir-ecto/postgrex · GitHub

How do I actually use that JSON extension? And, what am I doing wrong?

Thanks for the help in advance! :slight_smile:

Showing Posts 1 to 9

alexgaribay

alexgaribay

Phoenix Core Team

You’re missing a cast of :data in your changeset.

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:first_name, :last_name, :data] ++ coherence_fields)
    |> ...
  end
johnnyicon

johnnyicon OP

Somehow I knew it was going to be something like that.

Thanks @alexgaribay. That was it!

nezzart

nezzart

In this

shouldn’t the “data” be of type “jsonb” instead of “map”?

BrightEyesDavid

BrightEyesDavid

The first argument (:data) in add :data, :map is the name of the table column. The type is the second argument (:map).

Here’s the documentation for Ecto.Migration.add.

nezzart

nezzart

yes, but my question is about “map” vs “jsonb”

david, your eyes are soooo green!

michalmuskala

michalmuskala

They are equivalent when using postgres. map is an abstract type and each database adapter can choose the actual representation - for postgres it’s jsonb.

Qqwy

Qqwy

TypeCheck Core Team

So is a correct conclusion that using :map would be preferable over using :json, to allow you to switch database adapters, if desired, later on?

SoldierCoder

SoldierCoder

Is such a thought falling into this famous trap: “Premature optimization is the root of all evil!”? Or to put this another way, do you want your code to express what you are intending to happen right now? Or do you want your code to express what you MIGHT want it to do in the somewhat nebulous FUTURE?

“Why should you want to know?
Don’t you mind about the future
Don’t you try to think ahead
Save tomorrow for tomorrow
Think about today instead” – Jesus

Qqwy

Qqwy

TypeCheck Core Team

No, I don’t think this is a case of premature optimization. Though I will admit that I don’t know exactly what my thoughts were when I wrote the last post in this topic in 2017, 8 years ago.

I would still consider that programming is a challenge of solving puzzles with often incomplete information. Doing as little optimization (regardless of what you’re optimizing for) as needed while keeping your project as flexible as possible for the future (within practical limits) is therefore often a great approach because you can make better choices in the future as you will have (more) complete information then.

In this case: it costs nothing (not in performance, not in memory and not in developer mental complexity) to use :map instead of :jsonb if you want to store a hashmap with string keys in a Postgres column, whereas it does allow you to more easily switch over to a different database engine.

I think that that can be considered roughly the opposite of premature optimization, especially of the kind that Dijkstra originally talked about.

— All posts loaded —

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews