© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Drizzle TeamDT
Drizzle Team•16mo ago•
8 replies
pato

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();
Drizzle TeamJoin
The official Discord for all Drizzle related projects, such as Drizzle ORM, Drizzle Kit, Drizzle Studio and more!
11,879Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Write SQL query in Drizzle?
Drizzle TeamDTDrizzle Team / help
2y ago
Setting triggers with drizzle
Drizzle TeamDTDrizzle Team / help
2y ago
TRIGGERS in Drizzle
Drizzle TeamDTDrizzle Team / help
3y ago
Error with drizzle (sql)
Drizzle TeamDTDrizzle Team / help
2y ago