İçeriğe geç
Aurabase Logosu
aura tabanı

Triggers

Attach a function to the writes of a table: maintain updated_at, record who changed what in an audit table, fire only when a column changes, and list or remove the triggers of a table.

Nasıl yapılır kılavuzu10 dk. okuSeviye orta düzey

Bu sayfa henüz dilinizde mevcut değil. İngilizce olarak gösterilmektedir.

A trigger runs a function each time a table is written, in the same transaction as the write. It runs whatever the door (SDK, REST, aura db raw, a direct connection), so a rule enforced by a trigger cannot be bypassed by a client.

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 the tables sch_trg_notes and sch_trg_audit and functions named sch_trg_…, then remove them.

How a trigger runs#

ChoiceValuesEffect
Timingbefore, after, instead_of (views only; the CLI and the API take instead_of, SQL writes instead of)before can change or cancel the row; after sees the final row and cannot change it.
Eventsinsert, update, delete, truncateAny combination.
Granularityfor each row, for each statementOnce per row, or once per statement whatever the number of rows. truncate is statement only.

The function returns trigger and reads the row through NEW (insert, update) and OLD (update, delete), and the operation through TG_OP. A before row trigger returns NEW, possibly modified, to write it, or NULL to skip the row. The return value of an after trigger is ignored; return NULL. An error raised in the function cancels the whole write.

A trigger function needs no EXECUTE grant: PostgreSQL checks it when the trigger is created, not when it fires. The CLI warning "the function cannot be called by ANYONE" concerns direct calls only; the trigger fires for every caller (measured with a signed-in user).

Where to create a trigger#

DoorCommandCovers
CLIaura db trigger create <table> <name> --function <fn> --timing … --events … --for-each …, list <table>, drop <table> <name>Timing, events, granularity.
Trigger APIPOST /v1/db/{project_id}/{table}/triggers (name, timing, events, function_name, for_each), GET the same path, DELETE /v1/db/{project_id}/{table}/triggers/{name}Same as the CLI. service_role key.
SDKdb.createTrigger(table, …), db.listTriggers(table), db.dropTrigger(table, name)Same as the CLI, from a server.
SQLcreate trigger … with aura db rawEverything: when (…) conditions, update of <column>, arguments, transition tables.
StudioTriggers tab of the table editorLists, creates and drops the triggers of a table.

The function must exist first, in the project schema, with no arguments and returns trigger: create it with Database functions (--returns trigger).

Keep updated_at current#

Tables created by the CLI, the schema API and Studio have an updated_at column, set at insert and never updated afterwards. A before update trigger fixes that:

aura db table create sch_trg_notes "body:text"
aura db function create sch_trg_touch --returns trigger \
  --body 'begin new.updated_at := now(); return new; end'
aura db trigger create sch_trg_notes sch_trg_notes_touch \
  --function sch_trg_touch --timing before --events update
» Creating table 'sch_trg_notes'
  ✔ Table 'sch_trg_notes' created with 3 column(s).
  ℹ RLS enabled by default.
  • Columns: id, body, created_at
  ✔ Function 'sch_trg_touch' created (plpgsql → trigger).
  ⚠ No GRANT EXECUTE: the server revoked EXECUTE from PUBLIC and all known roles — the function cannot be called by ANYONE.
  • Add --grant-execute-to authenticated to expose it.
  ✔ Trigger 'sch_trg_notes_touch' created on 'sch_trg_notes' (BEFORE UPDATE FOR EACH ROW).
  • Executes function 'sch_trg_touch'.

Write a note with an old date, then update it. now() is the start time of the current transaction, so updated_at = now() is true only if the trigger set it in this request:

aura db raw "insert into sch_trg_notes (body, created_at, updated_at) values ('first draft', '2026-01-01', '2026-01-01')"
aura db raw "update sch_trg_notes set body = 'second draft' where body = 'first draft' returning body, updated_at = now() as touched"
  ℹ No results (0 rows).
  body         │ touched
  ─────────────┼────────
  second draft │ true

  ℹ 1 row(s).

The same function serves every table that has an updated_at column: create one trigger per table.

Write an audit log#

An after trigger can record each change in another table. The audit table must not be writable by your users, otherwise they could forge or erase entries. Keep it closed (row level security with no policy) and make the trigger function security definer, so that it, and only it, writes there:

aura db raw "create table sch_trg_audit (
  id bigint generated always as identity primary key,
  table_name text not null,
  op text not null,
  row_id uuid,
  changed_by uuid,
  old_row jsonb,
  new_row jsonb,
  at timestamptz not null default now())"

aura db function create sch_trg_audit_row --returns trigger --security definer --body "
begin
  insert into sch_trg_audit (table_name, op, row_id, changed_by, old_row, new_row)
  values (TG_TABLE_NAME, TG_OP, coalesce(new.id, old.id), auth.uid(),
          case when TG_OP <> 'INSERT' then to_jsonb(old) end,
          case when TG_OP <> 'DELETE' then to_jsonb(new) end);
  return null;
end"

aura db trigger create sch_trg_notes sch_trg_notes_audit \
  --function sch_trg_audit_row --timing after --events insert,update,delete
  ℹ No results (0 rows).
  ✔ Function 'sch_trg_audit_row' created (plpgsql → trigger).
  ⚠ No GRANT EXECUTE: the server revoked EXECUTE from PUBLIC and all known roles — the function cannot be called by ANYONE.
  • Add --grant-execute-to authenticated to expose it.
  ⚠ SECURITY DEFINER: function executes with its owner's privileges, not the caller's.
  ✔ Trigger 'sch_trg_notes_audit' created on 'sch_trg_notes' (AFTER INSERT OR UPDATE OR DELETE FOR EACH ROW).
  • Executes function 'sch_trg_audit_row'.

A signed-in user who may edit notes (the policy below lets every signed-in user do so, for the example) updates one; the audit row records who did it, before and after:

aura db raw "create policy sch_trg_notes_edit on sch_trg_notes for all to aura_authenticated using (true) with check (true)"
aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "update sch_trg_notes set body = 'final' where body = 'second draft'"
aura db raw "select op, changed_by, old_row->>'body' as before, new_row->>'body' as after from sch_trg_audit"
aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "select count(*) as visible from sch_trg_audit"
  ℹ No results (0 rows).
  ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1).
  ℹ No results (0 rows).
  after │ before       │ changed_by                           │ op
  ──────┼──────────────┼──────────────────────────────────────┼───────
  final │ second draft │ 00000000-0000-4000-8000-0000000000a1 │ UPDATE

  ℹ 1 row(s).
  ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1).
  visible
  ───────
  0

  ℹ 1 row(s).

auth.uid() returns the user of the request, or null for the service_role key and for SQL without --as. The user cannot read the audit table: it has no policy.

Fire only when a column changes#

The CLI and the API create triggers without conditions. A condition (when), a column list (update of body) or arguments need SQL. This version of the updated_at trigger only fires when body really changes:

drop trigger sch_trg_notes_touch on sch_trg_notes;
create trigger sch_trg_notes_touch
  before update of body on sch_trg_notes
  for each row
  when (old.body is distinct from new.body)
  execute function sch_trg_touch();
  ℹ No results (0 rows).

A when condition is checked before the function is called, which is cheaper than testing inside the function.

List and drop triggers#

aura db trigger list <table> --json returns one entry per trigger, with its events in an array (the same as GET /v1/db/{project_id}/{table}/triggers):

aura db trigger list sch_trg_notes --json
[
  {
    "events": [
      "DELETE",
      "INSERT",
      "UPDATE"
    ],
    "function_name": "EXECUTE FUNCTION sch_trg_audit_row()",
    "name": "sch_trg_notes_audit",
    "table_name": "sch_trg_notes",
    "timing": "AFTER"
  },
  {
    "events": [
      "UPDATE"
    ],
    "function_name": "EXECUTE FUNCTION sch_trg_touch()",
    "name": "sch_trg_notes_touch",
    "table_name": "sch_trg_notes",
    "timing": "BEFORE"
  }
]

The trigger API and the SDK do the same from a server. Here they make the audit table append-only: a function that refuses the write, attached before update or delete at statement level through HTTP, then listed and dropped with the SDK:

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_trg_refuse", "args": [], "returns": "trigger", "language": "plpgsql", "body": "begin raise exception '"'"'% is append-only'"'"', TG_TABLE_NAME; end"}'
echo
curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/sch_trg_audit/triggers" "${key[@]}" \
  -d '{"name": "sch_trg_audit_lock", "timing": "before", "events": ["update", "delete"], "function_name": "sch_trg_refuse", "for_each": "statement"}'
echo
curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/sch_trg_audit/triggers" "${key[@]}"
echo
aura db raw "delete from sch_trg_audit where true" || echo "exit code: $?"
{"data":null,"meta":null}
{"data":null,"meta":null}
{"data":[{"name":"sch_trg_audit_lock","table_name":"sch_trg_audit","timing":"BEFORE","events":["DELETE","UPDATE"],"function_name":"EXECUTE FUNCTION sch_trg_refuse()"}],"meta":null}
Error: [400] BAD_REQUEST: Invalid request: sch_trg_audit is append-only
exit code: 1

Even the service_role key is refused now: a trigger applies to every role. A statement-level trigger fires once per statement, with NEW and OLD set to NULL.

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

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

const listed = await admin.db.listTriggers('sch_trg_audit')
console.log(listed.data?.map((t) => `${t.name} ${t.timing}`))
console.log('dropped:', (await admin.db.dropTrigger('sch_trg_audit', 'sch_trg_audit_lock')).error)
const truncate = await admin.db.createTrigger('sch_trg_audit', { name: 'sch_trg_audit_no_truncate', timing: 'before', events: ['truncate'], function_name: 'sch_trg_refuse', for_each: 'statement' })
console.log('truncate lock:', truncate.error)
console.log('dropped:', (await admin.db.dropTrigger('sch_trg_audit', 'sch_trg_audit_no_truncate')).error)
[ 'sch_trg_audit_lock BEFORE' ]
dropped: null
truncate lock: null
dropped: null

Without --json, the CLI prints ? in place of the events of each trigger (sch_trg_notes_touch — BEFORE ?): use --json to read them. aura db trigger drop <table> <name> removes a trigger; dropping one that does not exist succeeds.

Result#

aura db raw "select body, updated_at = created_at as untouched from sch_trg_notes"
  body  │ untouched
  ──────┼──────────
  final │ false

  ℹ 1 row(s).

Common errors#

MessageCauseFix
function project_<id>.nope() does not exist--function names a function that is not in the project, or that takes arguments.Create it first with --returns trigger and no arguments.
trigger "…" for relation "…" already existsA trigger of that name is already on the table.Drop it, or pick another name.
cannot drop function …() because other objects depend on itaura db function drop on a function a trigger uses.Drop the trigger first.
TRUNCATE exige for_each = 'statement' (aucun trigger TRUNCATE au niveau ROW en Postgres)--events truncate with the default --for-each row (the message is in French).Add --for-each statement.
Duplicate event: 'UPDATE' appears several times in events (…)The same event twice in --events.List each event once.
new row violates row-level security policy for table "…" from a triggerA security invoker trigger function writes to a table the caller cannot write.Make that function security definer, as for the audit log, or add a policy.
record "new" has no field "updated_at"The function sets a column the table does not have.Attach it only to tables with that column.

Clean up#

Drop the triggers before their functions (one of them through DELETE /v1/db/{project_id}/{table}/triggers/{name}, which succeeds even if the trigger is already gone), then the tables:

aura db trigger drop sch_trg_notes sch_trg_notes_audit --force
aura db trigger drop sch_trg_notes sch_trg_notes_touch --force
curl -s -X DELETE "$AURABASE_URL/v1/db/$PROJECT_ID/sch_trg_audit/triggers/sch_trg_audit_lock" -H "apikey: $AURABASE_SERVICE_ROLE_KEY"; echo
aura db function drop sch_trg_audit_row --force
aura db function drop sch_trg_touch --force
aura db function drop sch_trg_refuse --force
aura db table drop sch_trg_notes --force
aura db table drop sch_trg_audit --force
  ✔ Trigger 'sch_trg_notes_audit' dropped from 'sch_trg_notes'.
  ✔ Trigger 'sch_trg_notes_touch' dropped from 'sch_trg_notes'.
{"data":null,"meta":null}
  ✔ Function 'sch_trg_audit_row' dropped (or already absent).
  ✔ Function 'sch_trg_touch' dropped (or already absent).
  ✔ Function 'sch_trg_refuse' dropped (or already absent).
  ✔ Table 'sch_trg_notes' dropped.
  ✔ Table 'sch_trg_audit' dropped.

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ Bir sorunu bildirin