コンテンツへスキップ
オーラベースのロゴ
オーラベース

Create and change tables

Create a table from the terminal, a script or Studio, add and change its columns, drop it safely, and know which defaults, rights and row level security a new table receives.

ハウツーガイド10 分 読み取りレベル 初心者

このページはまだお使いの言語では利用できません。英語で表示されます。

A table of your project lives in the PostgreSQL schema of the project. You create and change it with aura db table, with the schema API (/v1/db/{project_id}/schema/tables), with SQL sent to aura db raw, or from the Studio table editor. All four need the service_role key, and all four give the new table the same protections: a primary key, row level security switched on, and rights for the three platform roles.

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 of this page create their own tables, named sch_tables_…, and remove them at the end. They never change a table of the example schema.

Four ways to change the schema#

Taskaura db tableSchema APISQL (aura db raw)Studio
Create a tablecreate <name> "col:type,…"POST /schema/tablescreate table …New table
List tables and columnslistGET /schema/tables, GET /schema/tables/{table}Refused on the catalogs: use the CLI or the APITable list, Columns tab
Add, rename, retype, drop a columnNo commandPOST, PATCH, DELETE /schema/tables/{table}/columns/{column}alter table …Columns tab
NOT NULL, UNIQUE, DEFAULT, foreign keyNo (every CLI column is nullable)Column fieldsAny constraintColumns tab
Drop a tabledrop <name>DELETE /schema/tables/{table}drop table …Settings tab
Turn row level security or Realtime on or offrls, realtimePATCH …/rls, PUT …/realtimealter table … row level securityTable header

The schema API paths start with /v1/db/{project_id}. The CLI covers the common case; a column constraint, a rename or a type change needs the API, SQL or Studio. Row level security and Realtime have their own pages: Row-level security.

Create a table with the CLI#

aura db table create takes the table name and a comma-separated list of name:type pairs:

aura db table create sch_tables_books "title:text,pages:int,tags:text[],published_on:date"
» Creating table 'sch_tables_books'
  ✔ Table 'sch_tables_books' created with 6 column(s).
  ℹ RLS enabled by default.
  • Columns: id, title, pages, tags, published_on, created_at

The types the CLI accepts are text, int, bigint, float, numeric, bool, uuid, timestamp, timestamptz, tsvector, date, time, json, jsonb and bytea, plus three forms with an argument: array(<type>) or <type>[], vector(<dimension>) and enum(<type_name>) for an enum created beforehand. A few PostgreSQL spellings are translated: integer becomes int, boolean becomes bool, varchar becomes text, decimal becomes numeric. A column written without a type is text. A parameter in parentheses (numeric(10,2), varchar(80)) is refused: use SQL for it. Choose column types compares the types.

The summary lists created_at but not updated_at, which the server adds too (see the next section). List the tables to see every column:

aura db table list
» Project tables
  • org_members [RLS]
    org_id, user_id, role, created_at
  • orgs [RLS]
    id, slug, name, created_at
  • posts [RLS]
    id, user_id, title, body, published, created_at
  • profiles [RLS]
    id, username, display_name, created_at
  • sch_tables_books [RLS]
    id, title, pages, tags, published_on, created_at, updated_at
  • todos [RLS]
    id, user_id, title, done, created_at

  ℹ 6 table(s).

aura db table list --json prints the same tables with each column's type, default, nullability and foreign key, and each table's indexes, unique and check constraints.

What every new table receives#

A table created by the CLI, the schema API or Studio gets, in the same transaction:

AddedExactlyWhen
Primary keyid uuid primary key default gen_random_uuid()No primary key is declared and no column is named id. A declared id column becomes the primary key.
Creation datecreated_at timestamptz not null default now()No column named created_at.
Update dateupdated_at timestamptz not null default now()No column named updated_at. Nothing updates it afterwards: add the trigger of Triggers if you need it.
Row level securityenable and force row level securityAlways. The rls_enabled field of the API body is ignored at creation.
Rightsselect, insert, update, delete and truncate (every table privilege) to aura_service_role, aura_authenticated and aura_anon. The project schema grants them by default on every relation created in it (table, partition, view, materialized view), whatever the door, and the example tables have them too.Always. These rights do not restrict rows: row level security, forced on new tables, decides which rows each role reads and writes. Keep it on every table and every partition, and revoke what the anon key must never reach (see Views and materialized views).

With row level security on and no policy, the anon key and signed-in users see no row and cannot write: add the policies the table needs (Row-level security). The service_role key bypasses them.

A table created in SQL through aura db raw gets row level security too: after a statement that changes the schema, the endpoint enables and forces it on every table that did not exist before, unless the same request contains alter table <name> disable row level security. It does not add id, created_at or updated_at: SQL creates exactly the columns you write.

Add, change and drop columns#

The CLI has no column command. The schema API has three routes, all with the service_role key:

RouteBodyStatement it runs
POST /v1/db/{project_id}/schema/tables/{table}/columnsA column: name, col_type, nullable, unique (all four required), optional default_val and references ({"table", "column", "on_delete"})alter table … add column …
PATCH /v1/db/{project_id}/schema/tables/{table}/columns/{column}Any of new_name, col_type, nullable, default_val, drop_defaultrename column, alter column … type … using col::type, set/drop not null, set/drop default, in one transaction
DELETE /v1/db/{project_id}/schema/tables/{table}/columns/{column}Nonealter table … drop column …

col_type takes the type names of the CLI as JSON: "text", "bigint", {"array": "text"}, {"vector": 1536}, {"enum": "mood"}. on_delete takes CASCADE, SET NULL, SET DEFAULT, RESTRICT or NO ACTION.

Add a unique isbn column, turn pages into a bigint with a default, then drop tags:

key=(-H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json')

curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sch_tables_books/columns" "${key[@]}" \
  -d '{"name": "isbn", "col_type": "text", "nullable": true, "unique": true}'
echo
curl -s -X PATCH "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sch_tables_books/columns/pages" "${key[@]}" \
  -d '{"col_type": "bigint", "default_val": "0"}'
echo
curl -s -X DELETE "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sch_tables_books/columns/tags" "${key[@]}"
echo
{"data":null,"meta":null}
{"data":null,"meta":null}
{"data":null,"meta":null}

Read the table back with GET /v1/db/{project_id}/schema/tables/{table}. The JSON has the columns with their type, default and nullability; the filter below keeps the fields this example changed:

curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sch_tables_books" \
  -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \
  | node -e 'const t = JSON.parse(require("fs").readFileSync(0, "utf8")).data
for (const c of t.columns) console.log(c.name, JSON.stringify(c.col_type), c.nullable ? "null" : "not null", c.default_val ?? "")
console.log("unique:", JSON.stringify(t.unique_constraints))'
id "uuid" not null gen_random_uuid()
title "text" null
pages "bigint" null 0
published_on "date" null
created_at "timestamptz" not null now()
updated_at "timestamptz" not null now()
isbn "text" null
unique: [["isbn"]]

A type change rewrites the column with using "<column>"::<type>: it fails if a value cannot be cast (a text value abc cannot become a bigint), and the whole change is rolled back.

Do the same in SQL#

aura db raw accepts create table, alter table and drop table. SQL is the way to declare what the CLI cannot: not null, a check, a foreign key, an identity column, a precise numeric(10,2):

create table sch_tables_loans (
  id bigint generated always as identity primary key,
  book_id uuid not null references sch_tables_books (id) on delete cascade,
  borrower uuid not null,
  due_on date not null,
  fee numeric(10,2) not null default 0 check (fee >= 0)
);
alter table sch_tables_books add column summary text;
alter table sch_tables_books rename column summary to blurb;
  ℹ No results (0 rows).

The endpoint enabled and forced row level security on sch_tables_loans (it is new) and reloaded the REST API, so the table is reachable from the SDK on the next call. todos and the example tables use the same generated always as identity key as sch_tables_loans: their id is written by PostgreSQL, never by the client. Constraints and foreign keys covers keys, checks and cascades.

Create a table with the schema API#

POST /v1/db/{project_id}/schema/tables takes the table as JSON. It is what the CLI and Studio send. Besides name and columns, the body accepts primary_key (one column) or primary_key_columns (several), unique_constraints (lists of columns), check_constraints (expressions), indexes (name, columns, unique, optional method and where_clause) and realtime_enabled.

curl -s -X POST "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables" \
  -H "apikey: $AURABASE_SERVICE_ROLE_KEY" -H 'content-type: application/json' \
  -d '{
    "name": "sch_tables_shelves",
    "columns": [
      {"name": "label", "col_type": "text", "nullable": false, "unique": true},
      {"name": "capacity", "col_type": "int", "nullable": false, "unique": false, "default_val": "50"}
    ],
    "check_constraints": ["capacity > 0"]
  }'
{"data":{"name":"sch_tables_shelves"},"meta":null}

The answer gives the name the table really has. A name that starts with a digit gets a leading _ (2024_events becomes _2024_events). When the primary key is not a single column named id, the answer adds a warning: the table is created, but the REST routes by id (/v1/db/{project_id}/{table}/{id}) do not work for it; filter by the key column instead (?sku=eq.…).

GET /v1/db/{project_id}/schema/tables lists the tables in the same JSON form, GET /v1/db/{project_id}/schema/tables/{table} returns one table or 404 NOT_FOUND, and DELETE /v1/db/{project_id}/schema/tables/{table} drops it (see Drop a table).

Use the Studio table editor#

In Studio, Database opens the table editor. The left panel lists the tables of the project; New table opens a form with the table name, the columns (name, type, nullable, default) and the primary key, and sends it to the same POST /schema/tables route. A selected table has these tabs:

TabWhat it does
DataBrowse, insert, edit and delete rows.
ColumnsAdd, rename, retype and drop columns, through the column routes above.
RLS policies, RLS simulatorPolicies of the table; see Row-level security.
IndexIndexes; see Indexes.
Triggers, FunctionsSee Triggers and Database functions.
APIReady-to-copy SDK and REST snippets for this table, and whether row level security is on.
SettingsRow level security, Realtime and deletion of the table.

Each tab has its own address in Studio:

/<project-id>/database/sql                         (opens the table editor)
/<project-id>/database/sql/table-editor            Data
/<project-id>/database/sql/table-editor/columns    Columns
/<project-id>/database/sql/table-editor/indexes    Index
/<project-id>/database/sql/table-editor/triggers   Triggers
/<project-id>/database/sql/table-editor/functions  Functions
/<project-id>/database/sql/table-editor/api        API
/<project-id>/database/sql/table-editor/settings   Settings

The footer of the left panel links to the SQL Editor, the ERD Schema diagram (Read and export your schema), Extensions and Backups.

Drop a table#

aura db table drop asks for confirmation; --force skips it. The CLI, the API and Studio all run drop table if exists "<name>" cascade:

aura db raw "create view sch_tables_late as select id from sch_tables_loans where due_on < current_date"
aura db table drop sch_tables_loans --force
aura db raw "select count(*) from sch_tables_late" || echo "exit code: $?"
  ℹ No results (0 rows).
  ✔ Table 'sch_tables_loans' dropped.
Error: [400] BAD_REQUEST: Invalid request: relation "sch_tables_late" does not exist (line 1, column 22)
exit code: 1

cascade removes what depends on the table without asking: the view sch_tables_late is gone with it, and so is a foreign key that another table had towards it (the other table and its rows stay). Look for dependent views and foreign keys before you drop a table that others use. Dropping a table that does not exist succeeds and changes nothing.

Result#

The project has two new tables, both protected by row level security:

curl -s -X GET "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables" -H "apikey: $AURABASE_SERVICE_ROLE_KEY" \
  | node -e 'for (const t of JSON.parse(require("fs").readFileSync(0, "utf8")).data)
  if (t.name.startsWith("sch_tables_")) console.log(t.name, "rls:", t.rls_enabled, "columns:", t.columns.map((c) => c.name).join(","))'
sch_tables_books rls: true columns: id,title,pages,published_on,created_at,updated_at,isbn,blurb
sch_tables_shelves rls: true columns: id,label,capacity,created_at,updated_at

Common errors#

MessageCauseFix
[400] BAD_REQUEST: Invalid request: Invalid Nom de table: 'my-table' — only ASCII alphanumeric characters and '_' are allowed, and the identifier must be provided exactly as it will be created (no silent sanitizing)A table or column name with -, a space or an accent.Use letters, digits and _ only.
Unrecognized type 'numeric(10,2)': only array(<type>), vector(<dimension>), and enum(<type_name>) accept an argument in parentheses (…)A type parameter in aura db table create.Create the column in SQL.
Invalid JSON body — missing field `nullable` at line 1 column 33A column of the API body without nullable or unique.Send all four of name, col_type, nullable, unique.
No column change providedA PATCH on a column with an empty body.Send at least one of new_name, col_type, nullable, default_val, drop_default.
[404] NOT_FOUND: Not found: Table 'nope' not foundGET /schema/tables/{table} on a table that does not exist.Check the name with aura db table list.
relation "nope" does not exist (SQL) or 404 TABLE_NOT_FOUND (SDK, REST)The table does not exist, or the name differs in case.Check the name. A quoted name created in SQL ("Books") keeps its capitals.
cannot insert a non-DEFAULT value into column "id" (400 POSTGREST_ERROR from the SDK)A value sent for a generated always as identity column, including in an upsert with id.Leave id out of inserts; update by filter. See Constraints and foreign keys.
[403] FORBIDDEN: Forbidden: DDL operation is reserved to the service_role roleThe schema API called with the anon key or a user token.Use the service_role key, on a server.

aura db table create on a name that already exists answers ✔ Table '<name>' created, but the server runs create table if not exists and leaves the existing table unchanged: the columns you passed are not added. Check with aura db table list before you rely on them.

Clean up#

Drop the tables created on this page, one with the schema API and one with the CLI. sch_tables_books goes last, after sch_tables_loans, which referenced it and is already gone:

curl -s -X DELETE "$AURABASE_URL/v1/db/$PROJECT_ID/schema/tables/sch_tables_shelves" -H "apikey: $AURABASE_SERVICE_ROLE_KEY"
echo
aura db table drop sch_tables_books --force
{"data":null,"meta":null}
  ✔ Table 'sch_tables_books' dropped.

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ 問題を報告する