felix-starman

felix-starman

Handling a custom SQL signal similar to Changeset constraint functions?

So, I’m using MySQL, and having a table where I’m restricting the ability to insert/update records to have overlaps, but end_date is allowed to be NULL.

Since MySQL doesn’t have extensions around this, the easiest way to do it is with a trigger.

I have the following triggers:

CREATE TRIGGER memberships_insert_overlap
    BEFORE INSERT
    ON team_memberships FOR EACH ROW
BEGIN
    DECLARE rowcount INT;

    SELECT COUNT(*) INTO rowcount FROM team_memberships
    WHERE person_id = NEW.person_id
        AND (NEW.start_date <= COALESCE(end_date, '9999-12-31')) and (COALESCE(NEW.end_date, '9999-12-31') >= start_date)
        AND (NEW.start_date <= COALESCE(NEW.end_date, '9999-12-31')) and (start_date <= COALESCE(end_date, '9999-12-31'));

    IF rowcount > 0 THEN
        signal sqlstate '45000' set message_text = 'overlap not allowed team_memberships.no_overlap';
    END IF;

END;


CREATE TRIGGER memberships_update_overlap
    BEFORE UPDATE
    ON team_memberships FOR EACH ROW
BEGIN
    DECLARE rowcount INT;

    SELECT COUNT(*) INTO rowcount FROM team_memberships
    WHERE person_id = NEW.person_id AND id != OLD.id
        AND (NEW.start_date <= COALESCE(end_date, '9999-12-31')) and (COALESCE(NEW.end_date, '9999-12-31') >= start_date)
        AND (NEW.start_date <= COALESCE(NEW.end_date, '9999-12-31')) and (start_date <= COALESCE(end_date, '9999-12-31'));

    IF rowcount > 0 THEN
        signal sqlstate '45000' set message_text = 'overlap not allowed team_memberships.no_overlap';
    END IF;
END;

I’m getting the typical/expected (MyXQL.Error) (1644) overlap not allowed team_memberships.no_overlap

I feel like there’s probably something I’m missing with what sqlstate should be set to for “emulating” a constraint, or that there’s some place in MyXQL where I can register a custom handler.

Anyone have any ideas?

I’d rather not litter my code w/ error-catching statements wherever we do inserts/updates.

EDIT: I should note, I’m not concerned about the trigger logic itself. That works fine. I’m wondering if there’s a better way to wrap up this interface.

Marked As Solved

felix-starman

felix-starman

For anyone who comes across this in the future, extra_error_codes currently only allows the raised error to include a name: i.e. ** (MyXQL.Error) (1644) (ER_SIGNAL_EXCEPTION) overlap not allowed instead of just ** (MyXQL.Error) (1644) overlap not allowed .

I’m not sure what follows was the “right” way to do it and I’m sure MySQL DBAs would be shaking their heads, but it’s what I did.

Since it’s still similar enough to a duplicate entry/unique constraint if you turn your head sideways and squint at it, I just updated the SQLSTATE to 23000, and MYSQL_ERRNO to 1062, which maps to ER_DUP_ENTRY (used for unique constaints).

For completeness, here’s the migration.
This basically rejects any insert/update that is overlapping on date ranges, including nulls on the end_date.

I wouldn’t say it’s “good”. But it gets the job done.

defmodule MyApp.Repo.Migrations.AddNonoverlapTriggerToTeamMemberships do
  @moduledoc """
  From https://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap

  Proof:
  Let ConditionA Mean that DateRange A Completely After DateRange B

  _                        |---- DateRange A ------|
  |---Date Range B -----|                          _
  (True if StartA > EndB)

  Let ConditionB Mean that DateRange A is Completely Before DateRange B

  |---- DateRange A -----|                        _
  _                          |---Date Range B ----|
  (True if EndA < StartB)

  Then Overlap exists if Neither A Nor B is true -
  (If one range is neither completely after the other,
  nor completely before the other, then they must overlap.)

  Now one of De Morgan's laws says that:

  Not (A Or B) <=> Not A And Not B

  Which translates to: (StartA <= EndB)  and  (EndA >= StartB)
  """

  use MyApp.Migration

  def up do
    insert_trigger_sql = ~s"""
    CREATE TRIGGER memberships_insert_overlap
      BEFORE INSERT
      ON team_memberships FOR EACH ROW
    BEGIN
      DECLARE rowcount INT;
      DECLARE msg VARCHAR(200);

      SELECT COUNT(*) INTO rowcount FROM team_memberships
      WHERE person_id = NEW.person_id
        AND (NEW.start_date <= COALESCE(end_date, '9999-12-31')) AND (COALESCE(NEW.end_date, '9999-12-31') >= start_date)
        AND (NEW.start_date <= COALESCE(NEW.end_date, '9999-12-31')) AND (start_date <= COALESCE(end_date, '9999-12-31'));

      IF rowcount > 0 THEN
          set msg = CONCAT('Duplicate entry \\'', COALESCE(NEW.end_date, 'NULL'), '\\' for key \\'team_memberships.no_overlap\\'');
          signal sqlstate '23000' set MESSAGE_TEXT = msg, MYSQL_ERRNO = 1062;
      END IF;
    END;
    """

    update_trigger_sql = ~s"""
    CREATE TRIGGER memberships_update_overlap
      BEFORE UPDATE
      ON team_memberships FOR EACH ROW
    BEGIN
      DECLARE rowcount INT;
      DECLARE msg VARCHAR(200);

      SELECT COUNT(*) INTO rowcount FROM team_memberships
      WHERE person_id = NEW.person_id AND id != OLD.id
        AND (NEW.start_date <= COALESCE(end_date, '9999-12-31')) and (COALESCE(NEW.end_date, '9999-12-31') >= start_date)
        AND (NEW.start_date <= COALESCE(NEW.end_date, '9999-12-31')) and (start_date <= COALESCE(end_date, '9999-12-31'));

      IF rowcount > 0 THEN
          set msg = CONCAT('Duplicate entry \\'', COALESCE(NEW.end_date, 'NULL'), '\\' for key \\'team_memberships.no_overlap\\'');
          signal sqlstate '23000' set MESSAGE_TEXT = msg, MYSQL_ERRNO = 1062;
      END IF;
    END;
    """

    drop_triggers()
    repo().query!(insert_trigger_sql)
    repo().query!(update_trigger_sql)
  end

  def down do
    drop_triggers()
  end

  defp drop_triggers do
    repo().query!("DROP TRIGGER IF EXISTS memberships_insert_overlap")
    repo().query!("DROP TRIGGER IF EXISTS memberships_update_overlap")
  end
end

I may open a proposal thread for discussion about the ecto_sql adapters to allow custom handling of error codes through something like an mfa tuple from config.

Where Next?

Popular in Questions Top

gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New

Other popular topics Top

WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29703 241
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54250 245
New

We're in Beta

About us Mission Statement