सामग्री पर जाएँ
ऑराबेस लोगो
aurabase

Call functions with rpc()

Run logic that lives in the database with one call, shape what it returns with the usual filters, and turn its exceptions into errors your app can read.

कैसे-करें गाइड9 मि॰ पढ़ेंस्तर मध्यवर्ती

यह पेज अभी तक आपकी भाषा में उपलब्ध नहीं है. इसे अंग्रेजी में दिखाया गया है.

rpc(name, args) calls a PostgreSQL function of your project and returns its result. It is the door for anything a single read or write cannot express: several statements in one transaction, a computed value, a search with your own SQL. Over REST, the same call is POST /v1/db/rpc/{name} with the arguments as a JSON object. Creating functions is covered in Database functions; this page calls them.

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.

  • AURABASE_URL and AURABASE_ANON_KEY in the environment, for the SDK and curl examples.

The examples create the table qd_rpc_scores and four functions named qd_rpc_…, then remove them.

Functions to call#

create table qd_rpc_scores (id int primary key, player text not null, points int not null);
insert into qd_rpc_scores values (1, 'ada', 30), (2, 'bob', 12), (3, 'cy', 25), (4, 'ada', 5);
create policy qd_rpc_scores_read on qd_rpc_scores for select to aura_anon, aura_authenticated using (true);

create function qd_rpc_top(p_min int default 0) returns setof qd_rpc_scores
language sql stable as $$
  select * from qd_rpc_scores where points >= p_min order by points desc
$$;

create function qd_rpc_totals() returns table (player text, total bigint)
language sql stable as $$
  select player, sum(points) from qd_rpc_scores group by player order by 2 desc
$$;

create function qd_rpc_check(p_points int) returns int
language plpgsql as $$
begin
  if p_points < 0 then
    raise exception 'points must be positive' using errcode = '22023';
  end if;
  if p_points > 100 then
    raise exception 'too many points: %', p_points;
  end if;
  return p_points;
end
$$;

create function qd_rpc_noop() returns void language sql as $$ select $$;

grant execute on function qd_rpc_top(int), qd_rpc_totals(), qd_rpc_check(int), qd_rpc_noop()
  to aura_anon, aura_authenticated;
  ℹ No results (0 rows).

The policy lets anyone read the scores; the functions are security invoker (the default), so they read the table with the caller's rights. A function created in SQL gets no EXECUTE for the public roles until you grant it, as above.

Call a function#

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

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

const { data, error } = await aura.rpc('qd_rpc_check', { p_points: 42 })
console.log(data, error)
42 null

Over REST:

curl -s -X POST "$AURABASE_URL/v1/db/rpc/qd_rpc_top" \
  -H "apikey: $AURABASE_ANON_KEY" -H 'content-type: application/json' \
  -d '{"p_min": 20}'
echo
{"data":[{"id":1,"player":"ada","points":30},
 {"id":3,"player":"cy","points":25}],"meta":{}}

From SQL, call it like any function: aura db raw "select qd_rpc_check(42)".

What comes back#

The function returnsdata
A scalar (int, text, jsonb…)The value: 42, "text", an object.
setof <table>An array of rows of that table.
table (col type, …)An array of objects with those columns.
voidnull.
import { createClient } from '@aurabase/aurabase-js'

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

console.log('setof:', (await aura.rpc('qd_rpc_top', { p_min: 20 })).data)
console.log('table:', (await aura.rpc('qd_rpc_totals')).data)
console.log('void:', (await aura.rpc('qd_rpc_noop')).data)
setof: [
  { id: 1, player: 'ada', points: 30 },
  { id: 3, player: 'cy', points: 25 }
]
table: [
  { player: 'ada', total: 35 },
  { player: 'cy', total: 25 },
  { player: 'bob', total: 12 }
]
void: null

Rows returned by a function are capped at 1,000 per call, like reads.

Filter and sort returned rows#

When a function returns rows, chain the methods of a read: select(), filters, order(), limit(), single(). They apply to the rows the function returns:

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

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

const ada = await aura.rpc('qd_rpc_top').eq('player', 'ada').select('points')
console.log('filter:', ada.data)

const lowest = await aura.rpc('qd_rpc_top').order('points').limit(2).select('player, points')
console.log('order:', lowest.data)

const best = await aura.rpc('qd_rpc_top', { p_min: 26 }).single()
console.log('single:', best.data, best.error)
filter: [ { points: 30 }, { points: 5 } ]
order: [ { player: 'ada', points: 5 }, { player: 'bob', points: 12 } ]
single: { id: 1, player: 'ada', points: 30 } null

GET, HEAD and counts#

rpc() sends a POST by default. A function that does not write (declared stable or immutable) can be called with GET, which puts the arguments in the query string and can be cached by HTTP caches; head: true returns only the count:

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

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

