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

Read rows

Read the rows your application needs, in the order it needs them, and understand why a read returns fewer rows than the table holds.

कैसे-करें गाइड9 मि॰ पढ़ेंस्तर शुरुआत

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

A read is a select: from('todos').select(…) in the SDK, GET /v1/db/todos over REST, select … from todos in SQL. The SDK builds the REST request, and the REST API runs one SQL query under the role of the key or user that calls it, so the same row level security policies apply to every door.

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.

Most examples read the demo rows with the service_role key, which bypasses row level security: run that key on a server only. Which rows each key reads shows the same reads with the anon key and a signed-in user.

Read rows#

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('todos').select('title, done').order('title')
console.log(data, error)
[
  { title: 'Add a row level security policy', done: false },
  { title: 'Create a table', done: false },
  { title: 'Invite a teammate', done: false },
  { title: 'Read the quickstart', done: true }
] null

data is always an array for a read, [] when nothing matches; the call never throws unless you add .throwOnError(). The same read over REST: the query string carries select, the filters and order. curl --get --data-urlencode encodes the values for you:

curl -s --get "$AURABASE_URL/v1/db/todos" \
  -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \
  --data-urlencode 'select=title,done' \
  --data-urlencode 'order=title'
echo
{"data":[{"title":"Add a row level security policy","done":false},
 {"title":"Create a table","done":false},
 {"title":"Invite a teammate","done":false},
 {"title":"Read the quickstart","done":true}],"meta":{}}

And in SQL, with aura db raw (or db.sql() from a server):

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).

A view reads like a table: from('open_todos').select('title').

Choose columns#

select() takes a comma-separated list. * (or no argument) returns every column. Rename a column with alias:column and convert it with column::type:

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

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

const { data } = await admin.from('posts').select('heading:title, published, id::text').order('title')
console.log(data)
[
  { heading: 'Draft notes', published: false, id: '2' },
  { heading: 'Hello Aurabase', published: true, id: '1' }
]

Rows of related tables go in the same list (select('slug, org_members(role)')): Join tables and nest rows. Keys inside a jsonb column use -> and ->>: Query JSON columns. Ask only for the columns you use: it keeps responses small and lets generated types infer the shape of data.

Filter rows#

Each filter method adds a condition; several filters must all be true. eq, in and ilike cover most reads:

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

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

const open = await admin.from('todos').select('title').eq('done', false).ilike('title', '%a%').order('title')
console.log(open.data)

const two = await admin.from('profiles').select('username').in('username', ['alice', 'carol']).order('username')
console.log(two.data)
[
  { title: 'Add a row level security policy' },
  { title: 'Create a table' },
  { title: 'Invite a teammate' }
]
[ { username: 'alice' } ]

Over REST, a filter is column=operator.value: ?done=eq.false&title=ilike.*a* (* stands for %, which would need escaping in a URL). Every operator, with or, not and null checks: Filter operators.

Sort and limit#

Without order(), rows come back in no guaranteed order. Call order() once per column, in the order of priority:

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

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

const { data } = await admin
  .from('todos')
  .select('title, done')
  .order('done', { ascending: false })
  .order('title')
  .limit(2)
console.log(data)
[
  { title: 'Read the quickstart', done: true },
  { title: 'Add a row level security policy', done: false }
]

order(column, { ascending: false }) (or order(column, 'desc')) sorts in descending order; nullsFirst: true or false places null values. In REST, ?order=done.desc,title.asc&limit=2. limit(n) caps the number of rows; a read never returns more than 1,000 rows, whatever the limit: page through larger results as shown in Paginate and count rows.

Read exactly one row#

single() returns the row as an object instead of an array, and fails when zero or several rows match. maybeSingle() accepts zero rows and returns null:

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

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

const one = await admin.from('profiles').select('username, display_name').eq('username', 'alice').single()
console.log('single:', one.data, one.error)

const none = await admin.from('profiles').select('username').eq('username', 'nobody').single()
console.log('single, no row:', none.error?.status, none.error?.code, none.error?.message)

const many = await admin.from('profiles').select('username').single()
console.log('single, two rows:', many.error?.status, many.error?.code, many.error?.message)

const maybe = await admin.from('profiles').select('username').eq('username', 'nobody').maybeSingle()
console.log('maybeSingle, no row:', maybe.data, maybe.error)
single: { username: 'alice', display_name: 'Alice Martin' } null
single, no row: 406 PGRST116 JSON object requested, 0 rows returned
single, two rows: 406 PGRST116 JSON object requested, multiple rows returned
maybeSingle, no row: null null

Use single() when the row must exist (a lookup by key), maybeSingle() when it may not (find a profile by username). Over REST, single() is the header Accept: application/vnd.pgrst.object+json.

Read one row by id#

GET /v1/db/{table}/{id} reads the row whose id column equals the value, and returns it as an object:

id=$(aura db raw --json "select id from posts where title = 'Hello Aurabase'" | node -e 'console.log(JSON.parse(require("fs").readFileSync(0, "utf8"))[0].id)')
curl -s -X GET "$AURABASE_URL/v1/db/posts/$id?select=title,published" -H "apikey: $AURABASE_SERVICE_ROLE_KEY"
echo
curl -s -X GET "$AURABASE_URL/v1/db/posts/999999" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \
  | node -e 'const e = JSON.parse(require("fs").readFileSync(0, "utf8")).error; console.log(e.code, e.message)'
{"data":{"title":"Hello Aurabase","published":true},"meta":{}}
RECORD_NOT_FOUND Cannot coerce the result to a single JSON object

The route only works on a table whose key column is named id. In the SDK, write .eq('id', id).single().

Which rows each key reads#

Row level security filters every read before your filters apply. The same query returns all rows with the service_role key, none with the anon key alone, and only the user's rows once a user is signed in:

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

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

const anon = await aura.from('todos').select('title')
console.log('anon:', anon.data, anon.meta?.hint?.split('. ')[0])

const email = `select-${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
await aura.from('todos').insert({ user_id: session!.user.id, title: 'Read my rows' })

const mine = await aura.from('todos').select('title')
console.log('signed in:', mine.data)
anon: [] 0 rows returned
signed in: [ { title: 'Read my rows' } ]

An empty result is not an error: when a read without filters returns no row to the anon key or a user, meta.hint says that the table may be empty or that no policy lets the role read it, and how to check with aura db raw --as anon. Policies are written in Row-level security. The sign-up works because email confirmation is turned off on the test project; a project requires it by default.

Result#

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
  false │ Read my rows
  true  │ Read the quickstart

  ℹ 5 row(s).

Common errors#

MessageCauseFix
400 COLUMN_NOT_FOUND column todos.titel does not existA column name that does not exist; the hint often suggests the right one.Fix the name.
404 TABLE_NOT_FOUND …The table does not exist, or the API has not reloaded its schema after a change.Check the name; retry after a second.
406 PGRST116 JSON object requested, 0 rows returnedsingle() and no row matches (or a policy hides it).Use maybeSingle(), or check the filter.
406 PGRST116 JSON object requested, multiple rows returnedsingle() or maybeSingle() and several rows match.Filter on a unique column.
404 RECORD_NOT_FOUND Cannot coerce the result to a single JSON objectGET /v1/db/{table}/{id} on an id that does not exist or is hidden.Check the id and the policies.
data: [] and a meta.hintNo policy lets this role read the table, or the table is empty.Sign the user in, or add a select policy.
400 POSTGREST_ERROR "failed to parse select parameter …"A syntax error in the column list.Check commas, parentheses and :: casts.

Clean up#

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

aura db raw "delete from todos where title = 'Read my rows'"
  ℹ No results (0 rows).

See also#