使用 JavaScript SDK 查询您的数据库
aura.db的日常流程、拒绝不安全调用的规则以及如何通过行级安全性保护表。
读取行#
const { data, error } = await aura
.from('todos')
.select('id, title, done')
.eq('done', false)
.order('created_at', { ascending: false })
.limit(20)
aura.from('todos') 是本文档中使用的形式(它是 aura.db.from('todos')的快捷方式,同一调用)。每次调用都会返回 { data, error } 并且从不抛出,请参阅 客户端选项和错误。
过滤器链: eq、 neq、 gt、 gte、 lt、 lte、 like、 ilike、 in、 is以及 数据库参考中列出的其他链。对于一页行,请使用 range(from, to)。
插入、更新和删除#
// 插入一行或一组行,然后将它们取回
const { data } = await aura.from('todos').insert({ title: 'Write the docs' }).select()
// 更新插入
await aura.from('todos').upsert({ id, title: 'Renamed' }).select()
// 更新和删除需要过滤器
await aura.from('todos').update({ done: true }).eq('id', id)
await aura.from('todos').delete().eq('id', id)
除非链接 .select(),否则写入不会返回任何内容(data 是 null):插入 10,000 行不会发回 10,000 行。使用 .select() 行会返回,而没有匹配任何行的 PATCH 或 POST 会说明 meta.hint中的原因。
有两条规则可以保护您免受错误的影响:
- 批量插入需要每行具有相同的键。 具有不同键的行返回
400和All object keys must match。用null填充缺失的键。 - 在发送任何请求之前,客户端会拒绝不带过滤器的
update()和delete(),并返回错误代码UNFILTERED_MUTATION。要有意更改每一行,请从服务器运行 SQL。
一行、多行、计数#
// 恰好一行:如果没有或有几行,则会出错
const one = await aura.from('todos').select('*').eq('id', id).single()
// → 当过滤器匹配零行或几行时,error.status 406
// 零行或一行:当没有匹配项时数据为空
const maybe = await aura.from('todos').select('*').eq('id', id).maybeSingle()
// 行及其总数
const page = await aura.from('todos').select('*', { count: 'exact' }).range(0, 9)
// page.count 是总数,无论范围如何
// 仅总计,无行
const { count } = await aura.from('todos').select('*', { count: 'exact', head: true })
count: 'exact' 计算每个匹配的行。 'planned' 和 'estimated' 在非常大的表和近似值上更快。
保护桌子#
通过 Aurabase (db.sql()、迁移、Studio 或表 API)创建的表会自动获取 ENABLE 和 FORCE ROW LEVEL SECURITY (除非您在 DDL 批处理中明确包含 DISABLE ROW LEVEL SECURITY )。由于还没有策略, anon 和 authenticated 调用者会看到 []。通过直接 Postgres 连接创建的表需要显式 enable row level security。添加您需要的策略:
create policy todos_own_read on todos
for select to aura_authenticated
using (auth.uid() = owner);
规范数据库角色是 aura_anon、 aura_authenticated 和 aura_service_role (组别名 anon、 authenticated、 service_role 也映射到托管集群上的它们)。 auth.uid() 是 NULL 的公钥和登录用户的用户 ID。请参阅 行级安全性。
service_role 密钥在设计上会绕过 RLS:将其保留在您的服务器上。
SQL函数和rpc#
从服务器创建一个函数,然后使用 rpc()从任何地方调用它:
await admin.db.createFunction({
name: 'add',
args: [
{ name: 'a', data_type: 'int', mode: 'IN' },
{ name: 'b', data_type: 'int', mode: 'IN' },
],
returns: 'int',
language: 'sql',
body: 'SELECT a + b',
grant_execute_to: ['anon', 'authenticated'],
})
const { data } = await aura.rpc('add', { a: 1, b: 2 }) // → 3
- 调用它需要
grant_execute_to。没有它,任何人都无法执行该函数。未列出的角色获取403 permission denied for function。authenticated和aura_authenticated均被接受。这也适用于您使用db.sql()创建的函数或在此更改后创建的项目的迁移(PUBLIC的默认EXECUTE权限被撤销):自行添加grant execute on function hello(text) to aura_authenticated;。 - 几秒钟后即可调用新函数。 在 API 重新加载其架构之前,
rpc()返回404 Could not find the function。 - 通过 SQL 的函数 (
db.sql()):CREATE FUNCTION/CREATE OR REPLACE FUNCTION在SECURITY INVOKER模式下允许(默认);SECURITY DEFINER在/raw上被拒绝,必须通过createFunction(POST /v1/db/{project_id}/functions) 或具有显式grant_execute_to的 CLI/迁移来创建。
从服务器运行 SQL#
import { createAdminClient } from '@aurabase/aurabase-js'
const admin = createAdminClient(process.env.NEXT_PUBLIC_AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
await admin.db.sql(`
create table if not exists todos (
id uuid primary key default gen_random_uuid(),
title text not null,
done boolean not null default false,
owner uuid,
created_at timestamptz not null default now()
)
`)
db.sql() 需要 service_role 密钥。它拒绝没有 WHERE的 DELETE ,并且不会读取系统目录,例如 pg_class 或 pg_roles。要列出您的表,请使用 admin.db.schema()。
分页、行上限和确切数字
- 读取最多返回 1,000 行 — 默认值和硬上限,无论您要求
limit()或range()。 当更多行匹配时,meta.has_more是true;要求count: 'exact'也能获得meta.total。 - 使用键集分页翻阅一个大表,在第一百万页上的成本相同:
aura.from('events').select('id,label').limit(1000).after('id', lastId)(它是.order('id').gt('id', lastId))。.cursor()仅限 MongoDB; 越深入,offset就越慢。 - 超出 JavaScript 2^53 的数字。 9,007,199,254,740,991 以上的
bigint在解析为 JS 数字时会丢失最后一位数字:使用{ parseBigIntAsString: true }创建客户端以将这些值作为字符串接收。当numeric可以精确表示时,它会作为 JSON 数字返回,否则会作为精确的十进制字符串返回(长值,例如12345678901234567890.123456789)。 count: 'planned'和'estimated'只是估计值。 它们来自 PostgreSQL的统计信息,在刚刚加载的表上为空(60 行表可以报告 430)。当数字很重要时使用count: 'exact'。vector列作为字符串 返回,例如"[0.1,0.2,0.3]":使用JSON.parse解析它以获取number[]。- 视图以您的权限读取。 您创建的视图(SQL、迁移)获得
security_invoker = true,因此基础表的策略适用于读取器。仅当您确实希望视图绕过 RLS时才显式写入with (security_invoker = false)。 db.sql()在Retry-After延迟 之后重试429(被拒绝的请求从未运行)。/raw每个项目都有限制;对于批量加载,请使用类型化的insert()和数组。