Перейти к содержимому
Логотип Аурабаза
аурабаза

Join tables and nest rows

Fetch a row with its related rows nested inside it, in one request from the SDK or the REST API, and know when to write the join in SQL instead.

Практическое руководство10 мин читатьУровень средний

Эта страница пока недоступна на вашем языке. Оно показано на английском языке.

The SDK and the REST API do not take a join keyword: you name a related table inside select(), and its rows come back nested in each row. The relation comes from a foreign key, which the API reads from your schema. Anything a foreign key cannot express (a join on another condition, a group by) goes in a view or a function.

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 in the environment, for the SDK and curl examples.

In the example schema, org_members.org_id references orgs (id): an org has many members, and each member row points to one org. The examples read them with the service_role key, since orgs and org_members have no policy (only that key reads them). The many-to-many section creates qd_joins_students, qd_joins_courses and qd_joins_enrollments, then removes them.

How nesting works#

You writeRelationNested value
orgs.select('slug, org_members(role)')one-to-many: org_members points to orgsan array of rows ([] when there is none)
org_members.select('role, orgs(slug)')many-to-one: the row points to orgsone object, or null
students.select('name, courses(title)')many-to-many through a join table with two foreign keysan array

The name inside the parentheses is the related table (or an alias, see below). The API looks up foreign keys between the two tables; with none, the request fails with Could not find a relationship. After a schema change, the new relation is visible once the API has reloaded its schema, which Aurabase triggers after each change through aura db raw, migrations and the schema API.

One to many#

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

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

const { data, error } = await admin.from('orgs').select('slug, name, org_members(user_id, role)')
console.log(JSON.stringify(data, null, 2), error)
[
  {
    "slug": "acme",
    "name": "Acme",
    "org_members": [
      {
        "role": "owner",
        "user_id": "00000000-0000-4000-8000-0000000000a1"
      },
      {
        "role": "member",
        "user_id": "00000000-0000-4000-8000-0000000000b2"
      }
    ]
  }
] null

Over REST, the same select goes in the query string:

curl -s --get "$AURABASE_URL/v1/db/orgs" \
  -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \
  --data-urlencode 'select=slug,org_members(role)'
echo
{"data":[{"slug":"acme","org_members":[{"role": "owner"}, {"role": "member"}]}],"meta":{}}

Many to one#

From the side that holds the foreign key, the related row is an object:

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

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

const { data } = await admin.from('org_members').select('role, orgs(slug, name)').order('role')
console.log(data)
[
  { role: 'member', orgs: { name: 'Acme', slug: 'acme' } },
  { role: 'owner', orgs: { name: 'Acme', slug: 'acme' } }
]

When two foreign keys link the same two tables (a billing_address_id and a shipping_address_id, say), name the one to follow after !: orgs!org_members_org_id_fkey(slug) uses the constraint org_members_org_id_fkey. A foreign key declared without a name is named <table>_<column>_fkey by PostgreSQL; the name also appears in the errors it raises.

Many to many#

A join table with a foreign key to each side, both part of its primary key, links two tables. The API detects it and lets you nest one side directly in the other:

create table qd_joins_students (id bigint generated always as identity primary key, name text not null);
create table qd_joins_courses (id bigint generated always as identity primary key, title text not null);
create table qd_joins_enrollments (
  student_id bigint references qd_joins_students (id) on delete cascade,
  course_id bigint references qd_joins_courses (id) on delete cascade,
  primary key (student_id, course_id)
);
insert into qd_joins_students (name) values ('Ada'), ('Grace');
insert into qd_joins_courses (title) values ('Algebra'), ('Compilers');
insert into qd_joins_enrollments
  select s.id, c.id from qd_joins_students s, qd_joins_courses c
  where (s.name, c.title) in (('Ada', 'Algebra'), ('Ada', 'Compilers'), ('Grace', 'Compilers'));
  ℹ No results (0 rows).
import { createClient } from '@aurabase/aurabase-js'

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

const students = await admin.from('qd_joins_students').select('name, qd_joins_courses(title)').order('name')
console.log(JSON.stringify(students.data))

const courses = await admin.from('qd_joins_courses').select('title, qd_joins_students(name)').order('title')
console.log(JSON.stringify(courses.data), courses.error)
[{"name":"Ada","qd_joins_courses":[{"title":"Algebra"},{"title":"Compilers"}]},{"name":"Grace","qd_joins_courses":[{"title":"Compilers"}]}]
[{"title":"Algebra","qd_joins_students":[{"name":"Ada"}]},{"title":"Compilers","qd_joins_students":[{"name":"Ada"},{"name":"Grace"}]}] null

To read columns of the join table itself (an enrollment date, a role), nest through it: select('name, qd_joins_enrollments(course_id, qd_joins_courses(title))').

Filter on related rows#

