Database Functions
Postgres has built-in support for SQL functions. These functions live inside your database, and they can be used with the API.
Quick demo
Getting started
Supabase provides several options for creating database functions. You can use the Dashboard or create them directly using SQL. We provide a SQL editor within the Dashboard, or you can connect to your database and run the SQL queries yourself.
- Go to the "SQL editor" section.
- Click "New Query".
- Enter the SQL to create or replace your Database function.
- Click "Run" or cmd+enter (ctrl+enter).
Simple functions
Let's create a basic Database Function which returns a string "hello world".
Show/Hide Details
At it's most basic a function has the following parts:
create or replace function hello_world()
: The function declaration, wherehello_world
is the name of the function. You can use eithercreate
when creating a new function orreplace
when replacing an existing function. Or you can usecreate or replace
together to handle either.returns text
: The type of data that the function returns. If it returns nothing, you canreturns void
.language sql
: The language used inside the function body. This can also be a procedural language:plpgsql
,plv8
,plpython
, etc.as $$
: The function wrapper. Anything enclosed inside the$$
symbols will be part of the function body.select 'hello world';
: A simple function body. The finalselect
statement inside a function body will be returned if there are no statements following it.$$;
: The closing symbols of the function wrapper.
After the Function is created, we have several ways of "executing" the function - either directly inside the database using SQL, or with one of the client libraries.
Returning data sets
Database Functions can also return data sets from Tables or Views.
For example, if we had a database with some Star Wars data inside:
Planets
id | name |
---|---|
1 | Tattoine |
2 | Alderaan |
3 | Kashyyyk |
People
id | name | planet_id |
---|---|---|
1 | Anakin Skywalker | 1 |
2 | Luke Skywalker | 1 |
3 | Princess Leia | 2 |
4 | Chewbacca | 3 |
We could create a function which returns all the planets:
Because this function returns a table set, we can also apply filters and selectors. For example, if we only wanted the first planet:
Passing parameters
Let's create a Function to insert a new planet into the planets
table and return the new ID. Note that this time we're using the plpgsql
language.
Once again, you can execute this function either inside your database using a select
query, or with the client libraries:
Suggestions
Database Functions vs Edge Functions
For data-intensive operations, use Database Functions, which are executed within your database and can be called remotely using the REST and GraphQL API.
For use-cases which require low-latency, use Edge Functions, which are globally-distributed and can be written in Typescript.
Security definer
vs invoker
Postgres allows you to specify whether you want the function to be executed as the user calling the function (invoker
), or as the creator of the function (definer
). For example:
It is best practice to use security invoker
(which is also the default). If you ever use security definer
, you must set the search_path
.
This limits the potential damage if you allow access to schemas which the user executing the function should not have.
Function privileges
By default, database functions can be executed by any role. There are two main ways to restrict this:
-
On a case-by-case basis. Specifically revoke permissions for functions you want to protect. Execution needs to be revoked for both
public
and the role you're restricting: -
Restrict function execution by default. Specifically grant access when you want a function to be executable by a specific role.
To restrict all existing functions, revoke execution permissions from both
public
and the role you want to restrict:To restrict all new functions, change the default privileges for both
public
and the role you want to restrict:You can then regrant permissions for a specific function to a specific role:
Debugging functions
You can add logs to help you debug functions. This is especially recommended for complex functions.
Good targets to log include:
- Values of (non-sensitive) variables
- Returned results from queries
General logging
To create custom logs in the Dashboard's Postgres Logs, you can use the raise
keyword. By default, there are 3 observed severity levels:
log
warning
exception
(error level)
Error handling
You can create custom errors with the raise exception
keywords.
A common pattern is to throw an error when a variable doesn't meet a condition:
Value checking is common, so Postgres provides a shorthand: the assert
keyword. It uses the following format:
Below is an example
Error messages can also be captured and modified with the exception
keyword:
Advanced logging
For more complex functions or complicated debugging, try logging:
- Formatted variables
- Individual rows
- Start and end of function calls
Resources
- Official Client libraries: JavaScript and Flutter
- Community client libraries: github.com/supabase-community
- PostgreSQL Official Docs: Chapter 9. Functions and Operators
- PostgreSQL Reference: CREATE FUNCTION