# SQL Functions

Source: https://cubibase.com/docs/database/functions

Also available: [Markdown version](https://cubibase.com/docs/database/functions.md) · [llms.txt](https://cubibase.com/llms.txt) · [full site content](https://cubibase.com/llms-full.txt)

Create, edit, and replace SQL or PL/pgSQL functions in the public schema from the Console. Functions power triggers, encapsulate queries, and can be granted to the Data API role. These are PostgreSQL functions — for TypeScript/JavaScript code in the managed runtime, see the CubiBase Functions docs.

## Creating a function

The editor takes a name, an argument list, a return type, and a body. Bodies can contain multiple statements — unlike the SQL editor, a function body is a program, not a single query.

| Option | Values | Notes |
| --- | --- | --- |
| Language | `sql`, `plpgsql` | SQL for single queries; PL/pgSQL for logic and loops |
| Volatility | `VOLATILE`, `STABLE`, `IMMUTABLE` | Tell the planner how the function behaves |
| Security | `INVOKER`, `DEFINER` | DEFINER runs with the function owner’s rights |
| Strict | on / off | STRICT returns NULL immediately when any argument is NULL |
| Returns set | on / off | `SETOF` for functions that return multiple rows |
| Replace | on / off | `CREATE OR REPLACE` keeps existing grants |

**Example · PL/pgSQL**

```sql
CREATE FUNCTION public.customer_count(plan_name text)
RETURNS bigint
LANGUAGE plpgsql
STABLE
SECURITY INVOKER
SET search_path = public, pg_catalog
AS $$
BEGIN
  RETURN (SELECT count(*) FROM public.customers WHERE plan = plan_name);
END;
$$;
```

Every function is created with `SET search_path = public, pg_catalog`, so name resolution cannot be hijacked by objects in other schemas — important for SECURITY DEFINER functions.

## Overloads and dropping

- PostgreSQL identifies a function by name plus argument types. Two functions named `search` with different argument types can coexist.
- When you drop (or toggle API access on) an overloaded name, the Console asks which signature you mean — pass the argument types, e.g. `id uuid` vs `term text`.
- Replacing a function keeps its grants; dropping it removes them.

## Editing a function

Every function you created has an Edit button. It opens the same form prefilled with the current definition and saves with `CREATE OR REPLACE`, so existing grants and dependent triggers or views keep working.

- Editable: the body, argument defaults, volatility, security (INVOKER/DEFINER), STRICT, and the Data API grant.
- Fixed: the name, argument names/types/modes, return type, and language — PostgreSQL identifies a function by that signature and cannot change it in place. To change the signature, create a new function and drop the old one.
- Replacing keeps EXECUTE grants; dropping removes them.

> **note**: Extension functions cannot be edited — see below. Only functions you created are editable.

## Extension functions are read-only

Enabling an extension (Database → Extensions, e.g. `pgcrypto` or `pg_trgm`) installs its functions into the public schema. Those functions belong to the extension, not to you:

- Hidden by default: the Functions screen lists only your own functions. Tick “Show extension functions” to see the rest, marked with an `extension: pgcrypto` badge.
- Read-only: they cannot be edited, replaced, or dropped — the API refuses with `403 extension_function`. PostgreSQL itself also refuses to drop a function an extension depends on.
- They leave only with their extension: disable it on the Extensions screen and its functions disappear together.
- You can still grant or revoke Data API EXECUTE on them — that is how you expose e.g. `gen_random_uuid()` over RPC without writing a wrapper.

> **note**: The lock survives backups: restoring a project hands your objects back to your project role but never extension members, so a restored database cannot be used to rewrite extension internals.

## Data API execute permission

Functions are private by default: the Console’s `sql` role can run them, the `api` role cannot. The Data API execute switch maps to a real grant:

**SQL · what the switch runs**

```sql
GRANT EXECUTE ON FUNCTION public.customer_count(text) TO example_project_db_api;
-- off:
REVOKE EXECUTE ON FUNCTION public.customer_count(text) FROM example_project_db_api;
```

With the grant on, the function is callable from your app at `POST /rest/v1/rpc/{name}` on the project host, with the publishable key and the end-user JWT. The body is a JSON object of named arguments; the call runs with the caller’s identity, so RLS applies to SECURITY INVOKER functions.

**RPC · request**

```http
POST https://example-project.api.cubibase.com/rest/v1/rpc/customer_count
apikey: cb_pub_EXAMPLE_ONLY
Authorization: Bearer <USER_JWT>
Content-Type: application/json

{ "plan_name": "pro" }
```

> **note**: The grant covers the function itself. Tables the body reads still need their own grants for the api role — expose them in the Console, or the call fails with 403. See Calling functions (RPC) for result shapes, overloads, and errors.

## SECURITY DEFINER, carefully

- A DEFINER function runs with its owner’s privileges, so it can bypass the caller’s RLS policies. That is the point — and the risk.
- Grant EXECUTE to the api role only when the function is meant to expose that capability.
- Validate arguments inside the function; a DEFINER function is a door through your policies.

> **warning**: A SECURITY DEFINER function granted to the api role can read or write rows the caller’s policies would block. Review the body before enabling Data API execute.

## Additional resources

- [Calling functions (RPC)](https://cubibase.com/docs/data-api/rpc) Call a granted function from your app over the Data API.
- [Triggers](https://cubibase.com/docs/database/triggers) Run a function automatically on INSERT, UPDATE, DELETE, or TRUNCATE.
- [Types](https://cubibase.com/docs/database/types) Enums and composites for arguments and return values.
- [SQL editor](https://cubibase.com/docs/database/sql-editor) Call your function with SELECT to test it.
- [CubiBase Functions](https://cubibase.com/docs/functions) TypeScript/JavaScript in the managed runtime — a different feature.
