sharkmyster

sharkmyster

I’m using an adjacency list to store a hierarchy of categories. There can be many root categories each with many children/descendants.

defmodule WordSolverDal.Categories.Category do
  use Ecto.Schema
  import Ecto.Changeset

  use Arbor.Tree,
    foreign_key: :parent_id,
    foreign_key_type: :integer

  schema "categories" do
    field(:name, :string)
    field(:parent_id, :integer)
    many_to_many(:answers, WordSolverDal.Answers.Answer, join_through: "answers_categories")
    timestamps()
  end

  @required [:name]
  @optional [:parent_id]

  def changeset(category, attrs) do
    category
    |> cast(attrs, @required ++ @optional)
    |> validate_required(@required)
    |> validate_length(:name, min: 3)
    |> unique_constraint(:name, name: :unique_categories_name_parent_id_null)
    |> unique_constraint(:name, name: :unique_categories_name_parent_id)
  end
end

The db throws a constraint error if a user tries to delete a record that has children due to the foreign key constraint on :parent_id.

constraint error when attempting to delete struct:

    * "categories_parent_id_fkey" (foreign_key_constraint)

If you would like to stop this constraint violation from raising an
exception and instead add it as an error to your changeset, please
call `foreign_key_constraint/3` on your changeset with the constraint
`:name` as an option.

This error gives advice on how to handle the error without raising an exception but I don’t see how this could work. As I understand it, foreign_key_constraint/3 is typically used for insert/update change sets.

How can I attempt a delete and not raise an exception as described? Or should I just rescue the error?

Showing Posts 1 to 10

kokolegorille

kokolegorille

Can You show your categories migrations?

There should be something like this…

      add :parent_id, references(:categories, on_delete: :delete_all)
sharkmyster

sharkmyster OP

def change do
    create table(:categories) do
      add(:name, :string)
      add(:parent_id, references(:categories), null: true)
      timestamps()
    end

    create(index(:categories, [:parent_id]))

    create(
      index(:categories, [:name, :parent_id],
        unique: true,
        name: :unique_categories_name_parent_id
      )
    )

    create(
      index(:categories, [:name],
        unique: true,
        where: "parent_id IS NULL",
        name: :unique_categories_name_parent_id_null
      )
    )
  end
ken-kost

ken-kost

Have you thought about soft delete? I feel this would solve your problem and give you a bonus to restore deleted categories.

sharkmyster

sharkmyster OP

I want to inform the user that the category has sub-categories and should not be deleted.

kokolegorille

kokolegorille

sbuttgereit

sbuttgereit

A Changeset is just a validation mechanism and there’s nothing inherent in them that prevents their use in deletion. I do agree that most people focus on insert and update when discussing Changesets, but validation is validation and there can be reasons to validate delete operations including your scenario. You’ll see that Ecto.Repo.delete/2 can take a Changeset: Ecto.Repo — Ecto v3.14.0.

Personally, I like the idea of Changesets and handling validation prior to attempting operations on the database, even for deletes… though I’d likely have delete-specific Changeset checks. It might be overly defensive on this, because I also absolutely believe that it’s not a substitute for correct constraints in the database, too, but by validating in the application I feel like I’m more in control. I also like raised exceptions to be logged and not depending on them for my logic means that I can be very consistent about that without thinking too much about it.

ibarch

ibarch

As far as I know, this is the idiomatic solution. Another option is to manually catch the exception within a try/rescue block, but this method is rather ugly so I’d recommend to use it as a last resort.

dimitarvp

dimitarvp

no_assoc_constraint will indeed give you nice Changeset error that you can directly work with in forms.

But if for one reason or another that’s not an option for you then you could always take the direct route:

category_id = 123 # desired parent id goes here
query = from(c in Category, where: c.parent_id == ^category_id)
children_count = Repo.aggregate(query, :count, :id)
if children_count > 0 do
  # construct and/or handle an error here and act on it
else
  # all good, you can delete the category
end
sbuttgereit

sbuttgereit

But isn’t this in effect just Ecto.Changeset.foreign_key_constraint/3 except performing the foreign key check fully manually in advance?

My understanding is that database constraint validations (unique, foreign key, etc.) in Changesets aren’t checked in advance and rely on database error reporting to return a Changeset error post-execution attempt. Using a Changeset here with a foreign_key_constraint/3 check allows the database constraint to abort the database transaction on query with the appropriate error where Ecto picks it up and report it as a Changeset error. So while what your saying will work, I’m not sure I see the advantage to handling that way rather than submitting a Changeset… two queries vs. one.

sharkmyster

sharkmyster OP

So, using a changeset and no_assoc_constraint doesn’t work for me.

 def delete_category_by_id(id) do
    Repo.one!(from(c in Category, where: c.id == ^id))
    |> Ecto.Changeset.change()
    |> Ecto.Changeset.no_assoc_constraint(:categories)
    |> Repo.delete()
  end

I get the following error:

cannot add constraint to changeset because association categories does not exist. Did you mean answers?

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
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

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
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
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews