Natively write SQL functions/triggers with Drizzle?
Is it possible to, for example, write this kind of logic directly in Drizzle's schema?
-- Checks if a user already has an active ban before inserting a new one.
CREATE OR REPLACE FUNCTION check_active_ban()
RETURNS TRIGGER AS $$
BEGIN
-- Check if there is an existing ban for the same user_id with expire NULL or in the future
IF EXISTS (
SELECT 1 FROM bans
WHERE "userId" = NEW."userId"
AND (expires IS NULL OR expires > CURRENT_TIMESTAMP)
) THEN
-- Raise an exception to prevent the insert
RAISE EXCEPTION 'A ban for this user already exists and is not expired';
END IF;
-- Allow the insert
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-------------------------------- Triggers --------------------------------
CREATE OR REPLACE TRIGGER trigger_before_bans_insert
BEFORE INSERT ON bans
FOR EACH ROW
EXECUTE FUNCTION check_active_ban();-- Checks if a user already has an active ban before inserting a new one.
CREATE OR REPLACE FUNCTION check_active_ban()
RETURNS TRIGGER AS $$
BEGIN
-- Check if there is an existing ban for the same user_id with expire NULL or in the future
IF EXISTS (
SELECT 1 FROM bans
WHERE "userId" = NEW."userId"
AND (expires IS NULL OR expires > CURRENT_TIMESTAMP)
) THEN
-- Raise an exception to prevent the insert
RAISE EXCEPTION 'A ban for this user already exists and is not expired';
END IF;
-- Allow the insert
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-------------------------------- Triggers --------------------------------
CREATE OR REPLACE TRIGGER trigger_before_bans_insert
BEFORE INSERT ON bans
FOR EACH ROW
EXECUTE FUNCTION check_active_ban();