0
votes

Using sqlite I want to have a field 'url' generated from the given 'id' using a trigger both on insert and on update. For example id: '1' => url: 'test.com/1'

The table looks like this:

CREATE TABLE t1 (
  id TEXT,
  url TEXT
 );

Since sqlite can't run the same trigger for update and insert, I see two options to accomplish this.

Option A

  • run a trigger after insert, that updates the id to itself, which in turns triggers the update trigger
CREATE TRIGGER run_updates_on_insert AFTER INSERT ON t1
  BEGIN
    UPDATE t1 SET id = NEW.id WHERE id = NEW.id;
  END;

CREATE TRIGGER set_url_on_update BEFORE UPDATE on t1
  BEGIN
   UPDATE t1 SET url = 'test.com/' || NEW.id WHERE id = OLD.id;
  END;

Option B

  • replicating the logic in two separate triggers for update and insert
CREATE TRIGGER set_url_on_insert AFTER INSERT on t1
  BEGIN
   UPDATE t1 SET url = 'test.com/' || NEW.id WHERE id = NEW.id;
  END;

CREATE TRIGGER set_url_on_update BEFORE UPDATE on t1
  BEGIN
   UPDATE t1 SET url = 'test.com/' || NEW.id WHERE id = OLD.id;
  END;

Both of these options give me the desired results, I tend to favor Option A, as I only have to write the update logic once, but I was wondering if there are any other advantages/disadvantage to prefer one to the other?

EDIT: For this particular use case it is better to use generated column (see forpas answer below)

1
What is your version of SQLite? - forpas
Sqlite Version: 3.36.0 - react-newbie

1 Answers

0
votes

Since version 3.31.0 (2020-01-22) of SQLite, you can create generated columns (stored or virtual), so you don't need any triggers:

CREATE TABLE t1 (
  id TEXT,
  url TEXT GENERATED ALWAYS AS ('test.com/' || id) STORED
 );