Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One solution is to create a view for the <code>locations</code> table with a INSTEAD OF trigger on the view, then insert into the view. Here's what that would look like:</p> <p>View:</p> <pre><code>CREATE VIEW locations_view AS SELECT * FROM locations; </code></pre> <p>Trigger:</p> <pre><code>CREATE TRIGGER update_location INSTEAD OF INSERT ON locations_view FOR EACH ROW BEGIN INSERT OR REPLACE INTO locations (_id, name, latitude, longitude) VALUES ( COALESCE(NEW._id, (SELECT _id FROM locations WHERE latitude = NEW.latitude AND longitude = NEW.longitude)), NEW.name, NEW.latitude, NEW.longitude ); END; </code></pre> <p>Instead of inserting into the <code>locations</code> table, you insert into the <code>locations_view</code> view. The trigger will take care of providing the correct <code>_id</code> value by using the sub-select. If, for some reason, the insert already contains an <code>_id</code> the <code>COALESCE</code> will keep it and override an existing one in the table.</p> <p>You'll probably want to check how much the sub-select affects performance and compare that to other possible changes you could make, but it does allow you keep this logic out of your code.</p> <p>I tried some other solutions involving triggers on the table itself based on INSERT OR IGNORE, but it seems that BEFORE and AFTER triggers only trigger if it will actually insert into the table.</p> <p>You might find <a href="https://stackoverflow.com/a/4330694/857618">this answer</a> helpful, which is the basis for the trigger.</p> <p>Edit: Due to BEFORE and AFTER triggers not firing when an insert is ignored (which could then have been updated instead), we need to rewrite the insert with an INSTEAD OF trigger. Unfortunately, those don't work with tables - we have to create a view to use it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload