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

Read and export your schema

Find out what your project's schema contains without querying the system catalogs, follow its relationships, and export it as a replayable SQL file, knowing what the export leaves out.

Nasıl yapılır kılavuzu8 dk. okuSeviye acemi

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

aura db raw refuses the PostgreSQL catalogs (information_schema, pg_catalog, pg_tables…), since on a shared cluster they would describe other projects. Aurabase reads them for you, filtered to your project, through the CLI, the schema API, the SDK and Studio. This page lists what each one returns and how to export the schema as SQL.

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.

This page only reads; the export example writes a local file that the last step removes.

Where to read the schema#

You wantCLIAPI (service_role key)SDKStudio
Tables, columns, keys, indexes, constraintsaura db table list [--json]GET /v1/db/{project_id}/schema/tables, …/schema/tables/{table}db.schema()Table editor, ERD Schema
Views, functions, enums tooGET /v1/db/{project_id}/schemadb.schema()ERD Schema
Policiesaura db policy list [--json]GET /v1/db/{project_id}/policiesRLS policies tab
Functions with security and grantsaura db function list [--json]GET /v1/db/{project_id}/functionsdb.listFunctions()Functions tab
Triggers of a tableaura db trigger list <table> --jsonGET /v1/db/{project_id}/{table}/triggersdb.listTriggers()Triggers tab
Extensionsaura db extensions listGET /v1/db/{project_id}/schema/extensionsExtensions
Index usage, table sizes, locksaura db inspect indexes|tables|locks
The schema as SQLaura db pullGET /v1/db/{project_id}/schema/dumpERD Schema › Export schema

Every route needs the service_role key: the schema is administration data, refused to the anon key and to user tokens.

Tables, columns and relationships#

aura db table list --json returns each table with its columns (type, nullability, default, identity, foreign key), primary key, indexes, unique and check constraints, and its row level security and Realtime flags. The foreign keys are on the columns, under references. List the relationships of the example schema:

aura db table list --json | node -e 'for (const t of JSON.parse(require("fs").readFileSync(0, "utf8")))
  for (const c of t.columns) if (c.references)
    console.log(`${t.name}.${c.name} -> ${c.references.table}.${c.references.column}`, c.references.on_delete ?? "NO ACTION")'
org_members.org_id -> orgs.id CASCADE

todos.user_id and posts.user_id hold user ids but declare no foreign key: the users live in the Auth schema of the project, which your tables do not reference. The keys and identity columns of one table:

aura db table list --json | node -e 'const t = JSON.parse(require("fs").readFileSync(0, "utf8")).find((x) => x.name === "org_members")
console.log("primary key:", t.primary_key_columns.join(", "))
for (const c of t.columns) console.log(c.name, JSON.stringify(c.col_type), c.nullable ? "null" : "not null", c.default_val ?? "")'
primary key: org_id, user_id
org_id "bigint" not null
user_id "uuid" not null
role "text" not null 'member'::text
created_at "timestamptz" not null now()

A composite primary key leaves primary_key empty (null) and fills primary_key_columns; a single-column key fills both.

The whole schema in one call#

GET /v1/db/{project_id}/schema returns tables, views (views and materialized views), functions (those the REST API can call, with their arguments) and enums (each with its labels in order). It is what Studio and the type generators read:

curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/schema" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \
  | node -e 'const s = JSON.parse(require("fs").readFileSync(0, "utf8")).data
console.log("engine:", s.engine)
console.log("tables:", s.tables.map((t) => t.name).join(", "))
console.log("views:", s.views.map((v) => v.name).join(", "))
console.log("functions:", s.functions.map((f) => `${f.name}(${f.args.map((a) => a.name + " " + a.data_type).join(", ")}) -> ${f.returns}`).join(", "))
console.log("enums:", s.enums.length)'
engine: postgres
tables: org_members, orgs, posts, profiles, todos
views: open_todos
functions: todo_count(p_user uuid) -> bigint
enums: 0

Read it from the SDK#

db.schema() calls the same route. Use it from a server or a script, with the service_role key:

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

