انتقل إلى المحتوى
شعار أوراباسي
aurabase

Database functions

Put logic next to your data: create a SQL or PL/pgSQL function, decide who may call it, call it from the SDK, and know when a security definer function is the right door and how to keep it safe.

دليل عملي11 د قراءةالمستوى وسيطة

هذه الصفحة غير متوفرة بلغتك بعد. يتم عرضه باللغة الإنجليزية.

A database function is SQL or PL/pgSQL stored in your project's schema. Your application calls it with rpc() of the SDK or POST /v1/db/rpc/{name}, a trigger runs it on writes, and SQL calls it like any function. Database functions are not Edge Functions: aura db function manages the first, aura functions the second.

Prerequisites#

  • A linked project: aura link <project-id>.

  • The example schema, installed with the service role key of the project:

    export AURABASE_SERVICE_ROLE_KEY=aura_sk_…
    aura db seed --example docs

    It creates profiles, orgs, org_members, posts, todos, the view open_todos and the function todo_count(p_user uuid). See Example schema.

The examples create functions named sch_fn_…, then remove them. todo_count(p_user uuid) of the example schema is a function of the same kind, granted to signed-in users.

Where to create a function#

DoorCommandNotes
CLIaura db function create, list, dropSends the function API calls below.
Function APIPOST /v1/db/{project_id}/functions, GET /v1/db/{project_id}/functions, DELETE /v1/db/{project_id}/functions/{name}service_role key for all three.
SDKdb.createFunction(), db.listFunctions(), db.dropFunction()Same API, from a server with the service_role key.
SQLcreate function … with aura db rawAny argument mode, returns table (…), dynamic execute. security definer is refused.
StudioFunctions tab of the table editorLists, creates (name, arguments, return type, language, security, GRANT EXECUTE TO, body) and drops functions, through the function API.

The function API takes a name, args (each name, data_type, mode), returns, language (sql or plpgsql), body (without the enclosing $$), and optional security (invoker or definer) and grant_execute_to (a list of roles).

Create a function with the CLI#

A SQL function that counts the open todos of a user, callable by signed-in users:

aura db function create sch_fn_open_count \
  --language sql --returns bigint --args "p_user:uuid" \
  --body 'select count(*) from todos where user_id = p_user and not done' \
  --grant-execute-to authenticated
  ✔ Function 'sch_fn_open_count' created (sql → bigint).
  • EXECUTE granted to: authenticated

--args takes name:type pairs separated by commas, --body-file reads the body from a file, --language defaults to plpgsql and --returns to void.

What the server enforces#

RuleDetail
security invoker by defaultThe function runs with the rights of its caller, so the policies of the tables it reads apply. --security definer must be asked for.
A fixed search_pathEvery function is created with set search_path = <project schema>: names in the body resolve in your schema, whoever calls it.
Nobody can call a new functionEXECUTE is revoked from PUBLIC and from every platform role, then granted to the roles of --grant-execute-to only. Re-creating a function resets its grants the same way.
Allowed granteesanon, authenticated, service_role (or their PostgreSQL names aura_anon, aura_authenticated, aura_service_role).
Argumentsin mode only. Other modes, returns table (…) and default values need SQL.
BodyChecked like an aura db raw query, and stricter: no dynamic execute, no change to row level security.
One signature per nameRe-creating a function with other argument types is refused, since PostgreSQL would add a second function next to the first. Drop it first.

A function created in SQL through aura db raw gets no EXECUTE for the platform roles either (measured: the anon key gets 403 INSUFFICIENT_PRIVILEGE on it): grant it yourself with grant execute on function <name>(<types>) to aura_authenticated. It has no fixed search_path unless you write set search_path = … in its definition.

Call it with rpc()#

The SDK calls a function with rpc(name, args). A signed-in user creates a todo, then counts its open todos; the anon key is refused, since the function was granted to authenticated only:

import { createClient } from '@aurabase/aurabase-js'

const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)

const anon = await aura.rpc('sch_fn_open_count', { p_user: '00000000-0000-4000-8000-0000000000a1' })
console.log('anon:', anon.error?.status, anon.error?.code)

const email = `functions-${Date.now()}@example.com`
const password = 'correct-horse-battery-9'
const signUp = await aura.auth.signUp({ email, password })
if (signUp.error) throw signUp.error
const { data: session, error } = await aura.auth.signInWithPassword({ email, password })
if (error) throw error
const me = session!.user.id