const get = await aura.rpc('qd_rpc_top', { p_min: 20 }, { get: true }).select('player')
console.log('get:', get.data)

const head = await aura.rpc('qd_rpc_top', { p_min: 10 }, { head: true, count: 'exact' })
console.log('head:', head.data, head.count)

const post = await aura.rpc('qd_rpc_top', { p_min: 10 }, { count: 'exact' }).limit(1)
console.log('post with count:', post.data?.length, post.count)
get: [ { player: 'ada' }, { player: 'cy' } ]
head: null 3
post with count: 1 null

The count is lost on a POST call for now (count: null): ask for it with head: true, or with get: true for a read-only function. Over REST, GET /v1/db/rpc/qd_rpc_top?p_min=20.

Arguments#

  • Arguments are passed by name, as a JSON object whose keys are the parameter names ({ p_min: 20 }). Their order does not matter.
  • A parameter with a default (p_min int default 0) can be left out.
  • The function is found by its name and the names of the arguments you send: a wrong or missing argument name gives 404 FUNCTION_NOT_FOUND, not a type error.
  • Two functions with the same name are told apart by their parameter names only. Give each function its own name.
  • A function created or replaced a moment ago may answer 404 FUNCTION_NOT_FOUND until the API reloads its schema; the gateway retries for about a second.
import { createClient } from '@aurabase/aurabase-js'

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

const wrongName = await aura.rpc('qd_rpc_check', { points: 5 })
console.log(wrongName.error?.status, wrongName.error?.code, wrongName.error?.message)

const missing = await aura.rpc('qd_rpc_nope')
console.log(missing.error?.status, missing.error?.code, missing.error?.message)
404 FUNCTION_NOT_FOUND Could not find the function qd_rpc_check(points) in the schema cache
404 FUNCTION_NOT_FOUND Could not find the function qd_rpc_nope without parameters in the schema cache

Errors raised by a function#

raise exception in PL/pgSQL stops the function, rolls back everything it did, and becomes the error of the call. The message is yours; the code depends on the SQLSTATE:

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

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

const invalid = await aura.rpc('qd_rpc_check', { p_points: -1 })
console.log(invalid.error?.status, invalid.error?.code, invalid.error?.message)

const plain = await aura.rpc('qd_rpc_check', { p_points: 500 })
console.log(plain.error?.status, plain.error?.code, plain.error?.message)
400 INVALID_INPUT points must be positive
400 POSTGREST_ERROR too many points: 500

A plain raise exception (SQLSTATE P0001) arrives as 400 POSTGREST_ERROR, with the SQLSTATE in upstream_code of the REST body. To let your app branch on the error, choose an SQLSTATE that the API maps to a code (22023 → INVALID_INPUT, 23505 → DUPLICATE_KEY, 42501 → INSUFFICIENT_PRIVILEGE), or put a stable prefix in the message.

Who can call a function#

QuestionRule
Who can call itThe roles with EXECUTE: grant execute on function f(int) to aura_authenticated. Others get 403 INSUFFICIENT_PRIVILEGE permission denied for function f. The service_role key can call every function.
With whose rights does it runsecurity invoker (default): the caller's, so the policies of the tables apply to the caller. security definer: the owner's, which bypasses row level security.
Who is the caller insideauth.uid() is the signed-in user, null for the anon key.

security definer functions cannot be created through aura db raw; use the function API with --security definer and read the precautions in Database functions. The example function todo_count is granted to aura_authenticated only: the anon key gets 403, as shown in Example schema.

Result#

aura db raw "select qd_rpc_check(7) as checked, (select count(*) from qd_rpc_top(10)) as top_rows"
  checked │ top_rows
  ────────┼─────────
  7       │ 3

  ℹ 1 row(s).

Common errors#

MessageCauseFix
404 FUNCTION_NOT_FOUND Could not find the function f(a) in the schema cacheNo function with that name and those argument names, or it was created a moment ago.Check the names of the arguments; retry after a second.
403 INSUFFICIENT_PRIVILEGE permission denied for function fThe caller's role has no EXECUTE.grant execute on function f(<types>) to aura_authenticated.
400 POSTGREST_ERROR <your message>The function raised an exception (SQLSTATE P0001).Handle it in the app; use a mapped SQLSTATE to branch on code.
data: [] while the table has rowsThe function is security invoker and the caller's policies hide the rows.Add a policy, or sign the user in.
count: nullcount on a POST call.Use head: true or get: true.
400 BAD_REQUEST … The 'SECURITY DEFINER' option is not allowed in raw queriesCreating a definer function through aura db raw.Use the function API (Database functions).

Clean up#

aura db raw "drop function qd_rpc_top(int); drop function qd_rpc_totals(); drop function qd_rpc_check(int); drop function qd_rpc_noop()"
aura db raw "drop table qd_rpc_scores"
  ℹ No results (0 rows).
  ℹ No results (0 rows).

See also#