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

Example schema

The example schema is a small todo and blog model with row level security. Every Database page runs its snippets against it, so you can replay them on your own project.

Referans6 dk. okuSeviye referans

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

Install it#

aura db seed --example docs sends the schema to the linked project as one SQL request. On a linked project the request goes through the data plane, so the command needs the service_role key of the project in AURABASE_SERVICE_ROLE_KEY. Without it the command stops with Error: AURABASE_SERVICE_ROLE_KEY is not set.

export AURABASE_SERVICE_ROLE_KEY=aura_sk_…
aura db seed --example docs
» Seeding example schema 'docs'...
  • Installing on linked project 41fd6f07-3acf-48cf-9eb5-d665ce99a849...

✔ Example schema 'docs' installed.

The command is idempotent: it uses create table if not exists, create or replace and inserts only the rows that are missing, so you can run it again at any time. Only docs is accepted as a name; any other value fails with unknown example '<name>' (available: docs).

The file never uses a statement that aura db raw refuses (no CREATE EXTENSION, no SET, no explicit transaction), so it installs on any PostgreSQL project. Its source is aura-cli/src/examples/docs.sql in the Aurabase repository.

Tables#

aura db table list
» Project tables
  • org_members [RLS]
    org_id, user_id, role, created_at
  • orgs [RLS]
    id, slug, name, created_at
  • posts [RLS]
    id, user_id, title, body, published, created_at
  • profiles [RLS]
    id, username, display_name, created_at
  • todos [RLS]
    id, user_id, title, done, created_at

  ℹ 5 table(s).
TableColumnTypeDefault and constraints
profilesiduuidprimary key
usernametextnot null, unique
display_nametextnullable
created_attimestamptznot null, default now()
orgsidbigintgenerated always as identity, primary key
slugtextnot null, unique
nametextnot null
created_attimestamptznot null, default now()
org_membersorg_idbigintnot null, references orgs (id) on delete cascade
user_iduuidnot null
roletextnot null, default 'member'
created_attimestamptznot null, default now()
primary key (org_id, user_id)
postsidbigintgenerated always as identity, primary key
user_iduuidnot null, index posts_user_id_idx
titletextnot null
bodytextnullable
publishedbooleannot null, default false
created_attimestamptznot null, default now()
todosidbigintgenerated always as identity, primary key
user_iduuidnot null, index todos_user_id_idx
titletextnot null
donebooleannot null, default false
created_attimestamptznot null, default now()

user_id is a plain uuid column, without a foreign key to the users of the project: the demo rows belong to two made-up users.

View and function#

ObjectDefinitionWho can use it
View open_todosselect id, user_id, title, created_at from todos where not doneAnyone who can read todos. A view created through Aurabase runs with security_invoker, so the policies of todos apply to the reader.
Function todo_count(p_user uuid) returns bigintlanguage sql stable, select count(*) from todos where user_id = p_user, SECURITY INVOKERSigned-in users only: grant execute on function todo_count(uuid) to aura_authenticated. The anon key gets 403 INSUFFICIENT_PRIVILEGE.

Because the function is SECURITY INVOKER, it counts only the rows the caller is allowed to see. A signed-in user who has no todo yet gets 0, even for the id of a demo user.

select todo_count('00000000-0000-4000-8000-0000000000a1') as alice,
       todo_count('00000000-0000-4000-8000-0000000000b2') as bob
  alice │ bob
  ──────┼─────
  3     │ 1

  ℹ 1 row(s).

aura db raw runs with the service_role key, which bypasses row level security: that is why it sees the rows of both demo users.

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

const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)
const { data, error } = await aura.rpc('todo_count', { p_user: '00000000-0000-4000-8000-0000000000a1' })
console.log(data, error?.status, error?.code)
null 403 INSUFFICIENT_PRIVILEGE

Row level security and grants#

Every table of the schema has row level security enabled: todos and posts by the file itself, profiles, orgs and org_members because Aurabase enables it on every table created through aura db raw, a migration, the Studio or the table API.

TablePolicyRule
todostodos_owner, for allusing (auth.uid() = user_id) with check (auth.uid() = user_id)
postsposts_owner, for allusing (auth.uid() = user_id) with check (auth.uid() = user_id)
profiles, orgs, org_membersnoneRLS on and no policy: only the service_role key reads or writes them
aura db policy list
» RLS Policies
  Table                     Policy                    Cmd        USING Expression
  -------------------------------------------------------------------------------------
  posts                     posts_owner               ALL        (auth.uid() = user_id)
  todos                     todos_owner               ALL        (auth.uid() = user_id)

  ℹ 2 policy(ies).

What each key sees, with the schema just installed:

Callertodosprofilestodo_count(…)
Anon key, no userno rowno row403 INSUFFICIENT_PRIVILEGE
Signed-in userits own rows only (none until it inserts one)no rowthe number of its own rows
service_role keyevery rowevery rowevery row of the given user

Demo rows#

TableRows
profilesalice (00000000-0000-4000-8000-0000000000a1, Alice Martin), bob (00000000-0000-4000-8000-0000000000b2, Bob Durand)
orgsacme (Acme)
org_membersalice is owner of acme, bob is member
posts"Hello Aurabase" by alice (published), "Draft notes" by bob (not published)
todosalice: "Read the quickstart" (done), "Create a table", "Add a row level security policy"; bob: "Invite a teammate"

The two user ids are not accounts of your project: no one can sign in as alice or bob. Identity columns (id of orgs, posts, todos) get their values in an order that PostgreSQL does not guarantee, so the examples sort by title, never by id.

select title, done from todos order by title
  done  │ title
  ──────┼────────────────────────────────
  false │ Add a row level security policy
  false │ Create a table
  false │ Invite a teammate
  true  │ Read the quickstart

  ℹ 4 row(s).

Read it as a user#

aura db raw --as authenticated --user <uuid> runs a query as a signed-in user with that id, so you can watch the owner policy without creating an account. The same query as alice returns her three todos only.

aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000a1 "select title, done from todos order by title"
  ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000a1).
  done  │ title
  ──────┼────────────────────────────────
  false │ Add a row level security policy
  false │ Create a table
  true  │ Read the quickstart

  ℹ 3 row(s).

With --as anon, the same table returns no row, and profiles, which has no policy, returns no row to anyone but the service_role key.

aura db raw --as anon "select count(*) as visible from profiles"
  ℹ Executed as anon.
  visible
  ───────
  0

  ℹ 1 row(s).

With a real account, a signed-in user starts with no todo: the demo rows belong to other ids, so todo_count returns 0 for the user, and 0 even for alice. After the user inserts a todo of its own, the count is 1. The script signs a new user up: on a project that requires email confirmation (the default), turn it off first with aura auth settings set email_confirmation_required=false, as in the Quickstart.

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

const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)
const email = `schema-${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

const before = await aura.rpc('todo_count', { p_user: me })
console.log('before:', before.data, before.error)

const inserted = await aura.from('todos').insert({ user_id: me, title: 'My first todo' }).select('title, done')
console.log('insert:', inserted.data, inserted.error)

const after = await aura.rpc('todo_count', { p_user: me })
console.log('after:', after.data, after.error)

const alice = await aura.rpc('todo_count', { p_user: '00000000-0000-4000-8000-0000000000a1' })
console.log('alice, seen by this user:', alice.data)

const open = await aura.from('open_todos').select('title')
console.log('open_todos:', open.data, open.error)
before: 0 null
insert: [ { title: 'My first todo', done: false } ] null
after: 1 null
alice, seen by this user: 0
open_todos: [ { title: 'My first todo' } ] null

Clean up#

Delete the todo inserted above (the test user stays in the project; delete it with aura auth users delete <user-id>):

aura db raw "delete from todos where title = 'My first todo'"
  ℹ No results (0 rows).

Remove it#

The schema only adds objects to your project schema. To remove them, drop the view and the function, then the tables:

aura db raw "drop view if exists open_todos; drop function if exists todo_count(uuid); drop table if exists org_members, orgs, posts, todos, profiles cascade"
  ℹ No results (0 rows).

Run aura db seed --example docs again to bring it back.

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