await aura.from('todos').insert({ user_id: me, title: 'Call a database function' })
const mine = await aura.rpc('sch_fn_open_count', { p_user: me })
console.log('mine:', mine.data, mine.error)

const alice = await aura.rpc('sch_fn_open_count', { p_user: '00000000-0000-4000-8000-0000000000a1' })
console.log('alice, seen by this user:', alice.data)
anon: 403 INSUFFICIENT_PRIVILEGE
mine: 1 null
alice, seen by this user: 0

The function is security invoker: for this user, the owner policy of todos hides Alice's rows, so her count is 0. Arguments are sent by name, as JSON. Over REST, the same call is POST /v1/db/rpc/sch_fn_open_count with the body {"p_user": "…"} and the user's token or a key in the headers. The sign-up above works because email confirmation is turned off on the test project; a project requires it by default.

A PL/pgSQL function from the SDK#

PL/pgSQL adds variables, conditions and error messages. This function adds a todo for the signed-in user and refuses an empty title; auth.uid() reads the user from the request:

import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)

const created = await admin.db.createFunction({
  name: 'sch_fn_add_todo',
  args: [{ name: 'p_title', data_type: 'text', mode: 'IN' }],
  returns: 'bigint',
  language: 'plpgsql',
  body: `
declare new_id bigint;
begin
  if coalesce(trim(p_title), '') = '' then
    raise exception 'title is required';
  end if;
  insert into todos (user_id, title) values (auth.uid(), p_title) returning id into new_id;
  return new_id;
end`,
  grant_execute_to: ['authenticated'],
})
console.log('created:', created.error)

const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)
const email = `plpgsql-${Date.now()}@example.com`
const password = 'correct-horse-battery-9'
const signUp = await aura.auth.signUp({ email, password })
if (signUp.error) throw signUp.error
const { error } = await aura.auth.signInWithPassword({ email, password })
if (error) throw error

const ok = await aura.rpc('sch_fn_add_todo', { p_title: 'Write a PL/pgSQL function' })
console.log('ok:', typeof ok.data, ok.error)
const empty = await aura.rpc('sch_fn_add_todo', { p_title: ' ' })
console.log('empty:', empty.error?.status, empty.error?.message)
created: null
ok: number null
empty: 400 title is required

raise exception ends the function, rolls back what it wrote, and reaches the client as a 400 with your message. Since the function is security invoker, the insert still goes through the with check of the owner policy of todos.

Security invoker or definer#

security invoker (default)security definer
Runs with the rights ofThe callerThe owner of the function, the project's administrator role
Row level securityApplies to the callerBypassed: the function reads and writes every row
Created byThe CLI, the API, the SDK, SQLThe CLI, the API and the SDK only: aura db raw refuses security definer
Use it forAlmost everythingA controlled exception: a count across all users, a write the caller may not do directly

A definer function decides on its own what each caller gets. Filter with auth.uid() inside it, grant it to authenticated only, and validate every argument. Granted to anon, a definer function that reads todos returns data of every user to anyone with the anon key. Here is a narrow one, which tells a signed-in user how many todos exist in the project without showing any of them:

aura db function create sch_fn_total_todos \
  --language sql --returns bigint \
  --body 'select count(*) from todos' \
  --security definer --grant-execute-to authenticated
  ✔ Function 'sch_fn_total_todos' created (sql → bigint).
  • EXECUTE granted to: authenticated
  ⚠ SECURITY DEFINER: function executes with its owner's privileges, not the caller's.

aura db function list shows SECURITY DEFINER for such functions; review them when you audit the project.

List and drop functions#

aura db function list prints each function with its arguments, return type, language, security mode and the roles that hold EXECUTE. The administrator role of the project (tenant_<id>_admin) always holds it; --json returns the same as GET /v1/db/{project_id}/functions:

aura db function list --json | node -e 'for (const f of JSON.parse(require("fs").readFileSync(0, "utf8")))
  console.log(f.name, f.security, f.grant_execute_to.filter((r) => !r.startsWith("tenant_")).join(",") || "(nobody)")'
sch_fn_add_todo INVOKER aura_authenticated
sch_fn_open_count INVOKER aura_authenticated
sch_fn_total_todos DEFINER aura_authenticated
todo_count INVOKER aura_authenticated