const admin = createClient(process.env.AURABASE_URL!, process.env.AURABASE_SERVICE_ROLE_KEY!)
const { data, error } = await admin.db.schema()
if (error) throw error
const todos = data.tables.find((t) => t.name === 'todos')!
console.log(todos.columns.map((c) => c.name))
console.log(data.views.map((v) => v.name), data.functions.map((f) => f.name))

const aura = createClient(process.env.AURABASE_URL!, process.env.AURABASE_ANON_KEY!)
const refused = await aura.db.schema()
console.log(refused.error?.status, refused.error?.code)
[ 'id', 'user_id', 'title', 'done', 'created_at' ]
[ 'open_todos' ] [ 'todo_count' ]
403 FORBIDDEN

Policies, functions, triggers, extensions#

aura db policy list
aura db trigger list todos --json
» 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).
[]

aura db function list adds each function's security mode and the roles that hold EXECUTE (Database functions); aura db extensions list gives the installed extensions and their versions (Extensions).

Export the schema as SQL#

aura db pull writes the schema of the linked project to aurabase/schema.sql. It prints ✔ Schema exported to aurabase/schema.sql (<size> bytes). It calls GET /v1/db/{project_id}/schema/dump, which returns plain SQL; the Export schema button of the ERD Schema page in Studio downloads the same file.

aura db pull > /dev/null
head -n 9 aurabase/schema.sql
-- Aurabase DDL dump — project: 11111111-2222-4333-8444-555555555555

-- Table: org_members
CREATE TABLE IF NOT EXISTS "org_members" (
  "org_id" bigint NOT NULL,
  "user_id" uuid NOT NULL,
  "role" text NOT NULL DEFAULT 'member'::text,
  "created_at" timestamp with time zone NOT NULL DEFAULT now()
);

The file is portable: names are not qualified by the project's internal schema, and the objects Aurabase adds itself (the Realtime trigger, the GraphQL wrapper) are left out. Statements use if not exists and drop policy if exists, so the file can be replayed on another project with aura db raw -f.

What the export contains#

IncludedNot included
Enum typesViews and materialized views
Tables, with types, defaults and identity columnsPartitioned tables and their partitions
Primary keys, unique, check and foreign key constraintsgrant and revoke (on tables, views and functions)
IndexesComments
Row level security (enable and force) and policiesData
Functions and triggersExtensions (installed in every project)

Check it on the example schema: the view open_todos and the grant on todo_count are missing from the file:

grep -c 'open_todos' aurabase/schema.sql || true
grep -ci '^grant' aurabase/schema.sql || true
grep -c 'CREATE POLICY' aurabase/schema.sql
0
0
2

The route itself returns the same text, for a script or a backup job:

curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/schema/dump" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" | grep -c '^CREATE TABLE'
5

Keep views, materialized views, partitioned tables and grants in your own migration files, next to the export.

Export data#

The schema export contains no rows. To export data:

  • a table or a query as JSON, from the SDK or aura db raw --json "select …" (each request is limited by the statement timeout of the endpoint);
  • the whole project, schema and data, with pg_dump on the direct connection: Connect to your database;
  • managed backups of the project, with aura db backup and the Backups page of Studio.

Result#

The schema of the example project, read four ways, gives the same five tables:

aura db table list --json | node -e 'console.log(JSON.parse(require("fs").readFileSync(0, "utf8")).map((t) => t.name).join(" "))'
org_members orgs posts profiles todos

Common errors#

MessageCauseFix
Referencing the system schema 'information_schema' is not allowed in raw queries — it could enumerate other tenantsA catalog query through aura db raw.Use the commands and routes of this page.
Referencing the system view 'pg_type' is not allowed in raw queriesA function or view whose name contains a catalog name, such as pg_typeof().Avoid the function in aura db raw.
[403] FORBIDDEN: Forbidden: DDL operation is reserved to the service_role roleA schema route called with the anon key or a user token.Use the service_role key.
[404] NOT_FOUND: Not found: Table '…' not foundGET /schema/tables/{table} on an unknown table.Check the name with aura db table list.
A table missing from aura db table listIt is a partitioned table: only its partitions are listed.Query it by name; see Partitions.

Clean up#

Remove the exported file:

rm -r aurabase

See also#

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