PostgreSQL front-end

Statements and catalogs

The PostgreSQL statements, functions and catalogs that are translated, with how.

Statements#

DDL. CREATE TABLE [IF NOT EXISTS] with PRIMARY KEY, UNIQUE, NOT NULL, DEFAULT, CHECK, REFERENCES .. ON DELETE | UPDATE NO ACTION | RESTRICT | CASCADE | SET NULL, named and unnamed constraints (PostgreSQL's names: t_pkey, t_a_key, t_a_fkey, t_a_check), CREATE TEMP TABLE, CREATE TABLE AS; ALTER TABLE ADD COLUMN, DROP COLUMN, ADD | DROP CONSTRAINT, RENAME TO, RENAME COLUMN, ALTER COLUMN TYPE | SET | DROP DEFAULT | SET | DROP NOT NULL; DROP TABLE | VIEW | SEQUENCE | INDEX | SCHEMA | DATABASE | ROLE [IF EXISTS] [CASCADE] with PostgreSQL's 2BP01 message, detail and hint and the drop cascades to notices; CREATE [UNIQUE] INDEX [IF NOT EXISTS] (btree, DESC), CREATE SEQUENCE (START, INCREMENT, MINVALUE, MAXVALUE, CYCLE), ALTER SEQUENCE RESTART, nextval, currval, lastval, setval; CREATE [OR REPLACE] VIEW (a view's columns cannot be dropped as PostgreSQL); CREATE SCHEMA, CREATE DATABASE, TRUNCATE.

Queries. SELECT [DISTINCT | DISTINCT ON (..)], joins INNER, LEFT, RIGHT, FULL (as a derived table of the left join and the unmatched right rows), CROSS, NATURAL, USING, derived tables, VALUES, WITH and WITH RECURSIVE, UNION [ALL], INTERSECT, EXCEPT, GROUP BY (names and positions), HAVING, ORDER BY (names, positions, NULLS FIRST | LAST; PostgreSQL's null order; text by bytes), LIMIT, OFFSET, FETCH FIRST n ROWS ONLY, subqueries (scalar, IN, EXISTS, ANY, ALL), window functions with OVER and WINDOW, FILTER (WHERE ..), generate_series in FROM, FOR UPDATE (read and ignored), ARRAY(subquery) and = ANY(ARRAY[..]) / IN lists.

Expressions and functions. Operators + - * / % ^ || = <> < > <= >= AND OR NOT IS [NOT] NULL | TRUE | FALSE | DISTINCT FROM, BETWEEN, IN, [I]LIKE .. ESCAPE, SIMILAR TO with a literal pattern, ~ ~* !~ !~*, & | # << >>, :: and CAST, CASE, COALESCE, NULLIF, GREATEST, LEAST, JSON -> ->> #> #>> @> <@ ?, date arithmetic with interval '..' literals, string functions (length, upper, lower, substr, substring .. from .. for, position, strpos, replace, trim, btrim, ltrim, rtrim, lpad, rpad, left, right, repeat, reverse, concat, concat_ws, split_part, starts_with, md5, ascii, chr, regexp_replace), math (abs, ceil, floor, round, trunc, mod, div, power, sqrt, sign, exp, ln, log, random, trigonometry), date and time (now, current_date, current_timestamp, extract, date_part, date_trunc, to_char, to_date, to_timestamp, make_date, age), aggregates (count, sum, avg, min, max, string_agg, array_agg (as text {a,b}), bool_and, bool_or, stddev, variance), window functions (row_number, rank, dense_rank, ntile, lag, lead, first_value, last_value, nth_value), pg_typeof, current_database, current_user, current_schema, version, current_setting, gen_random_uuid, jsonb_typeof, jsonb_array_length.

DML. INSERT .. VALUES | SELECT | DEFAULT VALUES, ON CONFLICT [(cols)] DO NOTHING | DO UPDATE SET .. [WHERE ..] (with EXCLUDED; engine ON DUPLICATE KEY UPDATE), RETURNING, UPDATE .. SET .. [FROM ..] [WHERE ..] [RETURNING ..], DELETE FROM .. [USING ..] [WHERE ..] [RETURNING ..], COPY. A string literal is read as the type of the column or operator it meets, with PostgreSQL's errors: malformed input for type integer: "abc" (22P02), value does not fit in type character varying(5) (22001), column "x" has type integer, yet the expression has type text (42804), no such operator: integer + text (42883).

Transactions. BEGIN / START TRANSACTION, COMMIT, END, ROLLBACK, ABORT, SAVEPOINT, RELEASE, ROLLBACK TO; after an error the transaction is failed and every statement but ROLLBACK / COMMIT / ROLLBACK TO is 25P02 the transaction has failed; commands are skipped until the transaction block ends (COMMIT of a failed transaction answers ROLLBACK).

Session. SET [SESSION | LOCAL] name {TO | =} value, SET TIME ZONE, RESET, SHOW for server_version, server_encoding, client_encoding, DateStyle, TimeZone, standard_conforming_strings, integer_datetimes, max_identifier_length, transaction_isolation, search_path, application_name, extra_float_digits and others (SHOW ALL lists them), ParameterStatus for the ones PostgreSQL reports, DISCARD, VACUUM, ANALYZE, LISTEN, UNLISTEN, NOTIFY (accepted, nothing is delivered), CHECKPOINT, COMMENT ON, LOCK, REINDEX (accepted, no effect), EXPLAIN [ANALYZE] (a plausible plan, see below).

Roles and privileges (D110.1). CREATE | ALTER | DROP ROLE | USER with LOGIN, SUPERUSER, CREATEDB, CREATEROLE, INHERIT, PASSWORD, IN ROLE, ROLE, ADMIN (a password is stored as a SCRAM-SHA-256 verifier, as PostgreSQL does; the role logs in with scram-sha-256 and password, md5 cannot be checked against a verifier, as in PostgreSQL), with PostgreSQL 16's rules for who may create, alter and drop roles and their DETAIL lines. Privileges are enforced by the front-end (not by engine accounts: D110.1 gives the reason): the owner and superusers can do everything; GRANT | REVOKE of SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER on tables and views, USAGE, SELECT, UPDATE on sequences, USAGE, CREATE on schemas, CONNECT, CREATE, TEMPORARY on databases, ALL, ON ALL TABLES | SEQUENCES IN SCHEMA, TO PUBLIC | CURRENT_USER, WITH GRANT OPTION, REVOKE GRANT OPTION FOR, with PostgreSQL's warnings; GRANT role TO role [WITH ADMIN OPTION | INHERIT x | SET x] with inheritance (NOINHERIT roles); ALTER DEFAULT PRIVILEGES [FOR ROLE r] [IN SCHEMA s] .. ON TABLES | SEQUENCES; ALTER TABLE | VIEW | SEQUENCE | SCHEMA | DATABASE .. OWNER TO; SET ROLE, RESET ROLE, SET SESSION AUTHORIZATION, SESSION_USER, CURRENT_USER, CURRENT_ROLE, SHOW ROLE; has_table_privilege, has_sequence_privilege, has_schema_privilege, has_database_privilege, pg_has_role with literal names. Denied statements are 42501 access to table t is denied (also view, sequence, schema, database), must be owner of table t, this user may not create roles and the like, before anything runs. DROP ROLE of a role that owns objects is 2BP01 with the list.

COPY (D110.2). COPY t [(cols)] FROM STDIN | TO STDOUT and COPY (query) TO STDOUT in text, csv and binary format with DELIMITER, NULL, HEADER [MATCH], QUOTE, ESCAPE, FORCE_QUOTE, FORCE_NOT_NULL, both syntaxes of the options; psql \copy works; COPY FROM is atomic and its errors carry PostgreSQL's CONTEXT: COPY t, line n, column c: "v".

Functions, procedures, DO, CALL and triggers (D110.3). CREATE [OR REPLACE] FUNCTION | PROCEDURE with LANGUAGE plpgsql | sql, IN | OUT | INOUT | VARIADIC arguments with defaults, RETURNS type | SETOF type | TABLE (..) | void | trigger, STRICT; DROP FUNCTION | PROCEDURE [IF EXISTS] f[(types)]; calls in SELECT, FROM, WHERE, INSERT .. VALUES, in other functions, with named notation; CALL; DO. PL/pgSQL: DECLARE (%TYPE, %ROWTYPE, record), assignment, IF, CASE, LOOP, WHILE, FOR over integers and queries, labels, EXIT/CONTINUE, RETURN, RETURN NEXT, RETURN QUERY, PERFORM, SELECT INTO [STRICT], EXECUTE .. INTO .. USING, GET [STACKED] DIAGNOSTICS, FOUND, ASSERT, RAISE at every level with USING fields, BEGIN .. EXCEPTION WHEN .. END with conditions and SQLSTATE, SQLERRM; errors with PostgreSQL's QUERY: and CONTEXT: lines. CREATE [OR REPLACE] TRIGGER .. BEFORE | AFTER INSERT | UPDATE | DELETE [OR ..] ON t FOR EACH ROW [WHEN (..)] EXECUTE FUNCTION f(args) and DROP TRIGGER: NEW, OLD, TG_OP, TG_WHEN, TG_LEVEL, TG_TABLE_NAME, TG_NAME, TG_NARGS, assignments to NEW, IF/CASE/WHILE, RAISE EXCEPTION, INSERT/UPDATE/DELETE in the body (the trigger function is translated into the engine's trigger).

Text search (D137). to_tsvector('simple', col) @@ to_tsquery('simple', 'a & !b <-> c:*') (also plainto_tsquery, phraseto_tsquery, and tsquery @@ tsvector) works in WHERE, the select list and FILTER-style conditions, with PostgreSQL's query grammar (! > <-> / <N> > & > |, quotes, :*, weights) and errors (syntax error in tsquery, no operand in tsquery). CREATE INDEX name ON t USING gin (to_tsvector('simple', col)) makes Raft DB's full-text index of the column and @@ over it looks the words up there (DROP INDEX drops it); the answers are those of the evaluator either way. The comparison script (2,152 lines: 43 query shapes before and with the index, writes under the index, ten syntax errors, 300 random texts with 60 random queries) is identical to PostgreSQL 18 (locale C). What is not copied: PostgreSQL's default parser knows hosts, e-mail addresses, URLs, paths, signed and decimal numbers, tags, entities and hyphenated words; this server reads a text only if it consists of ASCII letters and digits, space, tab, newline, , ; ! ? ( ) " ' : _ @ # $ % ^ * = [ ] { } | \ > and the backquote, and & or < before a blank, and refuses any other character (. - + / ~, < or & before a letter, non-ASCII letters, control characters) with 0A000, because it would otherwise have to guess. Also refused (0A000): ts_rank, ts_rank_cd (PostgreSQL's value depends on weights, positions and normalisation flags and is not reproduced; a different number would break the rule of identical results), ts_headline, setweight, websearch_to_tsquery, ts_stat, ts_debug, other text search configurations and the one-argument forms (the default configuration), a query that is not a constant, a phrase with an & or ! operand, an empty query, tsvector / tsquery columns, casts and output (the two exist only as operands of @@), other GIN indexes (arrays, jsonb, several columns, UNIQUE, partial) and the gist method. A refused text is refused only when it is read: with a GIN index a row the index does not select is not read. \d shows the GIN index as an ordinary index.

Arrays (D112.1). int[], text[], numeric(p,s)[], boolean[] and the other element types (two dimensions), ARRAY[..], ARRAY(subquery), '{1,2}' literals (read as PostgreSQL reads them, with its errors), array_agg, subscripts and slices, UPDATE .. SET a[i] = x, = ANY(arr) and the other quantified operators, unnest (also WITH ORDINALITY), array_length, cardinality, array_ndims, array_dims, array_lower, array_upper, array_append, array_prepend, array_cat, ||, array_position(s), array_remove, array_replace, array_reverse, array_fill, array_to_string, string_to_array, @>, <@, &&, casts, arrays as parameters and in the binary protocol.

More queries (D112.4). FETCH FIRST n ROWS WITH TIES, GROUP BY ROLLUP | CUBE | GROUPING SETS and grouping(), percentile_cont / percentile_disc WITHIN GROUP (constant fractions), FILTER, DISTINCT ON, FOR UPDATE | SHARE (accepted), generated columns GENERATED ALWAYS AS (expr) STORED, DEFAULT in VALUES, MERGE (PostgreSQL 15 form, a target with a primary key), LATERAL before a function, generate_series with bounds from other tables.

LISTEN / NOTIFY (D112.3), cursors and materialized views (D112.5), PREPARE / EXECUTE. Notifications between the sessions of one raftdb-pg process, delivered before ReadyForQuery and, on a connection in clear, to an idle listener within 100 ms; pg_notify with constant arguments. DECLARE (SCROLL, NO SCROLL, WITH HOLD), FETCH and MOVE in every direction, CLOSE. CREATE, REFRESH and DROP MATERIALIZED VIEW. PREPARE name (types) AS .., EXECUTE name (constants), DEALLOCATE. COMMENT ON for tables, columns, views, sequences, indexes, schemas, functions, constraints, triggers and databases.

pg_dump (D112.2). pg_dump 18 (plain, --schema-only, --data-only, -Fc), pg_restore and pg_dumpall --globals-only work against raftdb-pg; every table of PostgreSQL 18's pg_catalog exists with its columns (empty where this front-end keeps no data), and pg_depend, pg_proc, pg_trigger, pg_sequence, pg_description, pg_rewrite, pg_language, pg_extension (plpgsql) have rows.

Catalogs. pg_catalog: pg_class, pg_namespace, pg_attribute, pg_attrdef, pg_type, pg_index, pg_constraint (including PostgreSQL 18's NOT NULL constraints), pg_database, pg_roles, pg_authid, pg_user, pg_auth_members, pg_settings, pg_am, pg_tables, pg_views, pg_indexes, pg_sequences, the statistics views pg_stat_activity, pg_stat_user_tables, pg_stat_user_indexes, pg_statio_*, pg_stat_database, pg_stat_bgwriter, pg_stat_checkpointer, pg_locks and others (PostgreSQL's columns and rows; the counters are 0), pg_tablespace, pg_proc, pg_trigger, pg_sequence, pg_depend, pg_description, pg_rewrite, pg_language, pg_extension, pg_matviews, and every other table of PostgreSQL 18's pg_catalog empty; information_schema: tables, columns, schemata, table_constraints, key_column_usage, referential_constraints, views, sequences, column_privileges. Functions the clients call: format_type, pg_get_constraintdef, pg_get_indexdef, pg_get_viewdef, pg_get_expr, pg_get_userbyid, pg_table_is_visible, pg_encoding_to_char, current_schemas, to_regclass, pg_get_function_arguments, pg_get_function_result, pg_get_functiondef, pg_get_triggerdef, obj_description, col_description, quote_ident, quote_literal, information_schema._pg_expandarray, x::regclass, ::regtype, ::regnamespace, OPERATOR(pg_catalog.~). Object identifiers are made from the name (the same in every session and run). What psql does for \d table, \dt, \dv, \ds, \di, \dn, \l, \du and what pgjdbc does for DatabaseMetaData is identical to PostgreSQL's.

User-defined types, LATERAL, updatable views, triggers, indexes (stage 5b)#

Domains. CREATE DOMAIN name AS type [DEFAULT ..] [NOT NULL] [[CONSTRAINT c] CHECK (..)], ALTER DOMAIN (SET | DROP DEFAULT, SET | DROP NOT NULL, ADD | DROP | RENAME CONSTRAINT, RENAME TO), DROP DOMAIN [IF EXISTS] .. [CASCADE]. The constraints are checked on every assignment and cast with PostgreSQL's errors (23514, 23502).

Enums. CREATE TYPE name AS ENUM (..), ALTER TYPE .. ADD VALUE [IF NOT EXISTS] 'x' [BEFORE | AFTER 'y'], RENAME VALUE, RENAME TO, DROP TYPE; comparison and ordering in the order of the labels; enum_range, enum_first, enum_last; arrays of an enum.

Composite types. CREATE TYPE name AS (field type, ..), columns of the type, ROW(a, b)::t, record literals '(1,"a b",)', (value).field, (value).*. Field types: the built-in scalar types and their arrays.

time with time zone. Input and output with offsets, comparison as PostgreSQL (by the UTC time, then the offset), casts, extract, AT TIME ZONE, + interval.

LATERAL (subquery). FROM a, LATERAL (SELECT .. WHERE x = a.id ..) s, CROSS JOIN LATERAL, LEFT JOIN LATERAL .. ON true; the subquery is run again for each row of the items before it.

Updatable views. INSERT, UPDATE and DELETE (with RETURNING) through a view of one table or of one such view; WITH [CASCADED | LOCAL] CHECK OPTION. A view PostgreSQL does not update automatically is refused with its message and hint.

Triggers. BEFORE | AFTER INSERT | UPDATE | DELETE | TRUNCATE .. FOR EACH STATEMENT on tables and INSTEAD OF INSERT | UPDATE | DELETE .. FOR EACH ROW on views, with TG_OP, TG_WHEN, TG_LEVEL, NEW, OLD.

Indexes. CREATE [UNIQUE] INDEX .. ON t (lower(email)), ((a + b)), and partial indexes .. WHERE predicate (also unique).

Each of these is checked against a real PostgreSQL 18, and the output is identical.

Triggers, composite types, PL/pgSQL, MERGE .. BY SOURCE (stage 5c)#

Triggers. UPDATE OF columns, transition tables (REFERENCING OLD TABLE AS o NEW TABLE AS n) of statement-level AFTER triggers, WHEN on statement-level triggers, statement-level triggers on views, statement triggers for COPY, MERGE and INSERT .. ON CONFLICT DO UPDATE, RETURN NULL in BEFORE row triggers (the row is skipped). The functions of row triggers can use SELECT INTO, PERFORM, FOUND, FOR loops over integers and one-statement EXCEPTION blocks.

Composite types. Fields of any type (domains, enums, nested composite types, interval, bytea); ALTER TYPE .. ADD | DROP | RENAME | ALTER ATTRIBUTE; ordering comparison of records, ORDER BY, min and max of composite values; arrays of timetz.

PL/pgSQL. FOREACH, cursors (OPEN, FETCH, MOVE, CLOSE, FOR over a cursor, refcursor), COMMIT and ROLLBACK in procedures and DO, format().

Also. percentile_disc over any ordered type and percentile_cont over intervals; an unconstrained numeric keeps the scale of each value; information_schema reports which views are updatable; index expressions with commas; DETAIL: Failing row contains for a view's check option; MERGE .. WHEN NOT MATCHED BY SOURCE; UPDATE | DELETE .. WHERE CURRENT OF.

Each of these is checked against a real PostgreSQL 18, and the output is identical.

JSON, extensions, column privileges, TABLESAMPLE, client libraries (stage 6)#

The leftovers of stage 5c. COMMIT | ROLLBACK AND CHAIN (also in procedures), FOREACH .. SLICE, format() with widths and the - flag, percentile_cont of intervals with an array of fractions, MERGE .. RETURNING with merge_action(), unnest of several arrays, ordering comparison and ORDER BY of arrays, transition tables of row-level triggers, EXCEPTION blocks of several statements in the functions of row triggers.

JSON. to_json, to_jsonb, json_build_object, jsonb_build_object, json_build_array, json_agg, jsonb_agg, json_object_agg, json_extract_path[_text], jsonb_set, jsonb_insert, jsonb_strip_nulls, jsonb_pretty, jsonb_object_keys, jsonb_array_elements[_text], and the jsonb operators ||, - and #-. Set-returning functions (unnest, generate_series, generate_subscripts, the JSON ones) work in the select list too.

Extensions. CREATE EXTENSION and DROP EXTENSION for uuid-ossp (uuid_generate_v1 to v5, uuid_nil, uuid_ns_*), pgcrypto (digest, hmac, gen_random_bytes) and pg_trgm (similarity, show_trgm, %, <->); \dx lists them.

Column privileges. GRANT | REVOKE SELECT | INSERT | UPDATE | REFERENCES (columns) ON table, enforced; has_column_privilege; information_schema.column_privileges.

TABLESAMPLE BERNOULLI | SYSTEM (percent) [REPEATABLE (seed)].

Client libraries. psycopg2, SQLAlchemy 2 (DDL from models, reflection, ORM), asyncpg (type introspection, prepared statements, COPY) and Django (migrations, inspectdb, ORM) were run against Raft DB and a real PostgreSQL 18 with the same program: the outputs are identical. pgjdbc was checked before.

Each of these is checked against a real PostgreSQL 18, and the output is identical; what cannot be the same (statistics counters, which rows a sample holds) is listed under the known differences.