Amphi documentation
Amphi is a Rust relational and document database. This documentation is organized as a structured reference: each SQL command and built-in function has a dedicated page, grouped by purpose.
English is the default language. Portuguese is available through the language selector or at the pt-BR documentation path.
The documentation describes the current implementation. Pages may label a surface as initial, experimental, or planned when it is not yet a stable compatibility promise.
Getting started
Build
$ cargo build --release
$ ./target/release/amphi version
Create a data directory
$ amphi init /tmp/amphi-demo
initialized Amphi data directory /tmp/amphi-demo
The cluster identifier is unique to the data directory. Immutable layout options such as page size are selected during init. The server is still evolving; inspect the implementation status before using this workflow in production.
Next, read Inspecting the data directory.
Inspecting data with amphi inspect
amphi inspect reads Amphi files without starting the server. It provides control-file, WAL, page, and integrity inspection in one command.
$ amphi inspect control /tmp/amphi-demo
$ amphi inspect verify /tmp/amphi-demo
checked 0 files, 0 pages (0 new), skipped 3 other files: OK
Use inspect wal for WAL records, inspect file for page summaries, and inspect page for a decoded page with an optional hex dump. Use verify after copying or restoring a data directory.
Data directory
Created by amphi init. Immediately after initialization it contains amphi.conf, AMPHI_VERSION, global/amphi.control, base/, wal/, and tmp/.
WAL can be placed on another disk with wal_dir. Page size, segment size, and extent size are fixed at initialization; changing them requires a new data directory and a data load. Do not edit or delete files while the server is running. Use amphi inspect verify after copying or restoring data.
Configuration
The configuration file is generated by amphi init in the data directory. Each setting is written with a commented default so the file is self-describing.
Use SET for session-scoped changes:
SET work_mem = '64MB';
SHOW work_mem;
Keep secrets outside the configuration file when possible. Restart the server after changing startup-only settings. See the configuration reference for parameter semantics.
Continuous checkpoint
checkpoint_batch_pages, checkpoint_timeout, bgwriter_delay, max_recovery_wal, checkpoint_min_publish_advance,
checkpoint_dirty_target, and checkpoint_dirty_trigger control continuous checkpointing. The
generated defaults are starting recommendations, not performance guarantees: local NVMe, slow
disks, cloud volumes, and Kubernetes PVCs may require different values. Benchmark the settings on
the actual storage with the application’s workload and adjust them when latency, throughput, or
recovery measurements indicate a better configuration.
Commit durability
default_commit_durability sets the session default and accepts local (the default) or async.
local waits for WAL synchronization before acknowledging; async acknowledges after append and may
lose acknowledged commits if the process crashes. The session GUC commit_durability selects the
profile for ordinary DML. DDL, catalog operations, and 2PC always remain local.
wal_writer_delay sets the normal maximum interval between periodic WAL-writer flush attempts. It
limits the usual loss window for asynchronous commits but is not a strict guarantee. These values are
operational recommendations: the best result depends on the actual storage and workload.
Configuration reference
Configuration is read from amphi.conf and can be overridden with SET when the server is running.
| Parameter | Meaning |
|---|---|
| data_dir | Data directory |
| wal_dir | WAL location |
| page_size | Immutable page size selected by init |
| wal_segment_bytes | WAL segment size |
| segment_bytes | Relation segment size |
| extent_bytes | Allocation extent size |
| work_mem | Per-query working memory |
| max_recursive_iterations | Recursive CTE round limit |
| tls_mode | TLS policy: disabled, preferred, or required |
Bootstrap layout parameters cannot be changed after initialization. Unknown parameters are rejected instead of being silently ignored.
max_prepared_transactions
Maximum two-phase transactions kept prepared at once. Zero disables PREPARE TRANSACTION. This startup-only setting requires a restart.
TLS
TLS protects client connections to the Amphi wire endpoint. Set tls_mode to disabled, preferred, or required according to the deployment policy.
The init –tls-self-signed option creates a development certificate authority, server certificate, and private key. These certificates are suitable for local testing only. Production deployments should use a trusted certificate, protect the private key, and configure clients to verify the server name and certificate chain.
Security
Run the server with a dedicated operating-system user and restrict the data directory to that account. Do not expose the wire port directly to an untrusted network.
Use TLS for remote connections and rotate certificates before they expire. Keep authentication credentials and private keys out of source control and out of diagnostic output.
Access policies are evaluated by the SQL layer. Test both allowed and denied paths with a least privilege role before deploying a policy to production.
Integrity verification
Use inspect verify to scan control files, WAL, and data pages without starting the server:
$ amphi inspect verify /var/lib/amphi
checked 0 files, 0 pages (0 new), skipped 3 other files: OK
The command validates page checksums and reports the first failing path. Exit code 0 means the scan completed successfully; exit code 1 means inspected data has a problem. Run verification after copying, restoring, or moving a data directory.
SQL overview
The relational core, document extensions, queues, and in-memory tables share one SQL surface. Each group has its own dedicated reference pages.
See WITH RECURSIVE for recursive queries and Built-in functions for the function catalog. The command list should reflect executable behavior; planned features are marked explicitly.
| Feature | Catalog | SQL surface | Engine |
|---|---|---|---|
| Collection | catalog | CREATE/DROP COLLECTION, FIND | document codec |
| Queue | catalog | creation, delivery, ACK/NACK, DLQ | lease and retry |
| Memory table | catalog | creation and key commands | local process |
| Schedule | catalog | CREATE/ALTER/DROP SCHEDULE | SQL actions, worker pool and run history |
Queue delivery is at-least-once. Memory-table commands are atomic individually and are not transactional across commands.
Schedules are persisted definitions executed by the integrated scheduler. They use one
orchestrator and a bounded worker pool; creating a schedule does not create a dedicated thread.
ampdump exports the whole database as plain SQL by default. Use -t custom or -Fc for the
Amphi binary custom format, and append a relation name to limit the dump. Schedules and execution
history are still excluded.
System views
System views are the read-only SQL contract for Amphi metadata. They live in the sys schema, are created during catalog bootstrap, and can be queried by tools such as amphi-console.
The public contract is formed by sys.catalog_* views. Physical catalog relations remain implementation details and should not be queried directly by new applications.
SELECT schema, name, kind, engine
FROM sys.catalog_objects
ORDER BY schema, name;
sys.catalog_object_comments
Lists comments for entities with catalog OID identities. Relations and columns
are also available through sys.catalog_objects and sys.catalog_columns;
this view covers relations and other commentable families, including schemas,
types, domains, routines, roles, groups, tablespaces, policies, constraints,
triggers, and installed extensions.
| Column | Type | Description |
|---|---|---|
object_oid | int4 | Stable object identity |
object_kind | text | Object family |
schema_name | text | Schema, when applicable |
object_name | text | Object name |
owner_name | text | Owning relation for constraints/triggers |
comment | text | Stored comment |
SELECT object_kind, schema_name, object_name, comment
FROM sys.catalog_object_comments
ORDER BY object_kind, schema_name, object_name;
sys.catalog_object_tags
Lists tags for relations and catalog object families with OIDs (schemas, types,
domains, functions/aggregates, roles/groups, tablespaces, policies, constraints,
triggers, and named OID-backed objects), with one row per key. Filter by
key/value. Not all these families appear in
sys.catalog_objects, which continues to represent relations.
| Column | Type | Description |
|---|---|---|
object_oid | int4 | Stable object identity |
object_kind | text | Relation kind |
schema_name | text | Object schema |
object_name | text | Object name |
owner_name | text | Parent relation for constraints/triggers; NULL otherwise |
key | text | Tag key |
value | text | Tag value |
SELECT schema_name, object_name, object_kind
FROM sys.catalog_object_tags
WHERE key = 'env' AND value = 'prod'
ORDER BY schema_name, object_name;
ALTER TABLE ... ADD TAG key = 'value' creates or replaces a key;
ALTER TABLE ... DROP TAG key removes it. ALTER OBJECT manages non-relation
families; end-to-end validated coverage is listed in
Object tags.
Use the catalog views to inspect schemas, objects, columns, indexes, functions, and extensions. Changes must be made through the corresponding DDL commands.
sys.language
Lists procedural languages installed and active in the current process. A
language is registered by the extension that provides it; for example,
CREATE EXTENSION plamphi adds plamphi to this view.
| Column | Type | Description |
|---|---|---|
name | text | Language name used by LANGUAGE |
extension | text | Extension providing the handler |
status | text | Current handler state |
SELECT name, extension, status
FROM sys.language
ORDER BY name;
This is a virtual view of the current runtime. It is empty for a language that
is available but has not been installed with CREATE EXTENSION.
sys.catalog_functions.schema identifies the owning schema. arg_types remains encoded as
bytea; use the function history page for complete SQL definitions.
security_definer records the SECURITY DEFINER declaration; the owner is used as
current_user during execution.
sys.object_revision
Read-only history for versioned objects. For functions, source contains the complete DDL for
the revision and created_by identifies the role that made the change.
| Column | Type | Description |
|---|---|---|
object_oid | int4 | Stable object identity |
object_kind | text | Object type, currently function |
version | int8 | Revision number |
source | text | Complete DDL |
arg_names | bytea | Encoded argument names |
created_at | int8 | Timestamp in microseconds |
created_by | int4 | Author role OID |
ddl_seq | int8 | DDL sequence, when available |
sys.catalog_domains
Lists domains defined outside the sys schema. The checks column keeps the
catalog’s bytea representation so the public view can expose the complete
metadata without changing its one-row-per-domain shape; DDL and ampdump
decode that value when they need the named checks.
| Column | Type | Description |
|---|---|---|
oid | int4 | Domain identifier |
schema | text | Domain schema |
name | text | Domain name |
base_type | text | Base type |
default_expression | text | Domain default, when defined |
not_null | bool | Whether null values are rejected |
checks | bytea | Encoded named domain checks |
SELECT schema, name, base_type, default_expression, not_null
FROM sys.catalog_domains
ORDER BY schema, name;
sys.catalog_triggers
Exposes trigger descriptors stored in the catalog. This is the metadata contract of Epic 1; SQL creation and execution belong to later epics.
| Column | Type | Description |
|---|---|---|
oid | int4 | Trigger identifier |
rel | int4 | Relation owning the trigger |
name | text | Trigger name |
function | int4 | Function executed by the trigger |
timing | text | BEFORE, AFTER, or INSTEAD OF |
level | text | ROW or STATEMENT |
events | int2 | Mask of INSERT, UPDATE, DELETE, and TRUNCATE |
scope | text | LOGICAL or PHYSICAL |
arguments | bytea | Persisted trigger arguments |
enabled | bool | Whether the trigger is enabled |
scope = LOGICAL is reserved for a trigger that follows the logical operation
of a partitioned table; PHYSICAL follows a specific physical relation. This
is distinct from relation inheritance.
sys.catalog_partitions
Lists physical relations attached to a partitioned table.
| Column | Type | Description |
|---|---|---|
relation | int4 | Child relation |
parent | int4 | Parent partitioned table |
bound | text | Persisted canonical bound; typed semantics are still evolving |
sys.catalog_acls
Exposes persisted object privilege grants.
| Column | Type | Description |
|---|---|---|
relation | int4 | Protected relation OID |
grantee_kind | text | PUBLIC, ROLE, or GROUP |
grantee | int4 | Grantee OID; null for PUBLIC |
grantor | int4 | Granting role OID |
privilege | text | Granted privilege |
scope_kind | text | ALL, COLUMNS, or ALL_EXCEPT |
columns | bytea | Encoded attno list when applicable |
grant_option | bool | Whether the grantee can regrant it |
sys.catalog_default_acls
Exposes default privileges configured by a role for new tables, schemas, and
sequences. They are applied when the object is created. It has the same scope
and grantee columns as sys.catalog_acls; owner identifies the role that owns
the default rule and object identifies TABLES, SCHEMAS, or SEQUENCES.
sys.stat_activity
Shows active sessions and workers. SQL sessions use backend_type = 'client';
the internal worker uses backend_type = 'worker', worker_kind = 'partition',
and its alarm_id.
SELECT id, backend_type, worker_kind, alarm_id, state, query, relation
FROM sys.stat_activity
WHERE state = 'active';
Rows are ephemeral and disappear when the session or worker finishes.
sys.stat_progress
Shows current and recent progress for internal operations. It is an in-memory
view; durable outcome and errors remain in sys.system_alarm_status.
SELECT kind, state, phase, rows_done, rows_total, error
FROM sys.stat_progress;
Columns include operation_id, kind, state, phase, alarm_id, relation,
rows_done, rows_total, bytes_done, bytes_total, started_at, updated_at, and error.
sys.system_alarms
Shows occurrences of core-owned internal alarms. Users, extensions, and plugins cannot register new alarm kinds or handlers.
| Column | Type | Description |
|---|---|---|
| id | int8 | Occurrence identifier |
| kind | text | Internal kind, initially partition |
| owner | int4 | Associated core object, such as the parent relation |
| scheduled_at | int8 | Scheduled Unix time in microseconds |
| state | text | waiting, running, success, or failed |
| attempt | int4 | Current attempt |
| started_at | int8 | Execution start, when started |
| finished_at | int8 | Execution finish, when completed |
| error | text | Last attempt error |
| affected_objects | int4 | Objects created or changed |
| lease_owner | int8 | Worker holding the lease, when running |
| lease_until | int8 | Lease expiry as Unix microseconds |
sys.system_alarm_status exposes the same operational contract for health checks and monitoring;
users cannot create or alter system alarms. A minimal monitoring query is:
SELECT kind, state, attempt, scheduled_at, lease_owner, lease_until, error
FROM sys.system_alarm_status
WHERE state IN ('waiting', 'running', 'failed')
ORDER BY scheduled_at;
Alarm occurrences are durable and survive restart. A running row with an expired lease is
eligible for worker reclaim; failed retains the last error and may produce a new occurrence with
bounded backoff.
sys.partition_policies
Shows declarative partition policies persisted in the catalog. scope = database
represents the database policy; other values identify the schema where the policy
applies.
| Column | Type | Description |
|---|---|---|
| oid | int4 | Policy identifier |
| name | text | Policy name |
| scope | text | database or schema scope |
| relation_kind | text | table or collection |
| match_column | text | Column used for matching |
| match_type | text | Resolved column type |
| strategy | text | range, hash, or list |
| key | text | Partition key |
| every | text | Automatic interval |
| retention | text | Declared retention |
| sub_strategy | text | Subpartition strategy |
| sub_key | text | Subpartition key |
| subpartitions | int2 | Number of subpartitions |
| retention_action | text | detach or export_then_detach |
| retention_server | text | SERVER used by export, when applicable |
sys.prepared_transactions
Shows transactions retained by two-phase commit in the current cluster, including after recovery.
| Column | Type | Description |
|---|---|---|
| gid | text | Global identifier of the prepared transaction |
| xid | int8 | Transaction ID |
| prepared_at | int8 | Preparation time in microseconds since the Unix epoch |
| owner | text | User that executed PREPARE TRANSACTION |
2PC must be enabled with max_prepared_transactions greater than zero.
Logical backup neither exports nor recreates prepared transactions: ampdump refuses a dump while
the view has rows.
sys.function_cache_stats
Shows counters for the process-local cache of bound SQL-function bodies:
hits | misses | entries | capacity
hits and misses count reused and newly bound queries; entries shows the current number of
entries and capacity the LRU limit. Counters reset when the server process restarts.
Object tags
Tags are searchable key/value pairs in the catalog. The validated workflow covers named relations, schemas, and CHECK/foreign-key constraints. Tags are separate from comments, which remain free-form text.
ALTER TABLE public.users ADD TAG env = 'prod', team = 'finance';
ALTER TABLE public.users ADD TAG env = 'staging'; -- replaces the key's value
ALTER TABLE public.users DROP TAG team;
ADD TAG creates or replaces a key’s value. DROP TAG removes one or more
keys; a missing key leaves the catalog unchanged. For OID-backed objects that
are not relations, use ALTER OBJECT with an explicit type:
ALTER OBJECT DOMAIN public.status ADD TAG owner = 'registry';
ALTER OBJECT SCHEMA public ADD TAG team = 'platform';
ALTER OBJECT FUNCTION public.normalize ADD TAG stability = 'stable';
ALTER OBJECT PROCEDURE public.transfer_stock ADD TAG purpose = 'inventory movement';
ALTER OBJECT DATABASE analytics ADD TAG environment = 'prod';
ALTER OBJECT SECRET billing_api ADD TAG team = 'finance';
ALTER OBJECT SCHEDULE hourly_cleanup ADD TAG owner = 'platform';
ALTER OBJECT OPCLASS int4_ops ADD TAG category = 'index';
ALTER OBJECT OPERATOR "+" ADD TAG category = 'arithmetic';
ALTER OBJECT recognizes schema, type, domain, function, procedure, aggregate,
role, user, group, tablespace, partition_policy, access_policy,
constraint, trigger, extension, foreign_server, external_connection,
opclass, operator, database, secret, and schedule, as well as relation
types. End-to-end validation for families beyond schemas and CHECK/foreign-key
constraints remains pending. Constraints and triggers use ON <relation> to
disambiguate repeated names. Functions, operators, and operator classes must
have unique names. Casts do not support tags yet because they have no own OID.
Values are SQL strings.
Changes follow the current transaction; renaming a relation preserves its tags,
and dropping it removes its tags.
Query the public view:
SELECT schema_name, object_name, object_kind, key, value
FROM sys.catalog_object_tags
WHERE key = 'env' AND value = 'prod'
ORDER BY schema_name, object_name;
The Console shows tags in the Metadata tab on object details and on the Object Metadata page, which lists taggable objects without a dedicated tree detail. Actions prepare SQL in the editor. Comments remain in a dedicated Comments tab where object details support them. Database tags are cluster-wide; secret and schedule tags belong to the current database catalog. Dumps preserve secret tags, but the secret must be provisioned on the target first; secret values are never exported. Dumps include SQL schedule definitions and tags; native schedules cannot be exported. Extension, operator, and operator-class tag round-trips require the extension to be available on the target. Foreign tables are included without their remote rows when the server, connection, and options can be restored safely. If a tagged foreign server or external connection has opaque options, the dump fails instead of silently dropping its metadata.
Data definition language
DDL changes schemas and catalog objects. Every implemented command has a dedicated reference page, including CREATE and DROP for schemas, tables, views, indexes, users, groups, collections, queues, and memory tables.
See COMMENT ON for table and column metadata.
See CREATE PROCEDURE for persisted procedures and CALL.
DDL is validated by the parser, binder, and catalog before execution. Use explicit names and inspect sys.catalog_objects after migrations to confirm the resulting object kind and engine.
See Partitioning for the planned native partitioning model and the distinction between logical partition triggers and ordinary table inheritance.
CREATE TABLE
ALTER FOREIGN KEY CONSTRAINT
Changes the deferrability of an existing foreign key without recreating the constraint.
ALTER TABLE child
ALTER CONSTRAINT child_parent DEFERRABLE INITIALLY DEFERRED;
ALTER TABLE child
ALTER CONSTRAINT child_parent DEFERRABLE INITIALLY IMMEDIATE;
ALTER TABLE child
ALTER CONSTRAINT child_parent NOT DEFERRABLE;
The target must be an existing foreign key on the named table. DEFERRABLE
allows the foreign key to be controlled by SET CONSTRAINTS;
INITIALLY DEFERRED starts it deferred in each new transaction, while
INITIALLY IMMEDIATE checks it normally.
If INITIALLY ... is omitted, the current value is preserved. With
NOT DEFERRABLE, initially_deferred is normalized to false.
The change is transactional DDL: inside BEGIN it can be undone by
ROLLBACK; outside an explicit transaction, it commits at the end of the
statement. Foreign keys with a RESTRICT referential action cannot be made
deferrable in this version.
The Web Console shows persisted values in the constraints table as read-only checkboxes. The change is executed through the SQL editor.
COMMENT ON
Defines, replaces, appends to, or removes the description of relations and columns.
COMMENT ON TABLE users IS 'User registry';
COMMENT ON DATABASE app IS 'Application database';
COMMENT ON COLUMN users.email IS 'Email address';
COMMENT ON COLUMN users.email IS APPEND ' used for authentication';
COMMENT ON COLUMN users.email IS NULL;
COMMENT ON VIEW active_users IS 'Active users';
COMMENT ON MATERIALIZED VIEW user_totals IS 'Totals by user';
COMMENT ON INDEX users_email_idx IS 'Lookup by email';
COMMENT ON SEQUENCE users_id_seq IS 'User identifiers';
COMMENT ON COLLECTION events IS 'Incoming events';
COMMENT ON QUEUE pending_jobs IS 'Pending jobs';
COMMENT ON MEMORY TABLE request_cache IS 'Session cache';
COMMENT ON SCHEMA app IS 'Application objects';
COMMENT ON DOMAIN app.email IS 'Validated address';
COMMENT ON TYPE app.status IS 'Processing state';
COMMENT ON FUNCTION app.normalize_email(text) IS 'Normalizes addresses';
COMMENT ON ROLE analyst IS 'Analytics team';
COMMENT ON EXTENSION amphi_openai IS 'AI provider';
COMMENT ON FOREIGN TABLE app.remote_users IS 'Remote registry';
COMMENT ON SERVER csv_server IS 'CSV source';
COMMENT ON EXTERNAL_CONNECTION csv_connection IS 'Source credentials';
COMMENT ON CONSTRAINT users_email_key ON app.users IS 'Unique email';
COMMENT ON TRIGGER users_audit ON app.users IS 'Records changes';
For several columns of one table, Amphi provides an extension:
COMMENT ON TABLE users
COLUMN name IS 'Full name'
COLUMN email IS APPEND ' used for authentication'
COLUMN bio IS NULL;
IS replaces the text, IS APPEND concatenates text to the existing comment, and IS NULL
removes it. Column comments are supported on tables, views, materialized views, collections,
queues, and memory tables. The COMMENT ON COLUMN table.column form remains available for
PostgreSQL compatibility. Comments are metadata, not lexical -- or /* ... */ comments.
Relation comments are also accepted on heap tables and their partitions, memory tables, collections, queues, views, and materialized views; indexes, sequences, and foreign tables accept an object comment. Foreign tables also accept column comments. Memory tables are volatile: their comments disappear when the table is discarded on restart and are not included in dumps.
Other supported targets are SCHEMA, DOMAIN, TYPE, FUNCTION, AGGREGATE,
ROLE, GROUP, TABLESPACE, PARTITION_POLICY, ACCESS_POLICY,
CONSTRAINT, TRIGGER, EXTENSION, FOREIGN TABLE, SERVER,
EXTERNAL_CONNECTION, SECRET, OPCLASS, OPERATOR, and CAST. Operators
must include both operand types (use NONE for a missing side of a unary
operator); casts use (source AS target). Overloaded routines must include their argument
type list; constraints and triggers use ... ON table. Their comments are
exposed through sys.catalog_object_comments and included in logical dumps
when that object type is already exported.
For casts, object_name in that view is the target type and owner_name is the
source type.
Foreign data wrappers do not support comments yet. SCHEDULE comments appear
in sys.catalog_object_comments, but schedules and their comments are not
included in the current logical dump.
COMMENT ON SECRET is admin-only and autocommit-only. Its metadata is separate
from the encrypted value and appears in sys.catalog_object_comments. Secrets
and their comments are not exported by dumps.
Built-in operator, opclass, and cast comments are restored after their
catalog identities are available.
Databases, foreign servers, and external connections support comments.
Database comments are cluster-wide metadata and can be changed by the database
owner or an admin, outside transactions. Single-database and --cluster dumps
preserve them. Dumps restore
only definitions without options. Connections with options, including SECRET
references, are omitted because dumps do not contain the secret objects needed
for restore. Comments for omitted definitions are omitted too.
Internal objects (such as TOAST relations) are not
public targets. The Console Comments tab is available on database, foreign
server, relation, domain, and function detail panels; other SQL-supported types
are managed through the SQL editor.
LOCK TABLE
Acquires an explicit lock on one or more tables. The command is only valid inside an explicit
transaction and the lock is held until COMMIT or ROLLBACK.
BEGIN;
LOCK TABLE users IN ACCESS SHARE MODE;
LOCK TABLE orders IN ROW EXCLUSIVE MODE;
COMMIT;
Several tables may be listed in one command:
LOCK TABLE users, orders IN SHARE MODE;
Available modes are ACCESS SHARE, ROW SHARE, ROW EXCLUSIVE, SHARE UPDATE EXCLUSIVE,
SHARE, SHARE ROW EXCLUSIVE, EXCLUSIVE, and ACCESS EXCLUSIVE. Without IN ... MODE,
the default is ACCESS EXCLUSIVE.
NOWAIT fails immediately when the lock cannot be acquired and returns SQLSTATE 55P03.
DISCARD
Clears part of the state associated with the current session. It does not undo
a transaction; use ROLLBACK for that.
Supported forms
DISCARD SEQUENCES;
DISCARD ALL;
DISCARD SEQUENCES discards the local state kept for nextval/currval.
The next use registers the sequences visible to the session again. It does
not change a sequence’s persisted value.
DISCARD ALL does the same and also removes values set with SET, restoring
GUCs to their defaults, including
default_transaction_isolation = 'read committed'.
In this version, DISCARD can only run while the session is idle, outside a
BEGIN/COMMIT block. Otherwise it returns SQLSTATE 25001.
Limitations
DISCARD PLANS is not supported yet because protocol prepared statements and
portals are kept by the server loop, outside the Session object. DISCARD TEMPORARY is also not supported because temporary tables are not part of the
current language subset.
These forms are recognized by the parser but return SQLSTATE 0A000.
Tablespaces
Tablespaces place relation files outside the cluster’s main data directory.
CREATE TABLESPACE fast LOCATION '/srv/amphi-fast';
CREATE TABLE events (id int4, payload text) TABLESPACE fast;
ALTER TABLESPACE fast RENAME TO archive;
DROP TABLESPACE archive;
LOCATION must be an absolute path writable by the Amphi process. The
external directory receives a cluster-controlled subdirectory; do not use the
cluster data directory itself. pg_default is the internal tablespace used
when no tablespace is specified.
Creating, renaming, and dropping tablespaces require an administrative session.
ALTER TABLE ... SET TABLESPACE moves existing heap relations to a new
physical generation, preserving heap, TOAST, and indexes. The operation
requires an administrative session; non-heap relations are not supported yet.
Restore-time path mapping is available with an explicit option:
amprestore --tablespace fast=/srv/amphi-fast dump.sql
Repeat the option for multiple tablespaces. Tablespaces not present in the map
keep the LOCATION recorded in the dump.
DROP TABLESPACE requires an empty tablespace. Amphi does not provide
CASCADE for this command; remove associated relations explicitly first.
CREATE TABLESPACE and DROP TABLESPACE cannot run inside a transaction. When
an empty tablespace is removed, Amphi removes its ownership marker; unknown
content prevents the operation.
Partitioning
Status: the declaration and explicit
PARTITION OFbounds are persisted. AHASH ... SUBPARTITIONS ndeclaration creates its children synchronously; future interval partitions are maintained by the internal alarm worker. Routing, pruning, and policies are being expanded incrementally;RETENTIONalready performs a logicalDETACHwithout deleting data.
Partitioning divides one logical table into physical relations. Queries and writes target the parent; the server routes rows, prunes partitions, and creates future partitions when an automatic policy is configured.
Automatic declaration
CREATE TABLE events (
id bigint,
client_id bigint NOT NULL,
created_at timestamp NOT NULL,
payload jsonb,
PRIMARY KEY (created_at, id)
)
PARTITION BY RANGE (created_at)
EVERY INTERVAL '1 month'
RETENTION '12 months';
`HASH ... SUBPARTITIONS n` materializes deterministic children such as `events_h0` through
`events_h<n-1>` during the `CREATE TABLE` DDL. For `RANGE`, the server does not invent bounds:
explicit children use `PARTITION OF`, while `EVERY` interval windows are created by the worker
when they become due. `EVERY` and `RETENTION` remain policy metadata. On the server, a persisted
occurrence in `sys.system_alarms` schedules the next window; the worker wakes at the alarm deadline
and runs the core `partition` handler. The short reconciliation interval only detects a
newly-created policy with an earlier deadline; it is not a daily maintenance scan.
The HASH definition is structural: its key, strategy, and bucket cardinality cannot be changed by
an ordinary `ALTER`. Changing it requires a planned tree migration or rebuild.
An explicit partition can inherit its parent columns:
```sql
CREATE TABLE events_2026_11
PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
In this slice, the parent link and bound are persisted; the child’s physical file is created by DDL, while the parent’s logical storage is not yet fully separated.
The first write path now routes INSERT ... VALUES, including statements
whose rows belong to different partitions. Parent DELETE and UPDATE that
does not change the partition key also scan the children. INSERT ... SELECT
can use the same path when a DEFAULT RANGE partition exists; HASH uses its
fixed buckets without requiring DEFAULT. Updates that move the
key uses the move operator and reapplies the index, check, and foreign-key
validation of an ordinary write. Specific coverage for those combinations is
still being expanded in tests.
EVERY creates interval partitions. The short RETENTION form means DETACH: when the alarm runs, the
partition is removed from the parent, but its relation and data remain available. The worker
currently supports retention in months or days and never turns this operation into DROP.
The alarm state, attempt count, and active lease are visible through sys.system_alarms.
The Web Console shows these alarms in the detail view of a partitioned table or collection,
including kind, state (waiting, running, success, or failed), schedule, attempt, and
error.
Explicit partitions
CREATE TABLE events (
id bigint,
created_at timestamp NOT NULL,
payload jsonb
)
PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_11
PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
A child can also declare the next level of the tree. This is useful for an explicit RANGE → HASH layout:
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01')
PARTITION BY HASH (client_id) SUBPARTITIONS 8;
An existing table can also be attached:
ALTER TABLE events
ATTACH PARTITION events_2026_10
FOR VALUES FROM ('2026-10-01') TO ('2026-11-01');
ATTACH validates bounds, schema, constraints, indexes, and references before publishing the
partition. For collections, validation also decodes every existing document, resolves the
doc.* key path, and rejects missing, incompatible, or out-of-bound values before publishing.
DETACH removes the relation from the tree and turns it into a regular table. Publication
is transactional; physical index and file cleanup may continue in the background.
Subpartitions
CREATE TABLE events (
id bigint,
client_id bigint NOT NULL,
created_at timestamp NOT NULL,
payload jsonb
)
PARTITION BY RANGE (created_at)
PARTITION BY HASH (client_id)
SUBPARTITIONS 8
EVERY INTERVAL '1 month';
Pruning cascades through the tree: first by date, then by client_id. When an explicit RANGE child is created, its HASH children are materialized by the same DDL. The worker creates only new RANGE windows and, inside them, the fixed HASH buckets.
An equality predicate on the HASH key can prune the scan to one bucket; EXPLAIN reports the
reduction, for example PartitionAppend 1 of 8 (pruned 7). Without a compatible predicate, all
buckets are visited.
Default policies
A policy can be associated with a database or schema. When a table matches, the server applies the policy automatically; the CREATE TABLE statement does not need to repeat the clause.
CREATE PARTITION POLICY monthly_events
MATCH TABLES WITH COLUMN created_at timestamp
PARTITION BY RANGE (created_at)
EVERY INTERVAL '1 month'
RETENTION '12 months';
When retention must export before detaching, target an already configured `SERVER`:
```sql
CREATE PARTITION POLICY archived_events
MATCH TABLES WITH COLUMN created_at timestamp
PARTITION BY RANGE (created_at)
EVERY INTERVAL '1 month'
RETENTION '12 months'
ON RETENTION EXPORT TO SERVER archive_s3 THEN DETACH;
The worker reads physical leaves, sends batches to BackupExporter, and detaches only after
finish() succeeds. The request carries parent/child identity and a stable idempotency key
(partition/<parent>/<child>); providers must treat a retry with that key as the same completed
export. The native GCS provider uses resumable chunked uploads and publishes NDJSON with
contentType = application/x-ndjson; credentials are referenced through SECRET and are not
stored in the SERVER definition.
A policy can also be limited to one schema:
CREATE PARTITION POLICY analytics_events IN SCHEMA analytics
MATCH TABLES WITH COLUMN created_at timestamp
PARTITION BY RANGE (created_at)
EVERY INTERVAL '1 month';
ALTER DATABASE app SET DEFAULT PARTITION POLICY monthly_events;
ALTER DATABASE app RESET DEFAULT PARTITION POLICY;
DROP PARTITION POLICY monthly_events;
`SET DEFAULT` marks a database-scoped policy as the administrative default and `RESET` removes
that mark. Automatic matching is still determined by the policy declaration; the server does
not choose a column heuristically.
A policy can be dropped only after it is no longer the default. Dropping a policy does not change
tables or partitions already created from it; it only prevents future automatic applications.
The server never chooses a column heuristically. The policy declares its match. If no policy
matches, the table remains unpartitioned; if multiple policies match, the command fails as
ambiguous. The protocol sends a NOTICE describing the applied policy.
## Collections
Policies targeting collections declare an explicit document path:
```sql
CREATE PARTITION POLICY collection_events
MATCH COLLECTIONS WITH COLUMN doc.created_at timestamp
PARTITION BY RANGE (doc.created_at)
EVERY INTERVAL '1 month';
The parser and catalog preserve the declared path and type. A collection can use HASH or RANGE, and a two-level tree can combine an outer RANGE with an inner HASH:
CREATE COLLECTION events
PARTITION BY RANGE (doc.created_at)
EVERY INTERVAL '1 month'
PARTITION BY HASH (doc.client_id)
SUBPARTITIONS 8;
A collection can also declare an explicit RANGE child and define its HASH level at the same time:
CREATE COLLECTION events_2026 PARTITION OF events
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01')
PARTITION BY HASH (doc.client_id) SUBPARTITIONS 8;
The server routes INSERT to the physical leaf, reads the parent as one logical relation, and
prunes by equality on a document key. FIND returns the same document result; when pruning is
used, the protocol sends an INFO (SQLSTATE 00000) message such as:
partition pruning: selected 1 of 4 partitions (pruned 3)
EXPLAIN FIND shows the same decision before execution:
CollectionPartitionAppend 1 of 4 (pruned 3)
_id remains globally unique. Collection syntax currently supports one subpartition declaration;
the physical tree and worker already traverse additional levels when they exist in the catalog.
Indexes
Users do not need to include the partition key in indexes:
CREATE INDEX events_client_idx ON events (client_id);
CREATE UNIQUE INDEX events_external_id_key ON events (external_id);
Indexes created on the parent are logical definitions maintained by physical local indexes on each
existing leaf. New leaves receive that definition through the worker. Unique indexes use shared
coordination across physical members, so they do not need the partition key and prevent duplicates
across children. Indexes created directly on children remain local. The first coordinator uses the
local members; a durable directory may replace the peer lookup without changing the SQL contract.
Foreign keys can already reference this logical identity; the same infrastructure will be used for
collection _id.
Triggers and inheritance
Triggers created on the parent are logical and apply to the whole tree, including direct writes to a partition. Triggers created on a child are physical and apply only to that relation.
For an UPDATE that moves a row:
- logical triggers see one UPDATE;
- physical triggers see DELETE on the old partition and INSERT on the new one.
Statement triggers on the parent fire once per command, even when multiple partitions are touched. The order is:
logical BEFORE
→ routing
→ physical BEFORE
→ constraints and indexes
→ write
→ physical AFTER
→ logical AFTER
PARTITION OF and INHERITS are different concepts. Partitioning provides routing, bounds, and
pruning; inheritance allows extra columns, multiple parents, and overlap. Ordinary inheritance does
not propagate triggers, constraints, or indexes automatically.
used, the protocol sends an INFO (SQLSTATE 00000) message such as:
CREATE SEQUENCE
Creates a catalog relation of kind sequence:
CREATE SEQUENCE [IF NOT EXISTS] name
[START [WITH] value] [INCREMENT [BY] value]
[MINVALUE value] [MAXVALUE value] [CYCLE | NO CYCLE] [CACHE value]
ALTER SEQUENCE name RESTART [WITH] value
ALTER SEQUENCE name CACHE value
Sequences can be ascending or descending: a positive increment generates increasing values and a
negative increment generates decreasing values. Without explicit bounds, descending sequences use
MAXVALUE -1, MINVALUE -9223372036854775808, and start at -1; ascending sequences start at
1. The nextval, currval, and setval functions are available, and bounds and cycling are
persisted in the catalog.
CACHE n reserves n values per block. The default is 1 for explicit sequences and 32 for
sequences created automatically by serial/bigserial. Reserved values may be skipped after a
crash or restart; ROLLBACK also does not return consumed values. Change the cache with
ALTER SEQUENCE name CACHE n.
CREATE DOMAIN
Creates a persistent type name based on a supported built-in type:
CREATE DOMAIN name AS type
[DEFAULT expression]
[CONSTRAINT name CHECK (VALUE condition)]
[NOT NULL]
The domain has its own catalog identity and reuses the base type representation. Domain CHECK
constraints are applied when the domain is used by a table.
The supported ALTER DOMAIN actions are RENAME TO, SET DEFAULT, DROP DEFAULT,
SET NOT NULL, DROP NOT NULL, ADD CONSTRAINT ... CHECK, and DROP CONSTRAINT;
DROP DOMAIN is also supported. A drop is rejected while any column still uses the domain.
ALTER DOMAIN does not retroactively change defaults, nullability, or checks already copied to
existing columns. COLLATE and nested domains remain future work.
CREATE FUNCTION
Creates a scalar SQL-language function:
CREATE [OR REPLACE] FUNCTION name(argument type [, ...])
RETURNS type
[LANGUAGE SQL]
[SECURITY INVOKER]
AS $$ SELECT expression $$;
For LANGUAGE SQL, the body must contain exactly one SELECT returning one column of the declared type. Argument names can be used in
the body; $1, $2, and subsequent parameters are also supported.
SECURITY INVOKER is the default and may be declared explicitly. SECURITY DEFINER is
executed with the function owner as current_user, while preserving session_user. Function
dependencies in the body are checked recursively under that context. The SELECT may read
relations and must return at most one row; zero rows return NULL.
CREATE FUNCTION add_one(value int)
RETURNS int
AS $$ SELECT value + 1 $$;
SELECT add_one(41); -- 42
Small scalar functions can also use LANGUAGE plamphi after
CREATE EXTENSION plamphi:
CREATE FUNCTION double_value(value int4)
RETURNS int4
LANGUAGE plamphi
AS $$ value * 2 $$;
SELECT double_value(21); -- 42
PLAmphi functions can also iterate over text and compute rules directly in the
language body. Text indices start at zero, .length counts Unicode characters,
and indexing outside the text raises an error:
CREATE FUNCTION second_character(value text)
RETURNS text
LANGUAGE plamphi
AS $$
value[1]
$$;
SELECT second_character('Amphi'); -- m
With these operations, a CPF or CNPJ validator can calculate check digits
using PLAmphi loops and arithmetic; the formula does not need a SELECT.
The same control flow can validate and update inventory inside the caller’s
transaction. A guarded UPDATE ... RETURNING prevents concurrent withdrawals
from driving the balance below zero; throw raises SQLSTATE P0001.
The PLAmphi body can end with an expression of the declared return type or
explicitly return on every possible path; paths that can fall through without a
value are rejected. In this slice, parameters and return values must be
bool, int2, int4, int8,
numeric, float8, or text. Scalar control flow and sql<T> templates with
SELECT without row locks or INSERT, UPDATE, and DELETE with RETURNING
are supported; scalar templates return one column, while for (const row of sql<T[]>...) iterates typed table records. Zero rows in a nullable scalar result
return NULL; more than one row in a scalar result raises an error and rolls
back the calling statement. SQL uses the caller’s transaction, snapshot, and
identity. Read-only templates reject calls to SQL VOLATILE functions; writes
commit or roll back with the caller. A try/catch block containing DML opens a
real savepoint: when a write fails, the protected block is rolled back and the
calling transaction remains usable. The caught Error exposes sqlstate,
message, retryable, and cause; rethrow errors the function does not intend
to handle. The transfer_stock E2E demonstrates two atomic updates: a failure
when crediting the target also rolls back the debit from the source. print,
cursors in DO, explicit transaction blocks, afterCommit, and SECURITY DEFINER
remain unavailable. Persistent functions can iterate typed records from a query:
CREATE TABLE stock_by_product (
product_id int4 PRIMARY KEY,
quantity int4 NOT NULL CHECK (quantity >= 0)
);
CREATE TABLE order_items (
item_id int4 PRIMARY KEY,
order_id int4 NOT NULL,
product_id int4 NOT NULL,
quantity int4 NOT NULL CHECK (quantity > 0),
unit_price int4 NOT NULL CHECK (unit_price >= 0)
);
CREATE FUNCTION process_order(order_id int4)
RETURNS int4 LANGUAGE plamphi AS $$
let total = 0;
let item_count = 0;
for (const item of sql<order_items[]>`
SELECT * FROM order_items
WHERE order_id = ${order_id}
ORDER BY item_id
`) {
const updated_stock = sql<int4?>`
UPDATE stock_by_product
SET quantity = quantity - ${item.quantity}
WHERE product_id = ${item.product_id}
AND quantity >= ${item.quantity}
RETURNING quantity
`;
if (updated_stock == null) {
throw 'Missing product stock or insufficient quantity';
} else {
total = total + item.quantity * item.unit_price;
item_count = item_count + 1;
}
}
if (item_count == 0) {
throw 'Order has no items';
} else {
return total;
}
$$;
Each item is a typed record. A failure on a later item rolls back earlier
stock updates, and an outer ROLLBACK also undoes the order. The current host
buffers query rows in memory before iteration. DML row conflicts may return 40001.
The DDL and function history persist; the function is recompiled when the
database is reopened.
A function can also send an event to a queue. Sending uses the same transaction as the stock changes: commit publishes the event, while rollback discards both the event and the changes. Structured values are sent as JSON; text is passed through unchanged:
CREATE QUEUE order_events (payload text);
CREATE FUNCTION process_and_notify(order_id int4, total int4)
RETURNS int4 LANGUAGE plamphi AS $$
db.order_events.send({ order_id: order_id, total: total });
return total;
$$;
If a send occurs in a try block that fails, the block savepoint discards that
provisional message too. The queue is resolved and validated at compile time;
its persisted OID identifies the resource at runtime.
The same pattern can combine a conditional update with an audit row. The
balance = old_balance condition detects a concurrent change after the read;
the function fails instead of writing a value calculated from stale data:
CREATE TABLE account_balance (
account_id int4 PRIMARY KEY,
balance int4 NOT NULL CHECK (balance >= 0)
);
CREATE TABLE balance_audit (
account_id int4 NOT NULL,
old_balance int4 NOT NULL,
new_balance int4 NOT NULL
);
CREATE QUEUE balance_events (payload text);
CREATE FUNCTION change_balance(account_id int4, delta int4)
RETURNS int4 LANGUAGE plamphi AS $$
const old_balance = sql<int4?>`
SELECT balance FROM account_balance WHERE account_id = ${account_id}
`;
if (old_balance == null) {
throw 'Account not found';
} else {
const new_balance = old_balance + delta;
if (new_balance < 0) {
throw 'Insufficient balance';
} else {
const updated = sql<int4?>`
UPDATE account_balance SET balance = ${new_balance}
WHERE account_id = ${account_id} AND balance = ${old_balance}
RETURNING balance
`;
if (updated == null) {
throw 'Balance changed concurrently';
} else {
sql<int4>`INSERT INTO balance_audit
(account_id, old_balance, new_balance)
VALUES (${account_id}, ${old_balance}, ${updated})
RETURNING account_id`;
db.balance_events.send({ account_id: account_id,
old_balance: old_balance, new_balance: updated });
return updated;
}
}
}
$$;
The balance, audit row, and event belong to the same transaction. A missing account, insufficient balance, concurrent change, or outer rollback leaves no partial effects.
PLAmphi DO blocks, functions, and procedures can also contain direct SQL.
SELECT ... INTO and DML with RETURNING ... INTO bind local variables as SQL
parameters. The target must be nullable: zero rows assign null and set FOUND
to false; one row assigns the value and sets FOUND to true; multiple rows
raise 21000 without a partial assignment. ROW_COUNT is 0 or 1 in these
cases, and FOUND equals ROW_COUNT > 0. For DML without RETURNING,
ROW_COUNT is the actual number of affected rows and FOUND reports whether
any row changed. This stage accepts one scalar target. A failed command keeps
the previous status values.
CREATE FUNCTION update_stock(product int4, amount int4) RETURNS int4
LANGUAGE plamphi AS $$
let remaining: int4? = null;
UPDATE stock SET quantity = quantity - amount
WHERE product_id = product
RETURNING quantity INTO remaining;
return remaining ?? 0;
$$;
The body accepts dollar-quoted strings, including named delimiters ($$ ... $$ and
$SQL$ ... $SQL$). OR REPLACE keeps the function identity and creates a new revision.
Different argument lists are distinct overloads.
History and diff
Every create or replace stores the complete DDL in sys.object_revision, together with its
version, author, and timestamp:
SELECT version, source, created_by, created_at
FROM sys.object_revision
WHERE object_kind = 'function'
ORDER BY object_oid, version;
The retained history is controlled by amphi.function_history_retention. The default is 10;
a positive value keeps the latest N versions and 0 keeps all versions:
SET amphi.function_history_retention = 20;
The diff returns one text cell in unified-diff format, with one complete source line per diff
line. The signature must identify the exact overload; a version can be a number or HEAD:
SELECT sys.function_diff('add_one(int)', '1', 'HEAD');
The body also records the functions it calls. While an active dependent function exists,
DROP FUNCTION fails with 2BP01; remove or replace the dependent first.
The function owner is the user who created the first revision. Only that owner or an admin may
use CREATE OR REPLACE FUNCTION or DROP FUNCTION.
Current limitations: scalar SQL functions follow the one-SELECT contract; persistent PLAmphi
functions are limited to the scalar subset above. Persisted procedures are documented in CREATE PROCEDURE; packages and selective version restoration are outside this delivery. DROP FUNCTION removes
the active definition but preserves retained history. Recreating the same signature after a drop
creates a new object with a new OID and history starting at version 1; the previous history
remains attached to the old OID.
Trigger functions
A PLAmphi trigger function declares RETURNS trigger and is attached to a table with
CREATE TRIGGER. The first slice supports BEFORE ROW triggers for INSERT and UPDATE on heap
tables:
CREATE FUNCTION validate_quantity()
RETURNS trigger
LANGUAGE plamphi AS $$
if (NEW.quantity < 0) {
throw 'Invalid quantity';
}
return NEW;
$$;
CREATE TRIGGER validate_quantity
BEFORE INSERT OR UPDATE ON inventory
FOR EACH ROW
EXECUTE FUNCTION validate_quantity();
NEW is the proposed row. OLD is available during UPDATE. Return NEW to continue;
return null suppresses the row. throw aborts the statement and rolls back its writes.
Trigger functions cannot be called through SELECT. Embedded SQL and transaction control are not
available in a trigger body; DELETE, AFTER, statement-level triggers, and other relation kinds
are not supported yet.
CREATE PROCEDURE
Creates a persisted routine with no return value. In this stage, executable bodies are supplied by a language extension such as PLAmphi:
CREATE PROCEDURE transfer_stock(source_id int4, target_id int4, amount int4)
LANGUAGE plamphi AS $$
if (amount <= 0) { throw 'Amount must be positive'; }
transaction {
const remaining = sql<int4?>`UPDATE inventory
SET quantity = quantity - ${amount}
WHERE client_id = ${source_id} AND quantity >= ${amount}
RETURNING quantity`;
if (remaining == null) { throw 'Insufficient stock'; }
sql<int4?>`UPDATE inventory
SET quantity = quantity + ${amount}
WHERE client_id = ${target_id}
RETURNING quantity`;
}
$$;
CALL transfer_stock(1, 2, 4);
CALL accepts positional arguments compatible with the declared types and
returns no row. A transaction {} block commits atomically when called outside
a caller transaction and uses a savepoint inside BEGIN; the outer COMMIT or
ROLLBACK still controls the caller transaction. Errors propagate their
SQLSTATE and roll back writes performed in the block.
CREATE OR REPLACE PROCEDURE replaces the revision with the same signature.
DROP PROCEDURE name(type, ...) removes the selected routine. OUT and
INOUT parameters, autonomous transactions, and procedures in languages that
do not implement the procedure contract are outside this stage.
CREATE DATABASE
CREATE DATABASE creates and initializes an independent physical store in the
current cluster:
CREATE DATABASE name;
CREATE DATABASE IF NOT EXISTS name;
CREATE DATABASE name TEMPLATE template1;
ALTER DATABASE name OWNER TO role;
DROP DATABASE name;
DROP DATABASE IF EXISTS name;
Only an administrator can run the command in this delivery. The directory is
created at databases/<name> with a control file, WAL, and bootstrapped
catalog. IF NOT EXISTS emits a notice when the directory already exists.
Bootstrap creates amphi and template1. Without TEMPLATE, the source is
template1; TEMPLATE name clones the selected database’s catalog and data.
Templates cannot have active connections.
Roles, SCRAM credentials, and group memberships are cluster-global: changes
made from amphi or a child database are resolved through the cluster
authority and are available for authentication in the other databases. The
command does not switch the current session’s database. New connections can
provide the created name in startup and the server opens and caches the matching
store. The server also discovers valid physical stores in the cluster. \\l
lists those names through sys.catalog_databases, which also exposes
owner and template. The sys.catalog_roles, sys.catalog_groups, and
sys.catalog_group_members projections also reflect the global authority. The
custom dump preserves SCRAM verifiers; the SQL/plain format preserves only role
attributes and memberships.
The cluster dump preserves database owners and TEMPLATE sources in dependency
order. template0 is intentionally not part of the product.
Main errors are 3D000 for an unknown database, 42501 for a
non-administrator, 42P04 for a duplicate name without IF NOT EXISTS, and
42602 for an invalid name.
ALTER DATABASE requires an administrator and an existing role. DROP DATABASE
requires an administrator, refuses the current database, and removes the store
files. The command also refuses the operation while the target database has
active connections.
CREATE INDEX
CREATE [ UNIQUE ] INDEX [ CONCURRENTLY ] [ IF NOT EXISTS ] name
ON table_or_collection [ USING { btree | gin } ]
(column [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ] [, ...])
[ WITH (fillfactor = integer) ];
btree is the default for orderable keys. gin supports array containment
(@>) and overlap (&&), and collection content searches on doc with @>.
The index narrows the candidates; the original predicate is rechecked to
preserve exact semantics. For doc, the planner uses GIN only for positive
structural equality filters whose indexed terms are necessary for a match.
Logical or negative operators, equality with null, and empty containers use a
sequential scan. Those filters remain valid and return the same results.
Example GIN index on a collection:
CREATE INDEX events_doc_gin ON events USING gin (doc);
Expressions, partial indexes, and INCLUDE are not available.
For B-tree indexes, fillfactor accepts values from 10 to 100 and defaults to
90. It controls initial leaf-page occupancy. The option is persisted and used
by REINDEX; ALTER INDEX name SET (fillfactor = n) changes the option for the
next rebuild and RESET (fillfactor) returns to the default.
CREATE VIEW
CREATE SCHEMA
CREATE EXTENSION
CREATE EXTENSION [ IF NOT EXISTS ] name [ WITH SCHEMA schema ];
Registers an extension available to the server. See Extension development.
Without WITH SCHEMA, the extension is installed in the first schema in
search_path; an explicitly named schema must already exist. Extensions do not
create a private schema automatically. For example:
CREATE SCHEMA spatial;
CREATE EXTENSION amphi_gis WITH SCHEMA spatial;
Installs are recorded in sys.extension, including the extension name,
installation schema, and package version. The catalog survives restarts, and
ampdump emits CREATE EXTENSION before dependent objects. Restore requires the
same extension to be available on the target; the installed version is the
package version available there. Installs created before explicit registration
are not inferred or migrated automatically. Secrets and external connections
remain outside logical dumps.
PLAmphi
plamphi provides the PLAmphi procedural language. After installation it can
be inspected through sys.language and used in DO blocks:
CREATE EXTENSION plamphi;
DO LANGUAGE plamphi AS $$
print(1 + 2);
$$;
DO supports scalar expressions, print, and parameterized SQL templates with
SELECT, INSERT, UPDATE, and DELETE. A template must return one column
and at most one row; DML uses RETURNING. Each ${expression} becomes a bound
SQL parameter. Execution shares the session transaction, and transaction {}
and write-bearing try/catch blocks use real savepoints.
print(value) emits a server notice; ampsql displays it on stderr.
A non-nullable scalar query that returns no rows fails with SQLSTATE 02000.
Example:
CREATE TABLE counters (value int4);
DO LANGUAGE plamphi AS $$
const next = sql<int>`INSERT INTO counters VALUES (${1}) RETURNING value`;
print(next);
$$;
Current limits: SQL cursors and afterCommit are not available; templates with
multiple columns, multiple rows, or utility commands are rejected. Parameter
and result types are limited to the scalar subset supported by the runtime.
Each block is limited to 100,000 step checks and 1,000,000 instructions.
statement_timeout, transaction_timeout, and session cancellation also
interrupt the block.
DROP TABLE
DROP SEQUENCE
Explicitly removes a sequence:
DROP SEQUENCE [IF EXISTS] name
IF EXISTS emits a notice when the object does not exist.
DROP VIEW
DROP VIEW [ IF EXISTS ] nome [, ...];
DROP INDEX
DROP INDEX [ CONCURRENTLY ] [ IF EXISTS ] nome [, ...];
REINDEX
REINDEX INDEX [ CONCURRENTLY ] name;
REINDEX [ CONCURRENTLY ] TABLE name;
Rebuilds a B-tree or GIN index from the table’s visible rows. The
REINDEX TABLE form rebuilds the table’s valid indexes.
REINDEX CONCURRENTLY builds replacement indexes while the old indexes remain
in use and cannot run inside a transaction block (BEGIN/COMMIT).
If a concurrent rebuild fails, the original index remains available.
Because the rebuild publishes a replacement relation, the index’s internal OID may change.
REINDEX reapplies the fillfactor persisted on the index.
Expressions, partial indexes, and INCLUDE are outside the current index
subset.
DROP SCHEMA
COPY
TRUNCATE
TRUNCATE TABLE removes every row from one or more tables in one operation:
TRUNCATE TABLE sessions;
TRUNCATE TABLE sessions, events RESTART IDENTITY;
The command is transactional. Inside a transaction, ROLLBACK restores the
removed rows. The table and its indexes remain available for new INSERTs, and
the command returns the TRUNCATE TABLE tag.
Foreign keys
Without CASCADE, the command is rejected when another table has a foreign key
referencing the target, even if the child table is empty:
TRUNCATE TABLE parent CASCADE;
With CASCADE, dependent tables are truncated in the same savepoint, in
child-to-parent order. A ROLLBACK undoes the whole operation. Self-referencing
foreign keys are allowed.
Multiple tables can be listed with commas. Without CASCADE, a referenced table
must be included in the same list or the command is rejected. RESTART IDENTITY
resets sequences owned by serial/bigserial columns to start at 1, including
dependents expanded by CASCADE.
Concurrency and current limitations
TRUNCATE takes an exclusive relation lock. Concurrent writes wait or fail with
55P03, according to lock_timeout.
For heap tables, the command swaps in an empty physical generation. The old
generation is removed only after commit and when no active snapshot depends on
it. B-tree and GIN indexes are swapped together with the heap. Identity resets are transactional
and are undone by ROLLBACK/ROLLBACK TO SAVEPOINT.
Identity and access policies
Object privileges are separate from identity management. Functions support explicit overload
grants with GRANT EXECUTE ON FUNCTION, for example:
GRANT EXECUTE ON FUNCTION public.add_one(int) TO analyst;
REVOKE EXECUTE ON FUNCTION public.add_one(int) FROM analyst;
CREATE SECRET
CREATE SECRET stores a credential for providers, external connections,
foreign data wrappers, and backup operations. Only administrators can create
secrets in the current release.
CREATE SECRET name TYPE TEXT VALUE 'sensitive value';
CREATE SECRET openai_api_key TYPE TEXT VALUE '...';
CREATE SECRET IF NOT EXISTS service_credentials TYPE JSON
VALUE '{"access_token":"..."}';
The value cannot be read through SQL, SHOW, system views, audit output, error
messages, or dumps. Providers need to recover credentials to authenticate, so
values are encrypted at rest rather than hashed.
For systemd services, provide the key as a protected credential. Configure
LoadCredentialEncrypted in the unit; the process reads the amphi-secret-key
credential from $CREDENTIALS_DIRECTORY:
[Service]
LoadCredentialEncrypted=amphi-secret-key:/etc/credstore.encrypted/amphi-secret-key
The decrypted credential must contain 64 hexadecimal characters (32 bytes),
optionally followed by a newline. This credential is the only supported key
configuration; environment variables are not supported. Without
CREDENTIALS_DIRECTORY, the server can start without secret access, but
creating or resolving secrets fails.
The key is not written to the data directory. secrets.bin and its temporary
file are restricted to the server user (mode 0600); keep the data directory
accessible only to that user as well. Without the key, the server can start,
but creating or resolving secrets fails. Storage uses AES-256-GCM and an atomic
file update. The file format is not a public API. KMS, HSM, and external secret
managers are future work.
CREATE SECRET writes outside the catalog transaction, so run it in autocommit;
ROLLBACK cannot undo it. Statement audit events redact the SQL literal.
Rotate a value without changing its name or type:
ALTER SECRET openai_api_key VALUE 'new-sensitive-value';
ALTER SECRET encrypts the replacement value with a fresh nonce and atomically
rewrites secrets.bin. It must run in autocommit and cannot be rolled back. The
secret type is preserved. Statement and security audit events include the secret
name but redact the value.
Remove a secret that is no longer used:
DROP SECRET openai_api_key;
DROP SECRET IF EXISTS optional_key;
DROP SECRET is administrator-only and autocommit-only. It refuses to remove a
secret referenced by an external connection, server option, or foreign-table
option. Remove those definitions first, then drop the secret. IF EXISTS
suppresses only the missing secret error; it does not bypass dependency checks.
Secret values remain outside logical dumps. Fine-grained permissions are not
available yet.
Reference a secret from an external connection instead of passing its value to the provider:
CREATE EXTERNAL CONNECTION openai_prod
PROVIDER openai
OPTIONS (api_key = SECRET openai_api_key);
CREATE EXTERNAL CONNECTION
CREATE EXTERNAL CONNECTION registers a reusable connection for an external
provider. A connection can be referenced by a SERVER, FDW, FCW, backup, or
remote operation.
CREATE EXTERNAL CONNECTION csv_local
PROVIDER csv
WITH (root = '/data/csv');
Connection options define shared access context. Options specific to one file or resource belong on the consuming object, usually the foreign table:
CREATE SERVER csv_files CONNECTION csv_local;
CREATE FOREIGN TABLE people_csv (
id int8,
name text
)
SERVER csv_files
WITH (file = 'people.csv', delimiter = ',', header = true);
Reference credentials through CREATE SECRET:
CREATE EXTERNAL CONNECTION aws_prod
PROVIDER aws
WITH (credentials = SECRET aws_credentials, region = 'us-east-1');
SECRET name is a reference, not the credential value. The server resolves the
secret when it validates or opens the provider. The catalog stores the
connection definition and secret reference, never the resolved credential.
Connection definitions are persisted in the catalog and remain available after a server restart. Logical dumps currently include external connection and server definitions only when their option lists are empty. Opaque provider options are not written because they may contain credentials, and the omitted definitions produce a warning. If an omitted definition has tags, dumping fails instead of silently losing those tags. Secret values are never included.
Full plain/custom dumps include foreign table definitions, comments, and tags
when their server and connection can be restored safely. Remote rows are not
copied. Option names that suggest credentials require a SECRET reference;
otherwise dumping stops rather than placing a possible credential in the
archive. Provision referenced secrets on the target first.
The provider validates its options and implements the capabilities it offers. The core stores the definition and routes provider operations to the matching provider.
CREATE ROLE
CREATE ROLE name
[ PASSWORD 'password' ]
[ LOGIN | NOLOGIN ]
[ SUPERUSER | NOSUPERUSER ]
[ CREATEDB | NOCREATEDB ]
[ CREATEROLE | NOCREATEROLE ]
[ INHERIT | NOINHERIT ]
[ VALID UNTIL 'timestamp' ];
Creates a persisted authorization role. Defaults are NOLOGIN, NOSUPERUSER,
NOCREATEDB, NOCREATEROLE, and INHERIT. VALID UNTIL limits
authentication; infinity removes the limit.
ALTER ROLE
ALTER ROLE name PASSWORD 'password';
ALTER ROLE name { LOGIN | NOLOGIN };
ALTER ROLE name { SUPERUSER | NOSUPERUSER };
ALTER ROLE name { CREATEDB | NOCREATEDB };
ALTER ROLE name { CREATEROLE | NOCREATEROLE };
ALTER ROLE name { INHERIT | NOINHERIT };
ALTER ROLE name VALID UNTIL 'timestamp';
ALTER ROLE name ENABLE;
ALTER ROLE name DISABLE;
Changes role attributes. VALID UNTIL 'infinity' removes expiration.
DROP ROLE
DROP ROLE [ IF EXISTS ] name;
Removes a role and its group memberships.
GRANT ROLE
GRANT group TO role;
Adds a group or role to a role. The granted identity comes first and the member
comes after TO; membership is persisted and exposed through
sys.catalog_group_members.
Amphi also accepts the explicit extension GRANT role TO GROUP group when the
target must be identified as a group.
Default privileges
ALTER DEFAULT PRIVILEGES configures grants automatically applied to new
tables, collections, queues, and memory tables created by the owning role:
ALTER DEFAULT PRIVILEGES
GRANT SELECT ON TABLES TO reporting;
The command does not accept column lists. Scopes such as SELECT (email) or
SELECT EXCEPT (secret) must be used with GRANT/REVOKE on a concrete table,
where the column set is already defined.
REVOKE ROLE
REVOKE group FROM role;
Removes a group or role from a role. This is the canonical authorization syntax
for the same catalog operation as ALTER GROUP ... DROP ROLE.
Amphi also accepts the explicit extension REVOKE role FROM GROUP group when
the target must be identified as a group.
CREATE USER
ALTER USER
ALTER USER nome PASSWORD 'senha';
ALTER USER nome ENABLE;
ALTER USER nome DISABLE;
ENABLE e DISABLE controlam se a identidade pode autenticar.
DROP USER
DROP USER [ IF EXISTS ] nome;
O Amphi impede remover ou desabilitar o último administrador habilitado capaz de login.
CREATE GROUP
ALTER GROUP
ALTER GROUP grupo ADD USER usuario;
ALTER GROUP grupo DROP USER usuario;
DROP GROUP
DROP GROUP [ IF EXISTS ] nome;
CREATE ACCESS POLICY
Creates a row-level access policy for a relation.
CREATE ACCESS POLICY policy_name
ON schema_name.table_name
USING (tenant_id = current_setting('app.tenant_id'));
The USING expression is evaluated for rows visible to the current role. Keep policies deterministic and test both matching and non-matching rows. Policy syntax and enforcement are still an initial implementation; unsupported expressions are rejected during binding.
DROP ACCESS POLICY
DROP ACCESS POLICY [ IF EXISTS ] nome;
CHECK ACCESS POLICY
Transactions and savepoints
Each command has a dedicated page: BEGIN, START TRANSACTION, COMMIT, ROLLBACK, SAVEPOINT, RELEASE SAVEPOINT, and SET TRANSACTION.
Supported isolation levels are READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, and
SERIALIZABLE.
Two-phase transactions (2PC)
With max_prepared_transactions greater than zero in amphi.conf and after restarting the
server, an explicit transaction with an XID can be detached from the session that began it:
BEGIN;
INSERT INTO orders VALUES (42);
PREPARE TRANSACTION 'coordinator-order-42';
-- In another session, including after a server restart:
COMMIT PREPARED 'coordinator-order-42';
-- Or: ROLLBACK PREPARED 'coordinator-order-42';
PREPARE TRANSACTION writes and synchronizes the state before it responds. The GID is
cluster-unique; XIDs and row locks stay active and are rebuilt during recovery until the final
decision. sys.prepared_transactions lists pending transactions.
The current subset rejects preparation with catalog DDL, savepoints, pending extensions, queue
operations, deferred foreign keys, or RESTART IDENTITY (0A000). A transaction without an XID or outside
an explicit block fails with 25001; a duplicate GID fails with 42710; and an unknown GID in
COMMIT PREPARED/ROLLBACK PREPARED fails with 42704. nextval remains non-transactional.
Logical backup cannot decide a coordinator transaction: ampdump refuses a dump while a prepared
transaction exists. After it is resolved, dump and restore use the normal flow; they neither
export nor recreate 2PC state.
Commit durability
The default is commit_durability = local: the server synchronizes commit WAL before acknowledging
COMMIT. For ordinary DML, a session may opt into SET commit_durability = async; the response then
follows WAL append without waiting for fsync, and a crash may lose already acknowledged commits. They
remain visible while the process is alive. DDL, catalog operations, and every 2PC step continue to use
local. wal_writer_delay limits the normal loss window but provides no absolute guarantee. The
default is a recommendation; different environments may achieve better results with other settings.
For a registered synchronous physical replica, SET commit_durability = 'replicas(1)' waits for
one persisted replica ACK; replicas(n) waits for n synchronous replicas. If the quorum is not
available, the commit fails in this first cut.
BEGIN
START TRANSACTION
START TRANSACTION [ ISOLATION LEVEL { READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE } ];
COMMIT
ROLLBACK
SAVEPOINT
RELEASE SAVEPOINT
RELEASE [ SAVEPOINT ] nome;
Libera o savepoint indicado.
SET TRANSACTION
SET TRANSACTION ISOLATION LEVEL {
READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE
};
The command changes the isolation of the current transaction and must run before its first query or write. Outside a transaction, it sets the isolation for the next transaction.
Amphi executes READ COMMITTED and REPEATABLE READ. Although READ UNCOMMITTED and SERIALIZABLE are accepted by the parser for syntax
compatibility, they return SQLSTATE 0A000 because they are not implemented.
READ ONLY, DEFERRABLE, and equivalent options are not currently available.
If the command runs after a query or write in the transaction, it returns
SQLSTATE 25001.
SET CONSTRAINTS
Changes, within the current transaction, when foreign keys declared as
DEFERRABLE are checked.
SET CONSTRAINTS ALL DEFERRED;
SET CONSTRAINTS ALL IMMEDIATE;
SET CONSTRAINTS child_parent DEFERRED;
SET CONSTRAINTS child_parent, other_parent IMMEDIATE;
DEFERRED allows a deferrable foreign key to be temporarily violated during
the transaction. The check runs when it is changed back to IMMEDIATE or at
COMMIT, according to the effective constraint state.
IMMEDIATE validates pending deferrable foreign keys before changing the
mode. If a reference is still invalid, the command fails with SQLSTATE 23503
and the mode is not changed.
The command can only run inside an explicit transaction. Its mode belongs to
the current transaction, is saved by SAVEPOINT, and is restored by
ROLLBACK TO SAVEPOINT.
Non-deferrable constraints remain immediate. The foreign key must be declared
DEFERRABLE, for example:
CREATE TABLE child (
parent_id int4 REFERENCES parent(id) DEFERRABLE INITIALLY DEFERRED
);
SET CONSTRAINTS does not make a non-deferrable foreign key deferrable and does
not change the persisted catalog definition.
Session and diagnostics
Each command has a dedicated page: SET, RESET, SHOW, and
EXPLAIN. See Transactions for SET TRANSACTION.
SET
SET [ SESSION ] parameter { TO | = } value;
Available parameters are listed in Configuration reference.
RESET
RESET parâmetro;
RESET ALL;
SHOW
SHOW parâmetro;
SHOW ALL;
EXPLAIN
EXPLAIN
EXPLAIN [ ( ANALYZE [, VERBOSE ] ) ] SELECT ...;
EXPLAIN shows the plan without executing the query. ANALYZE executes the query and includes
observed metrics for each node: inclusive time, rows delivered, and the number of loops.
VERBOSE adds an Output: line with the columns produced by each node.
The current subset accepts read-only queries only. EXPLAIN ANALYZE for INSERT, UPDATE,
DELETE, or another data-modifying statement returns 0A000. The BUFFERS option is not
supported yet.
WITH RECURSIVE plans may also include iterations, iteration_N_rows, duplicates,
spills, and plan-specific memory counters.
Maintenance
VACUUM
VACUUM [ VERBOSE ] [ table [, ...] ];
Without a table list, VACUUM processes eligible relations. FULL, FREEZE, and cost options
are not currently supported.
ANALYZE
CHECKPOINT
Forces a checkpoint for the current database by flushing dirty pages, making the required WAL durable, persisting the commit log, and publishing the redo point in the control file. The mechanism may remove WAL segments before the new recovery point when it is safe to do so.
CHECKPOINT;
The command does not change logical data or commit/abort transactions. It can
only be executed by an administrator while the session is idle, outside a
BEGIN/COMMIT block.
Relevant errors:
- SQLSTATE
42501: the session lacks administrator privilege; - SQLSTATE
25001: an explicit transaction is open; - SQLSTATE
XX000: WAL, data, or control-file persistence failed.
Manual checkpoints are maintenance operations and may produce I/O and latency. The server also runs checkpoints according to its policy; this command only forces an immediate checkpoint for the current database.
Schedules
Schedules register actions for future execution by Amphi’s integrated scheduler. The scheduler is a generic subsystem: SQL, backup, materialized-view refresh, and queue delivery can use the same trigger, policy, and execution-history mechanism.
Each schedule is persisted in the catalog. The server uses one orchestrator thread and a bounded worker pool; creating schedules does not create individual threads.
Execution session
Each DO SQL action runs in a dedicated internal session created by the worker. It is independent
of the client session that created the schedule and is closed when the action finishes.
poller/orchestrator
-> atomic occurrence claim
-> bounded queue
-> worker
-> dedicated internal session
-> SQL execution and commit/rollback
-> schedule history
The worker pool is shared by all schedules. Execution is at-least-once: after a crash or timeout,
an action may run again, so actions should be idempotent or deduplicate using the recorded
run_id. The runtime also provides a no-poller mode for servers or tests that dispatch
occurrences explicitly.
Logical dump and restore
ampdump exports tables, views, and materialized views. It does not export schedule
definitions or sys.schedule_run history.
When a full database dump is implemented, only schedule definitions should be exported as recreatable DDL. Execution history is operational and should not be restored. Schedules must be restored after the tables, queues, views, and materialized views referenced by their actions, and must not start running before data loading completes.
Secret values are never part of a dump. A schedule may refer to an EXTERNAL CONNECTION, but its
credentials remain outside the backup.
See CREATE SCHEDULE, ALTER SCHEDULE, and DROP SCHEDULE.
CREATE SCHEDULE
The scheduler persists schedule definitions and executes SQL actions. The runtime also has a generic path for native actions supplied by providers and extensions.
CREATE SCHEDULE purge_sessions
EVERY '5 minutes'
FROM '2026-11-06 23:00:00-03:00'
DO SQL $$
DELETE FROM sessions WHERE expires_at < now()
$$
WITH (
overlap = 'skip',
catch_up = 'none',
timeout = '1 minute'
);
EVERY is anchored at FROM; the next occurrence is calculated from that instant, not from the
end of the previous execution. A one-time execution uses AT:
CREATE SCHEDULE migrate_legacy
AT '2026-12-01 02:00:00-03:00'
DO SQL $$ INSERT INTO new_events SELECT * FROM legacy_events $$;
A materialized view can be refreshed through the same SQL execution path:
CREATE SCHEDULE refresh_dashboard
EVERY '10 minutes'
DO SQL $$ REFRESH MATERIALIZED VIEW dashboard $$;
Available policies are overlap = skip|queue|allow, catch_up = none|one, timeout, and
max_retries.
ALTER SCHEDULE
Controls an existing schedule:
ALTER SCHEDULE purge_sessions DISABLE;
ALTER SCHEDULE purge_sessions ENABLE;
ALTER SCHEDULE purge_sessions RUN NOW;
ENABLE and DISABLE update the persisted state. Currently, RUN NOW only records a manual run
in the schedule history as Claimed; it does not yet submit the action to a worker.
Schedules cannot be altered inside an explicit transaction.
DROP SCHEDULE
Removes a schedule from the catalog:
DROP SCHEDULE purge_sessions;
DROP SCHEDULE IF EXISTS purge_sessions;
Already-started executions are not automatically interrupted. Their recorded history remains available in the catalog. Schedules cannot be dropped inside an explicit transaction.
Built-in functions
Built-in functions are registered in the catalog and can be inspected through sys.function.
User-defined functions are documented in CREATE FUNCTION, including
versioning, retention, and sys.function_diff.
Signatures are resolved from argument types; each family has its own reference page:
- Text functions
- Math functions
- UUID and system functions
- Pattern operators and functions
- Aggregate functions
- Table functions
- Extension functions
Functions are strict by default: a NULL argument produces NULL. The documented exceptions
are concat, concat_ws, and random.
Inspecting the catalog
SELECT name, arg_types, ret_type, aggregate, volatility
FROM sys.function
ORDER BY name, arg_types;
This query is the operational reference for functions installed in the current cluster.
Text functions
All functions on this page accept text and return text unless noted otherwise. Lengths count
Unicode characters; octet_length counts UTF-8 bytes.
| Function | Signature and return type |
|---|---|
length, char_length, octet_length | text → int4 |
lower, upper | text → text |
substr, substring | (text, int4) or (text, int4, int4) → text |
btrim, ltrim, rtrim | (text) or (text, text) → text |
replace | (text, text, text) → text |
strpos | (text, text) → int4 |
left, right | (text, int4) → text |
repeat | (text, int4) → text |
reverse, initcap | text → text |
ascii | text → int4 |
chr | int4 → text |
concat, concat_ws | overloaded → text |
split_part | (text, text, int4) → text |
translate | (text, text, text) → text |
starts_with | (text, text) → bool |
concat ignores NULL arguments. concat_ws returns NULL when its separator is NULL.
Math functions
abs is available for int2, int4, int8, and float8. Unless noted otherwise, the
following functions operate on float8:
ceil, ceiling, floor, round, trunc, sign
sqrt, exp, ln, log(float8), log(float8, float8), power(float8, float8)
pi, sin, cos, tan, cbrt, degrees, radians
mod is available for int2, int4, and int8); gcdandlcmare available forint4andint8`. Arithmetic errors return SQLSTATE instead of silently saturating.
UUID and system functions
uuidv7() -- time-ordered uuid
gen_random_uuid() -- uuid
uuidv4() -- uuid
version() -- text
random() -- float8
now() -- timestamptz, classified as stable
clock_timestamp() -- timestamptz, volatile
random, uuidv7, uuidv4, and gen_random_uuid are volatile. version() and now() are
stable within a single command: all evaluations reuse the same value during execution.
clock_timestamp() is volatile and reads the clock on each evaluation. Both use UTC and the
server environment’s injected clock.
Pattern operators and functions
For text values, Amphi provides:
value LIKE pattern;
value NOT LIKE pattern;
value ILIKE pattern;
value NOT ILIKE pattern;
like_escape(value, escape);
LIKE is case-sensitive. ILIKE performs a case-insensitive comparison using the standard
Unicode mapping.
Aggregate functions
Available aggregates include:
count, sum, avg, min, max,
bool_and, bool_or, string_agg,
var_samp, var_pop, variance,
stddev, stddev_samp, stddev_pop
Signatures are registered by type in sys.function. sum and avg are numeric; count,
min, and max also have text and boolean variants where applicable.
SELECT count(*), avg(price), max(name) FROM products;
Window functions
This slice supports row_number(), rank(), dense_rank(), lag(), lead(),
first_value(), and last_value() with OVER:
SELECT group_id, value,
row_number() OVER (PARTITION BY group_id ORDER BY value DESC NULLS LAST)
FROM measurements;
OVER (), PARTITION BY, and ORDER BY with ASC, DESC, NULLS FIRST, and
NULLS LAST are supported. Without ORDER BY, numbering follows the order received
by the plan and is not deterministic. The implementation streams compatible
partitions within work_mem, spilling them to scratch files when needed, and
uses global materialization as a fallback for incompatible expressions.
Named windows can be declared after the filtering clauses:
SELECT row_number() OVER ordered
FROM measurements
WINDOW ordered AS (PARTITION BY group_id ORDER BY value);
This version also accepts ROWS, RANGE, and GROUPS BETWEEN frames with the bounds UNBOUNDED PRECEDING,
CURRENT ROW, n PRECEDING/n FOLLOWING, and UNBOUNDED FOLLOWING. The frame is
effective for first_value, last_value, and the count, sum, avg, min,
max, bool_and, bool_or, bit_and, bit_or, and any_value window
aggregates. Aggregates ignore NULL values; count(*) is also
supported. For an ordered window without an explicit frame, aggregates use the
partition start through the current peer group. FILTER and DISTINCT in window
calls are supported for window aggregates; they do not apply to ranking or value
functions. EXCLUDE NO OTHERS,
string_agg(value, delimiter), var_samp, var_pop, variance, stddev,
stddev_samp, and stddev_pop are also supported. Statistical aggregates use
their sample/population semantics and return NULL when there are insufficient
observations.
EXCLUDE CURRENT ROW, EXCLUDE GROUP, and EXCLUDE TIES are supported.
lag and lead accept value, an optional offset, and an optional default, in
that order. The offset must be a non-negative integer; when no matching row exists,
the default is returned, or NULL when no default was supplied.
Without an explicit frame, first_value and last_value use the window’s default
frame; with an explicit frame, they respect its bounds and EXCLUDE clause.
When one or more windows share the same specification and use direct column keys,
the plan shares one sort and processes one partition at a time, charging that
partition against work_mem. If it exceeds the limit, the partition uses the
scratch file. Incompatible windows or expression keys still use the global
materialization path.
Ordered-set aggregates
The first ordered-set aggregate slice also supports percentile_disc(fraction),
percentile_cont(fraction), and mode() with WITHIN GROUP (ORDER BY ...):
SELECT percentile_disc(0.5) WITHIN GROUP (ORDER BY value),
percentile_cont(0.5) WITHIN GROUP (ORDER BY value),
mode() WITHIN GROUP (ORDER BY value)
FROM measurements;
Each call accepts one or more ORDER BY expressions, including ASC, DESC,
NULLS FIRST, and NULLS LAST. Null order values are ignored; an input with no
non-null values returns NULL. percentile_disc returns an existing ordered
value, while percentile_cont interpolates numeric values and returns float8.
For a tied mode, the first value in the requested order wins.
The functions work with ordinary GROUP BY, GROUPING SETS, ROLLUP, and
CUBE, and can be mixed with normal aggregates in the same query. DISTINCT is supported on the
direct argument, for example percentile_disc(DISTINCT 0.5), and deduplicates
the first ORDER BY value before calculation. FILTER (WHERE ...) is applied
before deduplication and ordering. The implementation materializes
groups in memory and partitions groups into scratch files when they exceed
work_mem; a single group also uses the shared external sort. Scalar queries
follow the same path.
GROUPING SETS, ROLLUP, and CUBE
Amphi supports grouping sets in aggregate queries:
SELECT region, store, sum(amount)
FROM sales
GROUP BY ROLLUP (region, store);
The following forms are also supported:
GROUP BY GROUPING SETS ((region), (store), ())
GROUP BY CUBE (region, store)
GROUP BY ROLLUP (region), CUBE (store, channel)
ROLLUP produces detail groups, progressive subtotals, and the grand total.
CUBE produces every combination of the expressions. Expressions omitted from
a set are returned as NULL. HAVING, ORDER BY, and existing aggregates use
the normal aggregation path.
GROUPING() and GROUPING_ID() return an integer mask. The least significant
bit corresponds to the last argument; a 1 bit means that the expression was
omitted from the current grouping set. Multiple ROLLUP/CUBE components can
be combined in one clause. Hash aggregate spill remains available when group
cardinality exceeds work_mem. DISTINCT inside an aggregate combined with
grouping sets is rejected in this slice.
Table functions
Registered variants include:
generate_series(int4, int4 [, int4])
generate_series(int8, int8 [, int8])
generate_series(date, date [, interval])
Each variant returns a column named generate_series and rejects a zero step. The series is lazy:
LIMIT stops value production.
The simple single-column form in the SELECT list is also supported:
SELECT generate_series(1, 3);
To query a table directly, use TABLE name, equivalent to SELECT * FROM name.
For the temporal variant, months are applied first and the day is clamped to the last day of the
resulting month; days are applied afterwards. For example, date '2024-01-30' with
interval '1 month' produces 2024-02-29. The current implementation requires intervals used
with date to represent whole days; fractional hours, minutes, and seconds are not part of this
overload yet.
SELECT * FROM generate_series(date '2024-01-30', date '2024-05-01', interval '1 month');
Built-in extension functions
When the corresponding extension is enabled:
amphi-gis:st_point,st_x,st_y,st_distance,st_astext,st_equals,st_makebox,st_contains,st_intersects;amphi-fts:fts_vector,fts_match,fts_rank;amphi-audit:audit_event_count,audit_persisted_event_count.
See Extension development for extension types, capabilities, and the enablement process.
OpenAI extension (preview)
The amphi_openai extension calls the OpenAI Responses API through an explicit
SQL function. It is a Rust package integrated with the server. The call is
volatile, may incur external charges, and is not undone by ROLLBACK.
Configure the master key as a systemd credential (amphi-secret-key in
$CREDENTIALS_DIRECTORY) before creating secrets. This is the only supported
method; the key must contain 64 hexadecimal characters (32 bytes). The API key
is encrypted in the local secret store and must not be passed to the function.
CREATE SCHEMA openai;
CREATE EXTENSION amphi_openai WITH SCHEMA openai;
CREATE SECRET openai_api_key
TYPE TEXT
VALUE '...';
CREATE EXTERNAL CONNECTION openai_prod
PROVIDER openai
OPTIONS (api_key = SECRET openai_api_key);
The function accepts the connection name, model, system instructions, and user
input. It returns a document with id, model, text, and usage:
SELECT openai.complete(
'openai_prod',
'gpt-...',
'Answer in one sentence.',
'What is a B-tree?'
) AS response;
SELECT openai.complete(
'openai_prod', 'gpt-...', 'Answer in one sentence.', 'What is a B-tree?'
) ->> 'text' AS answer;
Each function evaluation makes an external request. Avoid calling it from a query that evaluates many rows: each row may create a billable API call. A global concurrency limit and batch function are not available yet.
The first cut uses https://api.openai.com/v1/responses, does not retry
automatically, and limits each prompt to 64 KiB and the response to 1 MiB. Rate
limits, authentication failures, timeouts, and protocol errors return SQL errors
without including the API key or remote response body. Requests follow the
OpenAI Responses API.
CREATE SECRET writes to encrypted storage outside the SQL transaction, so it
must run in autocommit and cannot be rolled back. The statement audit event
redacts its plaintext. Logical dumps include the extension installation and an
OpenAI connection that contains only SECRET references, but never the secret
store. Provision the same secret name and type on the target before running
amprestore; the restored connection then resolves it. Until external-connection
ACLs exist, only administrators can create or invoke an OpenAI connection.
Secret rotation and deletion, fine-grained authorization, batch calls,
streaming, tools, and embeddings are outside this preview.
Native arrays
Amphi supports one-dimensional, homogeneous, typed arrays. Elements may be bool, bytea,
int2, int4, int8, text, float8, uuid, or numeric.
Each element type has a corresponding array type identity in the catalog — for
example, int4 and int4[]. The array implementation is shared and
parameterized by the element type; the catalog distinction is required for
operator, cast, and protocol resolution. The catalog stores element-to-array
and array-to-element links, following PostgreSQL’s typelem/typarray model.
Construction and access
SELECT ARRAY[10, 20, NULL]::int4[];
SELECT (ARRAY[10, 20, 30])[2]; -- 20
SELECT (ARRAY[10, 20, 30, 40])[2:3]; -- {20, 30}
SELECT ARRAY[]::int4[]; -- typed empty array
Indexes are one-based. A NULL or out-of-range index returns NULL. Slices accept omitted
bounds and are clamped to the array size. ARRAY[] needs an explicit cast.
unnest, ANY, and ALL
unnest(array) returns one row per element and preserves NULL elements. Scalar operators can
compare against an array, for example 2 = ANY (ARRAY[1, 2, 3]). Empty ANY is false and
empty ALL is true; NULL elements follow SQL three-valued logic.
Arrays are also used as cycle paths by WITH RECURSIVE ... CYCLE. Multidimensional arrays and
types without a native codec are not currently supported.
WITH RECURSIVE
WITH RECURSIVE defines queries with an anchor term and a recursive term that consumes the
previous round’s frontier:
WITH RECURSIVE nums(n) AS (
VALUES (1)
UNION ALL
SELECT n + 1 FROM nums WHERE n < 3
)
SELECT n FROM nums ORDER BY n;
UNION ALL keeps every row. UNION removes already-seen keys and converges on cyclic graphs.
max_recursive_iterations limits recursive rounds; the default is 10000.
EXPLAIN ANALYZE reports iterations, duplicates, spills, and memory counters. CYCLE ... USING
produces a native array path. The current subset supports UNION [ALL], independent CTEs, and
initial mutual recursion support; window features are outside this subset.
Collections
Collections store schemaless documents using _id and doc. See CREATE COLLECTION
and DROP COLLECTION.
The document codec is available. The generic SQL path can insert and select _id and doc.
The Rust driver’s find command and SQL matches() use the same server-side matcher and the
documented MQL subset below, plus cursor skip and limit.
The Rust and Python clients send typed MQL collection requests over the same
connection used for SQL. The Python DB-API exposes connection.collection(name):
collection = conn.collection("events")
created = collection.insert_one({"name": "Ana", "score": 7})
found = collection.find_one({"name": "Ana"})
updated = collection.update_one({"name": "Ana"}, {"$inc": {"score": 1}})
deleted = collection.delete_one({"name": "Ana"})
find, find_one, insert_one, insert_many, replace_one, modifier
update_one, and delete_one use typed MQL requests. They share the DB-API
connection and explicit transaction with SQL. find accepts optional sort,
project, skip, and limit arguments. ampsql supports typed CRUD through
\\mql find|insert|replace|update|delete; cursor options and typed aggregation
are not available in that command yet.
This does not provide compatibility with clients that speak the MongoDB wire protocol.
Documents without _id receive a server-generated UUIDv7. The relational _id column is
canonical; object documents expose the same value in doc._id as a UUID string, including in
client results. A supplied _id must be a matching UUID or the write fails with SQLSTATE 22023.
ObjectId is not supported by this contract.
_id remains globally unique across the physical leaves of a partitioned collection,
including leaves created after the parent collection.
upsert_one is also available in the driver.
Modifier-style update_one supports $set, $unset, and integer $inc. The
client sends the filter and modifiers in a typed request; the server rechecks
the filter and applies the update to the selected row in the session’s normal
transaction and executor path. A replacement document passed to update_one
uses the replacement operation instead.
SQL can project a document path with dotted notation. The result remains of
type doc; a missing path becomes NULL and can be tested with IS NULL or
IS NOT NULL:
SELECT doc.profile.age
FROM events
WHERE doc.profile.age IS NOT NULL;
UPDATE can replace a value inside a document. Sibling fields are preserved,
and missing intermediate objects are created. If an existing intermediate
value is a scalar, array, or null, the statement fails with SQLSTATE 22023.
SQL NULL assigned to a path is stored as document null.
Collections can participate in regular SQL joins with tables. Reads in a statement share transaction visibility, including the current transaction’s uncommitted writes:
SELECT a.name, doc.kind
FROM accounts AS a
JOIN events AS e ON a.id = doc.account_id;
Other sessions do not see the current transaction’s uncommitted rows.
UPDATE events
SET doc.profile.age = 31
WHERE _id = '00000000-0000-0000-0000-000000000001'::uuid
RETURNING doc;
Each statement accepts one assignment to the doc column. The target must
start with the doc column; DEFAULT is not accepted for paths. Supported
scalar values include boolean, integers, float, numeric, text,
bytea, UUID, and other documents. numeric is converted to the document
floating-point number model and may lose precision; unsupported SQL types
return SQLSTATE 0A000.
To filter by document contents, use matches(doc, filter), which shares the MQL
subset supported by FIND:
SELECT _id, doc
FROM events
WHERE matches(doc, '{"age":{"$gte":18}}'::doc);
GIN indexes on documents
A collection can have a GIN index on doc to narrow candidates for content
searches with @>:
CREATE INDEX events_doc_gin ON events USING gin (doc);
SELECT _id
FROM events
WHERE doc @> '{"profile":{"city":"SP"}}'::doc;
The operator uses the same matcher as matches(doc, filter), and the complete
predicate is rechecked on candidate rows. The planner uses the index for
positive structural equality when every extracted term is required for a
match. Filters with logical or negative operators, equality with null, and
empty objects or arrays remain valid but use a sequential scan. EXPLAIN shows
IndexScan when GIN is selected.
The current subset includes equality, $eq, dotted paths, $gt, $gte, $lt, $lte,
$in, $all, $elemMatch, $size, $type, $mod, $regex, $not, $nin, $ne, $exists, $and,
$or, and $nor. $nor matches when none of the filters in its array match;
an empty list matches every document.
Unsupported operators, including $expr and $where, return SQLSTATE 22023.
$elemMatch applies a per-element filter to arrays of objects or scalars; one
element must satisfy every condition. Object elements use a document filter;
scalar elements accept an object made only of operators. $all requires a
nonempty array of values and matches only when the field is an array containing
every expected value as a direct element; nested objects and arrays use equality.
A $size predicate matches an array only when its length equals the given
non-negative integer. Negative and non-integer sizes are malformed predicates.
A $not predicate negates a non-empty field-operator object. It includes
missing fields when the inner predicate does not match, and malformed inner
operators still return an error.
$type accepts one of null, bool, int, float, text, bytea, uuid,
array, or object. For arrays, array checks the value itself; other names
match when a direct element has that type. Unsupported names and non-text
arguments are errors.
$eq makes the same structural comparison as a direct value and also matches
a scalar contained in an array field.
$mod accepts [divisor, remainder] with two integers and a nonzero divisor.
Only integer document values participate; for arrays, one matching integer
element is enough. Remainder follows the dividend’s sign, and invalid division
arguments are errors.
$regex accepts a pattern in the Rust regex crate syntax and tests scalar
text or direct text elements in an array. $options accepts i (case
insensitive), m (line anchors), s (. matches newlines), and x (ignore
pattern whitespace and comments). $options requires $regex; PCRE syntax
unsupported by the crate is outside this contract. Invalid patterns, patterns
larger than 16 KiB, or patterns compiling to more than 1 MiB are errors.
Equality with JSON null (direct, $eq: null, or $in: [null]) matches both
null values and missing paths. $ne: null matches only existing non-null
values; $nin also matches missing paths. Use $exists to test presence
independently of value. MQL relational comparisons
compare each array element with the expected scalar and match if any element
satisfies the operator; different types do not match. Lexicographic array
comparisons are outside this subset. SQL relational comparisons accept document
paths and scalar SQL values on either side, for example
doc.profile.age >= 18 or 30 = doc.profile.age. Comparisons preserve document
types: SQL integers compare with document integers, float/numeric values with
document floats, text with text, and so on. Different document types do not
match (=, <>, <, <=, >, and >= return false). A missing path is SQL
NULL, so its comparison is NULL; JSON null is a document value, not SQL
NULL. SQL types that cannot yet be represented in doc do not receive an
implicit conversion.
CREATE COLLECTION
Creates a document collection with _id and doc fields.
CREATE COLLECTION events;
CREATE COLLECTION IF NOT EXISTS events;
Collections use the document codec and receive server-generated UUIDv7 identifiers when an inserted document does not provide _id. Use DROP COLLECTION to delete a collection.
DROP COLLECTION
Work queues
Queues use at-least-once delivery: a received message remains leased until it is acknowledged,
returned, or expires. CREATE QUEUE, SEND, RECEIVE, ACK, NACK, EXTEND, and
queue inspection commands are documented separately.
CREATE QUEUE
DROP QUEUE
SEND
RECEIVE
ACK
NACK
EXTEND
PURGE QUEUE
QUEUE STATS
Displays operational queue metrics.
QUEUE STATS jobs;
The result contains depth (available messages), leased (messages under lease), dead_letters,
and next_wakeup (the next logical visibility change).
QUEUE DLQ
Lists messages that exceeded their retry limit and were moved to the dead-letter queue.
QUEUE DLQ jobs;
The result contains msg_id, payload, attempts, reason, and failed_at.
In-memory tables
In-memory tables are key-value structures bounded by a reservation. The initial command set includes PUT, GET, DEL, EXISTS, EXPIRE, TTL, PERSIST, and INCR.
Each command is atomic and does not participate in SQL transactions. Volatile data is lost on restart; snapshot data is saved in checkpoints.
CREATE MEMORY TABLE
DROP MEMORY TABLE
PUT
GET
DEL
EXISTS
EXPIRE
TTL
PERSIST
INCR
Command-line applications
The amphi binary provides subcommands. Its argument parser is dependency-free, so the grammar is simple: subcommand, positional arguments, and –flag [value].
| Command | Purpose |
|---|---|
| amphi init | creates a data directory |
| amphi inspect | decodes pages, WAL, and control files; verifies integrity |
| amphi version | prints the version |
Exit codes are 0 for success, 1 for inspected-data problems, and 2 for usage or tool errors.
amphi init
Creates a new data directory.
Synopsis
amphi init <dir> [--page-size 8k] [--set name=value]...
[--wal-segment-bytes <n>] [--segment-bytes <n>] [--extent-bytes <n>]
[--tls-self-signed]
Description
Creates the selected data directory with a control file, base, global, wal, and tmp directories, plus the generated amphi.conf. Invalid arguments produce usage exit code 2.
Options
–page-size <4k|8k|16k|32k|64k> sets the page size; the default is 8k and it cannot be changed later. –wal-segment-bytes, –segment-bytes, and –extent-bytes set immutable layout values. Repeat –set name=value to add bootstrap settings.
–tls-self-signed creates development certificates under tls/ and sets tls_mode = required. Do not use these certificates in production.
$ amphi init /var/lib/amphi --page-size 16k --set name=value
amphi inspect
Inspects a data directory without starting the server.
Synopsis
amphi inspect control <dir>
amphi inspect verify <dir>
amphi inspect wal <dir>
amphi inspect file <path>
amphi inspect page <path> <block> [--hex]
The control subcommand prints the cluster format and shutdown state. Verify checks page checksums. Wal prints records, file lists page summaries, and page decodes one page. All subcommands support JSON output where noted by the command help.
amphi version
Synopsis
amphi version
Prints the binary version.
Extension development
Amphi extensions register capabilities, types, functions, hooks, and optional storage adapters through an extension manifest. Keep registration, runtime hooks, and event delivery as separate concerns so each can be tested independently.
The built-in extensions are amphi-gis, amphi-fts, amphi-audit, and amphi-openai. Enable an extension explicitly and verify its catalog entries before using its SQL functions.
Extension code must validate input, avoid leaking secrets in errors, and preserve deterministic behavior in tests. See the individual pages for audit, full-text, GIS, and hook APIs. The OpenAI extension preview documents the external API function and its administrator-only connection restriction.
Procedural languages
Each language extension must keep its lexer, parser, checker, compiler, runtime, and adapters inside
its own package. The core provides only the generic LanguageHandler contract and SQL,
transaction, cancellation, and notice services. A Rust provider can register its handler with
ExtensionProvider::with_language_loader and be passed through EngineOptions::extension_providers
before opening the engine. This enables CREATE FUNCTION and DO blocks and lets the engine
recompile persisted functions at startup, restore, and restart. CREATE EXTENSION installs catalog
metadata; the embedding application must still ship and register the provider. The contract is an
in-process Rust API, not yet an ABI for binary plugins or languages implemented in other
programming languages. See the
procedural language host contract.
Hooks and events
Hooks are lifecycle callbacks used by extensions and observability integrations. Keep hooks short, deterministic, and failure-aware; a diagnostic hook must not change transaction results.
Separate the event registry from hook dispatch and from extension capability discovery. This keeps startup validation and runtime failure handling independently testable.
Procedural language handlers
amphi_ext::LanguageHandler dispatches persistent scalar functions through compile_scalar and
anonymous blocks such as DO through compile_inline. The language package owns parsing,
checking, compilation, and runtime. The host supplies generic SQL, transaction/savepoint,
cancellation, and notice services through LanguageInlineHost. The embedding application
registers the native provider through EngineOptions::extension_providers; CREATE EXTENSION
records installation in the catalog but does not load a package dynamically. See the
procedural language host contract.
Arrays of extension types use the shared generic ArrayOps implementation, but receive their
own OID and an explicit element-to-array relation in the catalog. The extension registry must
provide that OID; the core does not derive it from the type name.
amphi-gis
amphi-gis provides point and box values plus spatial inspection and predicates. Functions include st_point, st_x, st_y, st_distance, st_astext, st_equals, st_makebox, st_contains, and st_intersects.
Validate coordinate order and units at the application boundary. Spatial extension behavior is available only after the extension is enabled.
amphi-fts
amphi-fts provides full-text vector construction, matching, and ranking. Its SQL functions are fts_vector, fts_match, and fts_rank.
Treat indexed text as derived data. Rebuild or refresh the index when source rows change, and measure query latency with the same tokenizer and corpus used in production.
amphi-audit
amphi-audit records structured audit events emitted by the engine and extensions. Events should identify the actor, operation, object, outcome, and timestamp without storing credentials or unnecessary payload data.
The extension exposes audit_event_count and audit_persisted_event_count for operational checks. Use these functions to verify registration and persistence in an isolated test database.
Pages, tuples, and column storage
This page describes the physical format Amphi uses to store pages, tuples, and row values. The format is documented to make storage costs and wide-table limits transparent; applications do not need to construct these bytes manually.
Heap page
A heap page uses a slotted-page layout:
+----------------+------------------+----------------+-------------------+
| page header | line pointers | free space | tuples |
| 32 bytes | 4 bytes each | | |
+----------------+------------------+----------------+-------------------+
0 lower upper page size
The page header is 32 bytes. Each line pointer is 4 bytes and identifies a tuple by a stable slot. A tuple can move during compaction without changing that slot. Tuples are aligned to 8-byte units.
Tuple and row body
Each tuple has a 32-byte physical header followed by the encoded row body:
+-------------------+----------------------+
| tuple header | row body |
| 32 bytes | RowCodec |
+-------------------+----------------------+
The row body is:
[n_columns u16]
[null bitmap]
[optional external bitmap]
[fixed region]
[variable offsets]
[variable region]
The column count uses 2 bytes. The null bitmap uses 1 bit per column. Variable columns have one 2-byte offset containing the end of their value in the variable region. Fixed-width columns are packed separately in schema order.
For example, with id int4, name varchar(5), and code char(5), values 7,
'AB', and 'X' are conceptually encoded as:
+----------+------+------------+----------------+----------------------+
| columns | null | fixed | var offsets | variable region |
+----------+------+------------+----------------+----------------------+
| 03 00 | 00 | id = 7 | 02 00 06 00 | A B X _ _ _ |
+----------+------+------------+----------------+----------------------+
The offsets are ends, not (start, length) pairs:
name: starts at 0 and ends at 2
code: starts at 2 and ends at 6
var offsets = [2, 6]
var region = "ABX "
The null bitmap distinguishes NULL from an empty string, whose start and end
offsets can be equal.
varchar(n) and char(n)
Both types use the variable-width text storage format. There is no additional
per-value length byte for varchar(n) or char(n); the physical length comes
from the variable-region offsets.
The semantic limit is stored in the column catalog metadata:
varchar without a limit : type_mod = -1
varchar(5) : type_mod = 5
char(5) : type_mod = -6
varchar(n) rejects values longer than n. char(n) pads shorter values with
spaces and rejects values longer than n. Text is stored as UTF-8: validation
counts Unicode characters, while offsets count physical bytes.
Column limit and overhead
The current structural limit is 32,767 columns per table. The column counter is
a u16, but its top bit is reserved to indicate the presence of the external
bitmap.
The control overhead is:
fixed column : 1 null-bitmap bit + fixed value bytes
variable column : 1 null-bitmap bit + 2-byte offset + value bytes
For example, 100 variable columns use 13 null-bitmap bytes and 200 offset bytes, in addition to the 2-byte counter and the values. Wide rows can hit tuple or page size limits before reaching the structural column-count limit.
Physical catalog and sys.* relations
Amphi has two metadata layers: persisted physical sys.* tables and the public
read-only sys.catalog_* views. The physical tables are useful for diagnostics
and engine development; new applications should use the public views.
Persisted physical relations
Physical catalog relations use fixed OIDs. Their storage-order schemas are:
1 schema: (oid int4, name text)
2 relation: (oid int4, storage_oid int4, schema int4, name text, kind int2,
engine int2, toast_rel int4, options bytea, comment text)
3 attribute: (rel int4, attno int2, name text, type int4, type_mod int4,
not_null bool, dropped bool, comment text)
4 type: (oid int4, name text, len int2, schema int4, element_type int4, array_type int4)
5 function: (oid int4, name text, arg_types bytea, ret_type int4, native int4,
aggregate bool, volatility int2, schema int4, security_definer bool)
6 operator: (oid int4, name text, left int4, right int4, ret_type int4,
func int4, commutator int4, negator int4)
7 opclass: (oid int4, name text, am int2, type int4, is_default bool, compare int4)
8 opclass_operator: (opclass int4, strategy int2, operator int4)
9 cast: (source int4, target int4, func int4, context int2)
10 index: (index_rel int4, table_rel int4, am int2, unique bool, columns bytea, valid bool)
11 collection_dict: (rel int4, key_id int4, key text)
13 view_def: (rel int4, query text)
18 attr_def: (rel int4, attno int2, sequence int4)
19 sequence: (rel int4, high int8, start int8, increment int8, min int8, max int8, cycle bool, cache int8)
20 role: (oid int4, name text, can_login bool, enabled bool, is_admin bool,
can_create_db bool, can_create_role bool, inherit bool, valid_until int8)
21 group: (oid int4, name text)
22 group_member: (group int4, member int4)
23 role_credential: (role int4, salt bytea, iterations int4, stored_key bytea, server_key bytea)
24 access_policy: (oid int4, name text, priority int4, subject_kind int2, subject int4,
source text, database text, allow bool, rate_per_second int4, burst int4)
27 check_constraint: (oid int4, relation int4, name text, expression text)
28 foreign_key: (oid int4, relation int4, name text, columns bytea,
referenced_relation int4, referenced_columns bytea, on_delete int2, on_update int2,
deferrable bool, initially_deferred bool)
40 foreign_server: (name text, connection text, options bytea)
41 foreign_table: (relation int4, server text, options bytea)
46 column_default: (rel int4, attno int2, expression text)
47 column_missing: (rel int4, attno int2, expression text)
48 acl: (relation int4, grantee_kind int2, grantee int4, grantor int4, privilege int2,
scope_kind int2, columns bytea, grant_option bool)
50 default_acl: (owner int4, object_kind int2, grantee_kind int2, grantee int4,
privilege int2, scope_kind int2, columns bytea, grant_option bool)
74 object_comment: (object_oid int4, object_kind text, comment text)
76 named_object_identity: (object_oid int4, object_kind text, object_name text)
12 meta: (catalog_version int4, ddl_seq int8, next_oid int4)
14 stat_user_tables: (relid int4, schema text, name text, n_tup_ins int8,
n_tup_upd int8, n_tup_del int8, n_live_tup int8, n_dead_tup int8,
last_vacuum int8, last_analyze int8)
17 stat_column: (relid int4, attno int4, null_frac float8, n_distinct int8,
correlation float8, mcv text, histogram text)
36 schedule, 37 schedule_run, 45 external_connection, 52 trigger,
54 partition, 59 system_alarm, 60 domain, 61 partition_policy,
65 tablespace, 68 stat_progress, 69 object_revision, 70 prepared_transactions,
72 extension (name text, schema int4, version text)
stat_activity and blocking_tree are virtual process relations and have no
persistent heap.
Typmods, codes, and runtime OIDs
sys.attribute.type_mod currently uses -1 for no modifier, a positive value
for varchar(n), and -(n + 1) for char(n). Packed bytea columns contain
catalog position lists and numeric codes must be translated by the catalog layer.
Runtime-only relations use a separate range:
100 available_extensions
101 extension_lifecycle
102 extension_metrics
103 languages
They must never reuse a persisted sys.* OID. A collision can make a physical
relation be decoded with the wrong RowCodec schema.
Public contract
Use sys.catalog_schemas, sys.catalog_objects, sys.catalog_columns,
sys.catalog_indexes, sys.catalog_types, sys.catalog_functions,
sys.catalog_checks, sys.catalog_foreign_keys, sys.catalog_roles,
sys.catalog_groups, sys.catalog_group_members, sys.catalog_acls,
sys.catalog_default_acls, sys.catalog_domains, and
sys.catalog_partitions from applications and tools. Their columns and examples
are documented in System views.
Changing a physical catalog column, type, or position requires incrementing
CATALOG_VERSION and adding an explicit migration. Persistent OIDs must not be
reused, and an OID must not be confused with the array position in the source
definition.
Object metadata and tags
Tags are searchable catalog metadata, stored by stable object identity and
exposed through sys.catalog_object_tags. Do not add a variable tag list to
sys.catalog_objects. Supported objects must allow tags to be created, changed,
removed, queried in filters/joins, and viewed in the Web Console. Comments remain
free-form text with separate semantics.
Rule for new object types: when adding a persistent object type with a catalog identity, include it in the tagging contract (SQL, catalog/view, queries, permissions, dump/restore, and Console), or document why tagging does not apply. Do not consider a type complete until this decision is recorded. Internal objects without an administrable identity may be excluded, with the exclusion documented.
See Object tags for the initial inventory and current coverage.
Implementation status
This documentation describes implemented behavior and marks incomplete surfaces explicitly.
Implemented foundations include the data-directory format, inspection commands, catalog-backed DDL, relational query execution, arrays, recursive CTEs, built-in functions, document collections, queues, memory tables, and extension registration.
The server and full production authentication story are still evolving. Features described as planned are not stable compatibility commitments. Check the command-specific page and the current test suite before depending on an experimental feature.
Schedules are implemented in the catalog and can execute SQL actions through the integrated
scheduler. Manual RUN NOW currently records a claimed manual run but does not yet submit the
action to a worker. The current single-relation ampdump does not include schedule definitions or
run history.
Exit codes and SQLSTATE
Command line
| Code | Meaning |
|---|---|
| 0 | success; verification and page inspection found no issue |
| 1 | inspected data has a problem, such as corruption or a failed check |
| 2 | usage error, unreadable path, or tool failure |
SQLSTATE
See the SQLSTATE reference for the codes currently emitted by the engine.
SQLSTATE reference
Amphi returns a five-character SQLSTATE with every server error. Clients should branch on the code, not on localized message text. The list below covers the codes currently emitted by the parser, binder, planner, executor, session, lock manager, and wire protocol.
Syntax and statement structure
| SQLSTATE | Condition | Typical source |
|---|---|---|
42601 | syntax error | invalid SQL or lexical input |
54000 | program limit exceeded | oversized value, work memory, or recursive limit |
54001 | statement too complex | excessive parser nesting |
0A000 | feature not supported | valid syntax outside the implemented surface |
Names, objects, and types
| SQLSTATE | Condition |
|---|---|
3F000 | invalid schema name |
42P01 | undefined table or relation |
42P02 | undefined parameter |
42701 | duplicate column |
42702 | ambiguous column |
42703 | undefined column |
42704 | undefined object |
42710 | duplicate object |
42712 | duplicate alias |
42725 | ambiguous function |
42803 | grouping error |
42804 | datatype mismatch |
42809 | wrong object type |
42846 | cannot coerce |
42883 | undefined function |
42P06 | duplicate schema |
42P07 | duplicate table or relation |
42P10 | invalid column reference |
42P16 | invalid table definition |
42P18 | indeterminate datatype |
42939 | reserved name |
2BP01 | dependent objects still exist |
Data and constraint errors
| SQLSTATE | Condition |
|---|---|
22003 | numeric value out of range or arithmetic overflow |
22012 | division by zero |
2201W | invalid LIKE pattern escape |
22P02 | invalid text or binary representation |
23502 | not-null violation |
23505 | unique violation |
23514 | check violation |
42804 | datatype mismatch |
Concurrency, resources, and cancellation
| SQLSTATE | Condition |
|---|---|
25P02 | current transaction is aborted |
25P04 | transaction timeout |
40001 | serialization failure or concurrent update |
40P01 | deadlock detected |
53200 | out of shared memory, including row-lock capacity |
53100 | disk full |
55P03 | lock not available or lock timeout |
57014 | query or statement canceled |
Internal and protocol errors
| SQLSTATE | Condition |
|---|---|
08P01 | protocol violation |
08006 | connection failure |
XX000 | internal error, corruption, or unexpected I/O failure |
SQLSTATEs are also included in protocol ErrorResponse messages, client errors, logs, and test fixtures. New error paths must choose an existing compatible code or add a documented code before they are exposed to clients.
Glossary
| Term | Meaning |
|---|---|
| catalog | Metadata relations describing schemas, objects, columns, and functions |
| heap | The persistent row-store engine |
| lease | Temporary ownership of a queue message after RECEIVE |
| WAL | Write-ahead log used to record durable changes |
| worktable | Intermediate relation used by a recursive query |
| UUIDv7 | Time-ordered UUID format used for generated document identifiers |
| SQLSTATE | Five-character code identifying a SQL error class |