Last active
May 16, 2024 03:38
-
-
Save elyezer/6450054 to your computer and use it in GitHub Desktop.
How to create a ring buffer table in SQLite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Example table | |
CREATE TABLE ring_buffer (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT); | |
-- Number 10 on where statement defines the ring buffer's size | |
CREATE TRIGGER delete_tail AFTER INSERT ON ring_buffer | |
BEGIN | |
DELETE FROM ring_buffer WHERE id%10=NEW.id%10 AND id!=NEW.id; | |
END; |
Based on srgian's insight a more accurate approach would be:
-- Example table
CREATE TABLE ring_buffer (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT);
-- Number 10 on where statement defines the ring buffer's size
CREATE TRIGGER delete_tail AFTER INSERT ON ring_buffer
BEGIN
DELETE FROM ring_buffer where id < NEW.id-10000;
END;
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this approach not suitable for large tables. id%10 predicate from the where clause would require computing over table scan. I would suggest delete from ring_buffer where id < NEW.id-[some_buffer_capacity] so NEW.id and buffer capacity are scalars and id is indexed