A filter on a nested column is written table.column. It has two meanings:

  • without !inner, it filters the nested rows only: every parent row stays, with fewer (or no) nested rows;
  • with !inner on the nested table, it also drops the parent rows that have no matching nested row, like an SQL inner join.
import { createClient } from '@aurabase/aurabase-js'

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

const nestedOnly = await admin.from('orgs').select('slug, org_members(role)').eq('org_members.role', 'owner')
console.log('nested filter:', JSON.stringify(nestedOnly.data))

const noOwner = await admin.from('orgs').select('slug, org_members(role)').eq('org_members.role', 'guest')
console.log('nested filter, no match:', JSON.stringify(noOwner.data))

const inner = await admin.from('orgs').select('slug, org_members!inner(role)').eq('org_members.role', 'guest')
console.log('inner join, no match:', JSON.stringify(inner.data))
nested filter: [{"slug":"acme","org_members":[{"role":"owner"}]}]
nested filter, no match: [{"slug":"acme","org_members":[]}]
inner join, no match: []

Use !inner to answer "which orgs have an owner" or "which posts have a comment by this user". Over REST: ?select=slug,org_members!inner(role)&org_members.role=eq.owner.

Rename, flatten and count#

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

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

const alias = await admin.from('orgs').select('slug, members:org_members(role)')
console.log('alias:', JSON.stringify(alias.data))

const flat = await admin.from('org_members').select('role, ...orgs(org_slug:slug)').order('role')
console.log('spread:', JSON.stringify(flat.data))

const counted = await admin.from('orgs').select('slug, org_members(count)')
console.log('count:', JSON.stringify(counted.data))
alias: [{"slug":"acme","members":[{"role":"owner"},{"role":"member"}]}]
spread: [{"role":"member","org_slug":"acme"},{"role":"owner","org_slug":"acme"}]
count: [{"slug":"acme","org_members":[{"count":2}]}]
  • alias:table(…) renames the nested key.
  • ...table(…) (spread) copies the columns of a many-to-one row into the parent row instead of nesting an object.
  • table(count) returns the number of related rows. It is the only aggregate the API accepts: sum(), avg() and the others are turned off (Aggregate rows).

Sort and limit nested rows#

Over REST, prefix order and limit with the nested table: org_members.order=role.desc sorts the members of each org, org_members.limit=1 keeps one per org.

curl -s --get "$AURABASE_URL/v1/db/orgs" \
  -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \
  --data-urlencode 'select=slug,org_members(role)' \
  --data-urlencode 'org_members.order=role.desc' \
  --data-urlencode 'org_members.limit=1'
echo
{"data":[{"slug":"acme","org_members":[{"role": "owner"}]}],"meta":{}}

The SDK option order(column, { referencedTable }) is meant for this, but it currently builds a parameter the API rejects (400 POSTGREST_ERROR "failed to parse order (org_members.role.desc)"). Until it is fixed, sort nested rows in your code, or use the REST form above.

The same join in SQL#

A view or a function holds joins that foreign keys do not express, and returns a flat result you read like a table:

select o.slug, m.role, p.username
from orgs o
join org_members m on m.org_id = o.id
join profiles p on p.id = m.user_id
order by m.role desc
  role   │ slug │ username
  ───────┼──────┼─────────
  owner  │ acme │ alice
  member │ acme │ bob

  ℹ 2 row(s).

org_members.user_id has no foreign key to profiles in the example schema, so the API cannot nest profiles in org_members; the SQL join does not need one. Wrap such a query in a view (create view … as select …) and read it with from('<view>'), or in a function called with rpc().

Policies on related tables#

Each nested table is read under the caller's role, with its own policies: a user sees a parent row and, inside it, only the related rows the policies of the related table let it read. A nested table without a select policy for that role comes back as [] (or null for many-to-one), not as an error. With !inner, hidden related rows also hide the parent row.

Result#

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

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

const { data } = await admin
  .from('qd_joins_courses')
  .select('title, qd_joins_students!inner(name)')
  .eq('qd_joins_students.name', 'Grace')
console.log(JSON.stringify(data))
[{"title":"Compilers","qd_joins_students":[{"name":"Grace"}]}]

Common errors#

MessageCauseFix
400 POSTGREST_ERROR Could not find a relationship between 'todos' and 'profiles' in the schema cacheNo foreign key between the two tables (upstream_code PGRST200).Add a foreign key, or join in a view or function.
400 POSTGREST_ERROR "failed to parse order (…)"order(…, { referencedTable }) of the SDK.Use <table>.order= over REST, or sort in your code.
400 POSTGREST_ERROR Use of aggregate functions is not allowedAn aggregate other than table(count) in select.Use a view or a function.
Nested value [] or null while rows existThe caller's policies hide the related rows.Add a select policy on the related table.

Clean up#

aura db raw "drop table qd_joins_enrollments, qd_joins_courses, qd_joins_students"
  ℹ No results (0 rows).

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ Сообщить о проблеме