Skip to content

Instantly share code, notes, and snippets.

@TheOtherBrian1
Last active December 31, 2023 17:11
Show Gist options
  • Save TheOtherBrian1/fabee912bc0cdaae0b9735d7740b5ec5 to your computer and use it in GitHub Desktop.
Save TheOtherBrian1/fabee912bc0cdaae0b9735d7740b5ec5 to your computer and use it in GitHub Desktop.
How to log in supabase
CREATE OR REPLACE FUNCTION example (num INT DEFAULT 10) RETURNS TEXT AS $$
DECLARE
var1 INT := 20;
var2 TEXT;
BEGIN
-- Logging a variable from a SELECT query
SELECT col_1 FROM some_table INTO var1;
RAISE LOG 'logging a variable (%)', var1;
-- It is also possible to avoid using variables, by returning the values of your query to the log
RAISE LOG 'logging a query with a single return value(%)', (SELECT some_message_value FROM some_table LIMIT 1);
-- If necessary, you can even log an entire row as JSON
RAISE LOG 'logging an entire row as JSON (%)', (SELECT to_jsonb(table_name.*) FROM table_name LIMIT 1);
-- When using INSERT or UPDATE, the NEWLY created or updated values can be returned
-- into a variable
-- When using DELETE, the deleted value can be returned.
-- All three statement types use "RETURNING var INTO" syntax
INSERT INTO some_table (col_2)
VALUES('new val')
RETURNING col_2 INTO var2;
RAISE LOG 'logging a value from an INSERT (could also have been a DELETE or UPDATE) (%)', var2;
-- Besides logging, returning the variables is the only way to see their
-- values in PostgreSQL.
-- The following line concatenates the values into a string so all the variables can be returned as a single value.
-- Instead of returning variables as strings, you could create and return a composite data type, such as a Temporary table, a
-- Record type, custom type, array, or a JSON/JSONB type.
RETURN var1 || ',' || var2;
EXCEPTION
-- Handle exceptions here if needed
WHEN others THEN
RAISE EXCEPTION 'An error occurred: %', SQLERRM;
-- ALTERNATIVELY, you could use RAISE LOG
-- with the SQLERRM, e.g.: RAISE LOG 'An error occurred: %, SQLERRM;
-- The benefit of using RAISE LOG in the handler is that it will
-- allow you to write an exception that commits. It will essentially allow
-- the error handler section to behave as an independent transaction.
-- So you could execute cleanup code or INSERT values into an error management table.
-- You could even use PG_NET to send a failure message to an external
-- API: https://github.com/supabase/pg_net
-- But, once again, this is only if you use RAISE LOG instead of RAISE EXCEPTION
-- The tradeoff is that RAISE LOG will not be recognized as an error in the
-- the Dashboard's logs.
-- If you RAISE LOG in this section, you will have to RETURN
-- a value or the error handler will
-- fail
END;
$$ LANGUAGE plpgsql;
SELECT example(12222);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment