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

Views and materialized views

Save a query as a view that each caller reads through its own policies, precompute heavy aggregates in a materialized view, refresh it, and lock down what row level security cannot protect.

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

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

A view is a named query: reading it runs the query. A materialized view stores the result of the query and serves it until you refresh it. You create both in SQL, with aura db raw or the Studio SQL editor; there is no CLI or schema API command for views. The SDK and the REST API read them like tables, by name.

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 view sch_views_open and the materialized view sch_views_counts, then remove them. open_todos of the example schema is a view of the same kind.

View or materialized view#

ViewMaterialized view
DataRead from the tables at each queryStored when created or refreshed
FreshnessAlways currentAs of the last refresh
Row level securityApplies: Aurabase makes views run with the caller's rightsDoes not apply: the stored rows are the same for everyone
Who can read it by defaultAnon, signed-in users and service_role, each limited by the policies of the tablesAnon, signed-in users and service_role, every row: revoke it
IndexesThose of the tablesIts own (create index on <view> …)
Good forHiding columns, joining tables, a stable shape for the APIDashboards and costly aggregates read often and refreshed on a schedule

Create a view#

create view sch_views_open as
  select id, user_id, title, created_at
  from todos
  where not done;
  ℹ No results (0 rows).

The view appears in GET /v1/db/{project_id}/schema under views and in the ERD Schema page of Studio. create or replace view changes its query as long as the existing columns keep their names and types; otherwise drop it and create it again.

Views run with the caller's rights#

By default PostgreSQL runs a view with the rights of its owner, which would let anyone who can read the view see every row of todos. After each request that changes the schema, the aura db raw endpoint (and the migrations endpoint used by aura db push) sets security_invoker = true on every view of the project that has no such option. The view then runs with the rights of the caller, and the policies of todos decide what each caller sees:

aura db raw --as authenticated --user 00000000-0000-4000-8000-0000000000b2 "select title from sch_views_open"
aura db raw --as anon "select count(*) as visible from sch_views_open"
aura db raw "select count(*) as visible from sch_views_open"
  ℹ Executed as authenticated (00000000-0000-4000-8000-0000000000b2).
  title
  ─────────────────
  Invite a teammate

  ℹ 1 row(s).
  ℹ Executed as anon.
  visible
  ───────
  0

  ℹ 1 row(s).
  visible
  ───────
  3

  ℹ 1 row(s).

The signed-in user sees its own open todo, the anon key sees none, the service_role key sees the three open todos of the seed. The same holds through the SDK:

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

const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)
const { data, error } = await aura.from('sch_views_open').select('title')
console.log(data, error)
[] null

The option is only added when a view has none. A view created with (security_invoker = false) keeps that setting: it runs with the owner's rights and ignores the policies of its tables. Since every new relation of the project grants all table privileges to aura_anon and aura_authenticated, the anon key can then read every row through it, and, when the view is updatable (one table, no aggregate), also insert, update and delete rows of the table through the REST API: the policies of the table are not checked (measured on a view of a table with row level security and no policy). Never create such a view. If one exists, switch it with alter view <name> set (security_invoker = true), and revoke from the public roles what they must not do through it, for example revoke all on <name> from aura_anon, aura_authenticated (the anon key then gets 403 INSUFFICIENT_PRIVILEGE permission denied for view …). A view created through the direct PostgreSQL connection is not adjusted either: add with (security_invoker = true) yourself.

Create a materialized view#

A materialized view stores rows, and PostgreSQL has no row level security on it. Like any new relation of the project, it is readable by aura_anon and aura_authenticated until you revoke it, and they would read every row. Create it and revoke in the same request:

create materialized view sch_views_counts as
  select user_id, count(*)::int as todos, count(*) filter (where done)::int as done
  from todos
  group by user_id;

create unique index sch_views_counts_user on sch_views_counts (user_id);

revoke select on sch_views_counts from aura_anon, aura_authenticated;
  ℹ No results (0 rows).

The anon key is now refused, and the service_role key, on a server, reads it:

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

const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)
const anon = await aura.from('sch_views_counts').select('*')
console.log('anon:', anon.error?.status, anon.error?.code, anon.error?.message)

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const server = await admin.db.from('sch_views_counts').select('todos, done').order('todos')
console.log('service_role:', server.data, server.error)
anon: 403 INSUFFICIENT_PRIVILEGE permission denied for materialized view sch_views_counts
service_role: [ { todos: 1, done: 0 }, { todos: 3, done: 1 } ] null

To give each user its own figures from a materialized view, keep it revoked and expose a security definer function that filters on auth.uid(): Database functions. The function is the only door, and it decides what each caller gets.

Refresh a materialized view#

A new todo does not appear in the stored result until a refresh:

aura db raw "insert into todos (user_id, title) values ('00000000-0000-4000-8000-0000000000b2', 'Plan the sprint')"
aura db raw "select todos from sch_views_counts where user_id = '00000000-0000-4000-8000-0000000000b2'"
aura db raw "refresh materialized view concurrently sch_views_counts"
aura db raw "select todos from sch_views_counts where user_id = '00000000-0000-4000-8000-0000000000b2'"
  ℹ No results (0 rows).
  todos
  ─────
  1

  ℹ 1 row(s).
  ℹ No results (0 rows).
  todos
  ─────
  2

  ℹ 1 row(s).

concurrently lets readers keep reading during the refresh; PostgreSQL requires a unique index on plain columns of the view for it, hence sch_views_counts_user above. Without concurrently, the refresh is faster but blocks reads of the view until it ends.

Aurabase does not refresh materialized views for you, and pg_cron is not among the extensions of a project. Refresh from your code after the writes that matter, or from a scheduled job on your side that sends refresh materialized view concurrently … to aura db raw or POST /v1/db/{project_id}/raw. A refresh runs under the statement timeout of the endpoint (10 seconds by default): a view that takes longer to compute needs a smaller query, or the direct connection.

Write through a view#

A view over a single table, without aggregates, distinct or group by, accepts insert, update and delete, which PostgreSQL applies to the table. The policies of the table still apply, since the view runs with the caller's rights (a view with security_invoker = false skips them: see above). Add with check option to refuse writes that would produce a row the view does not show: through such a view of open todos, setting done = true fails with new row violates check option for view "…". A view with joins or aggregates is read-only: write to the tables, or through a function.

Result#

curl -s "$AURABASE_URL/v1/db/$PROJECT_ID/schema" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \
  | node -e 'console.log(JSON.parse(require("fs").readFileSync(0, "utf8")).data.views.map((v) => v.name).sort().join("\n"))'
open_todos
sch_views_counts
sch_views_open

Common errors#

MessageCauseFix
403 INSUFFICIENT_PRIVILEGE permission denied for materialized view …The materialized view was revoked from the caller's role.Read it with the service_role key, or through a function.
An empty array for a signed-in user or the anon keyThe view runs with the caller's rights and no policy of the table lets this role read the rows.Add a policy to the table (Row-level security), not to the view.
cannot refresh materialized view "…" concurrently with Hint: Create a unique index with no WHERE clause on one or more columns of the materialized view.concurrently without a unique index.Create one on columns that identify each row.
"…" is not a view with Hint: Use DROP MATERIALIZED VIEW to remove a materialized view.drop view on a materialized view.drop materialized view ….
cannot drop table … because other objects depend on it with Hint: Use DROP ... CASCADE to drop the dependent objects too.A plain drop table in SQL on a table used by a view.Drop the view first. The CLI and the schema API drop with cascade, which removes the view silently.
cannot change name of view column "…" to "…" with Hint: Use ALTER VIEW ... RENAME COLUMN ... to change name of view column instead.create or replace view with a renamed column.alter view … rename column, or drop and create the view.

Clean up#

Drop the two views and the todo added for the refresh:

drop materialized view sch_views_counts;
drop view sch_views_open;
delete from todos where title = 'Plan the sprint';
  ℹ No results (0 rows).

See also#