Here are my tables:
CREATE TABLE users(
user_id INT,
channel_id INT NOT NULL UNIQUE,
PRIMARY KEY (user_id)
);
CREATE TABLE credits(
user_id INT,
number_of_items INT CHECK(number_of_items > 0),
expiration DATETIME,
PRIMARY KEY (user_id, number_of_items, expiration),
FOREIGN KEY (user_id) REFERENCES users (user_id)
);
CREATE TABLE users_items(
user_id INT,
item_id INT,
PRIMARY KEY (user_id, item_id),
FOREIGN KEY (user_id) REFERENCES users (user_id)
);
and here is the trigger I have implemented:
CREATE TRIGGER check_has_enough_credits_to_monitor_item
BEFORE INSERT ON users_items
BEGIN
SELECT
CASE
WHEN (SELECT COUNT(*) FROM users_items WHERE user_id = NEW.user_id) >
(SELECT sum(number_of_items) FROM credits WHERE user_id = NEW.user_id)
THEN RAISE (ABORT, 'No more items allowed')
END;
END;
I want this trigger to prevent a row from being inserted in the users_items table if the user with that ID already has surpassed his credit limit or his credits have expired, however, when I have tested it using this fiddle the trigger does not raise an error. Currently the trigger just checks if the number of credits allowed against the number of items added to users_items and does not check the date, but I plan on checking the date by adding something like AND expiration >= datetime('now') to the trigger to make it look like this:
CREATE TRIGGER check_has_enough_credits_to_monitor_item
BEFORE INSERT ON users_items
BEGIN
SELECT
CASE
WHEN (SELECT COUNT(*) FROM users_items WHERE user_id = NEW.user_id) >=
(SELECT sum(number_of_items) FROM credits WHERE user_id = NEW.user_id AND expiration >= datetime('now'))
THEN RAISE (ABORT, 'No more items allowed')
END;
END;