Drop a function by name. The server resolves its signature; a name shared by several functions (overloads created in SQL) is refused rather than guessed:

aura db function drop sch_fn_open_count --force
  ✔ Function 'sch_fn_open_count' dropped (or already absent).

Dropping a function that a trigger uses fails: drop the trigger first (Triggers).

The same three operations over HTTP, from any language, with the service_role key:

key=(-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json')

curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/functions" "${key[@]}" -d '{
  "name": "sch_fn_greet", "args": [{"name": "p_name", "data_type": "text", "mode": "IN"}],
  "returns": "text", "language": "sql", "body": "select '"'"'Hello, '"'"' || p_name",
  "grant_execute_to": ["authenticated"]}'
echo
curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/functions" "${key[@]}" \
  | node -e 'const f = JSON.parse(require("fs").readFileSync(0, "utf8")).data.find((x) => x.name === "sch_fn_greet")
console.log(f.name, f.language, f.return_type, f.security, JSON.stringify(f.args))'
curl -s -X DELETE "$AURABASE_URL/v1/db/$PROJECT_ID/functions/sch_fn_greet" "${key[@]}"
echo
{"data":null,"meta":null}
sch_fn_greet SQL text INVOKER [{"name":"p_name","data_type":"text","mode":"IN"}]
{"data":null,"meta":null}

And from a server with the SDK, db.listFunctions() and db.dropFunction() (with db.createFunction() shown above):

import { createClient } from '@aurabase/aurabase-js'

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)

const listed = await admin.db.listFunctions()
const mine = listed.data?.find((f) => f.name === 'sch_fn_add_todo')
console.log(mine?.language, mine?.security, mine?.grant_execute_to.filter((r) => !r.startsWith('tenant_')))

const dropped = await admin.db.dropFunction('sch_fn_add_todo')
console.log('dropped:', dropped.error)
PLPGSQL INVOKER [ 'aura_authenticated' ]
dropped: null

Result#

aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000b2 "select sch_fn_total_todos() as total, todo_count('00000000-0000-4000-8000-0000000000a1') as alices_seen"
  ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000b2).
  alices_seen │ total
  ────────────┼──────
  0           │ 6

  ℹ 1 row(s).

The definer function counts every todo of the project; the invoker function todo_count sees none of Alice's for this user.

Common errors#

MessageCauseFix
403 INSUFFICIENT_PRIVILEGE permission denied for function …The caller's role has no EXECUTE.--grant-execute-to authenticated (CLI) or grant execute on function … to aura_authenticated (SQL).
404 FUNCTION_NOT_FOUND, with a hint such as Perhaps you meant to call the function todo_count(p_user)No function with this name and these argument names.Send the arguments by their exact names.
Invalid request: A function '…' already exists in this project with a DIFFERENT signature (…)Re-creating a function with other argument types.aura db function drop <name> --force, then create it.
'EXECUTE' is not allowed in a function body: SQL built at run time escapes any textual validation by nature.Dynamic SQL in a body sent to the function API.Write the statement out.
The 'SECURITY DEFINER' option is not allowed in raw queries (privilege escalation).security definer in aura db raw.Create it with aura db function create --security definer.
Invalid GRANT EXECUTE role: 'public'. Accepted values: anon, authenticated, service_role, aura_anon, aura_authenticated, aura_service_roleA role the CLI does not accept.Use one of the listed roles.
Invalid Language: 'js'. Accepted values: plpgsql, sqlAnother language.Use sql or plpgsql.
[403] FORBIDDEN: Forbidden: DDL operation is reserved to the service_role roleThe function API, including GET /functions, called with the anon key or a user token.Use the service_role key, on a server.

Clean up#

Remove the remaining functions and the todos added by the examples:

aura db function drop sch_fn_total_todos --force
aura db function drop sch_fn_add_todo --force
aura db raw "delete from todos where title in ('Call a database function', 'Write a PL/pgSQL function')"
  ✔ Function 'sch_fn_total_todos' dropped (or already absent).
  ✔ Function 'sch_fn_add_todo' dropped (or already absent).
  ℹ No results (0 rows).

The test users created by the examples stay in the project; delete them with aura auth users delete <user-id>.

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ الإبلاغ عن مشكلة