Skip to content

User Guide

Mohammad Rasoul Kazemi edited this page Nov 27, 2026 · 3 revisions

User Guide

This is the entry page for people who write SQL against KingresDB. Each extension has its own detailed page; this page says which one to use for which task, gives a short working path for each, and lists the SQL surface. Everything here is taken from the READMEs of the extensions, their install scripts and their regression tests, for the versions of the first release, 0.1.0 (published on 2026-11-28): kingres_shard 0.9, kingres_ledger 0.3, kingres_sketch 1.0, kingres_timepart 0.3 and kingres_columnar 0.2. See Limitations and Known Issues for what does not work.

How the cluster is set up and run is in the Administrator Guide. The REST API is in REST API Reference.

Which extension for which task

You want to Use Detailed page
Spread big tables over several servers, keep small tables on every server kingres_shard Sharding
Make reads and aggregates over distributed tables faster pushdown inside kingres_shard (automatic) Sharding Query Pushdown
Distribute or undistribute a table that already has rows, change its distribution kingres_shard 0.9 Sharding Table Lifecycle
Place whole schemas in one shard group (schema-based sharding) kingres_shard 0.9 Sharding
Detect tampering with history of a table kingres_ledger Ledger, The Verifier
Count distinct values, find top items, get percentiles approximately, and keep the result in a rollup kingres_sketch Analytics Extensions
Create and drop time partitions automatically, convert old ones to columnar kingres_timepart Analytics Extensions
Store append-only analytic data compactly and read a few columns fast kingres_columnar Analytics Extensions

The extensions build and work on PostgreSQL 18 and 19 from one source. Which extensions need a library in shared_preload_libraries:

Extension Needs a preload
kingres_shard Yes: shared_preload_libraries = 'kingres_shard' on every node (README, "Requirements and installation"); every node also needs max_prepared_transactions greater than zero and, for bucket moves, wal_level = logical.
kingres_ledger Yes: shared_preload_libraries = 'kingres_ledger'; without it ledger_enable refuses with KL003.
kingres_columnar Yes, on every node that writes, replays or restores columnar data, standbys included.

In a cluster that kingresd runs, you do not set this by hand: every instance it starts preloads kingres_shard,kingres_ledger,kingres_columnar,pg_stat_statements (a library that the installation does not have is left out), and the list takes effect at the next restart of the instance. | kingres_sketch | No. | | kingres_timepart | No (SQL and PL/pgSQL only). |

Quick path: sharding

On the first node, then from any node. Run these as a superuser; the administration functions have EXECUTE revoked from PUBLIC.

CREATE EXTENSION kingres_shard;
SELECT kingres.init_cluster('host1', 5432);       -- this node becomes node 1, the map group primary
SELECT kingres.add_node('host2', 5432);            -- each new primary is a new shard group

CREATE TABLE users (id int, name text, PRIMARY KEY (id));
SELECT kingres.create_distributed_table('users', 'id');
CREATE TABLE countries (code text PRIMARY KEY, name text);
SELECT kingres.create_reference_table('countries');

INSERT INTO users VALUES (42, 'ada');             -- from any node
SELECT name FROM users WHERE id = 42;             -- goes to the group that owns bucket of 42
SELECT count(*) FROM users;                       -- reads every group
EXPLAIN SELECT name FROM users WHERE id = 42;     -- shows where it runs
SELECT * FROM kingres.nodes;
SELECT * FROM kingres.buckets;
SELECT * FROM kingres.check_cluster();            -- no row when the cluster is consistent

Rules worth knowing before you start (details on Sharding):

  • Every unique constraint of a distributed table must include the distribution column.
  • A transaction that writes on several nodes commits with two-phase commit; there is no global snapshot, so a read that spans groups can see a distributed transaction on one group before another (ADR 0009).
  • Sequences are per node.
  • Errors named KS001 mean a stale bucket map: repeat the statement. The codes are on Sharding and Troubleshooting.
  • In a running cluster, adding nodes, moving buckets and rebalancing are normally driven by kingresd, not by hand: see Cluster Setup and Rebalancing.

Changing a table that holds rows (distribute, undistribute, change column or bucket count, blocking or online) is on Sharding Table Lifecycle; always look at kingres.table_change_report(...) first. Pushdown is automatic and only needs EXPLAIN to inspect; switches are on Sharding Query Pushdown.

SQL surface (full tables on the detailed pages): init_cluster, add_node, remove_node, sync_catalog, create_distributed_table, create_reference_table, bucket_for, set_node_property, rebalance_plan, move_bucket, resume_bucket_moves, cancel_bucket_move, cleanup_moved_buckets, check_cluster, recover_prepared_transactions, detect_distributed_deadlocks, rotate_secret, create_restore_point, promote_node, the standby and switchover functions, and the lifecycle functions table_change_report, *_concurrently, undistribute_table, alter_distributed_table, table_operation_advance, cancel_table_operation, resume_table_operations, cleanup_table_operations. Views: nodes, buckets, bucket_move_status, catalog_status, partitions, table_operations.

Quick path: ledger

-- in postgresql.conf: shared_preload_libraries = 'kingres_ledger'
CREATE EXTENSION kingres_ledger;                         -- superuser, in each database
GRANT EXECUTE ON FUNCTION kingres.ledger_enable(regclass, text) TO table_admin;   -- once, by the administrator

SELECT kingres.ledger_enable('public.accounts');         -- append-only; existing rows are entered
SELECT kingres.ledger_enable('public.inventory', 'updatable');   -- history table inventory_ledger_history

SELECT kingres.ledger_build_block();                     -- normally a background worker does this
SELECT kingres.ledger_generate_digest();                 -- store the result OUTSIDE the database
SELECT * FROM kingres.ledger_verify();                   -- no rows when consistent
SELECT kingres.ledger_verify_digest('{...}');            -- a digest exported earlier
SELECT kingres.ledger_inclusion_proof('accounts', kingres.ledger_row_hash(a.*))
  FROM accounts a WHERE id = 1;

Enabling a table is permanent, the mode cannot change, TRUNCATE and DROP TABLE of a ledger table are rejected, and ledger_verify alone proves nothing against someone who rewrites the whole chain: only a digest kept outside the database does. The independent check of a digest or proof, without trusting the database, is the kingres-verify program (The Verifier). Signing, publication and anchoring are run by kingresd: Ledger Signing and Publication, Ledger Anchoring. Clients can sign the rows they write (ledger_client_key_register, ledger_attest, ledger_set_signature_policy); see Ledger.

Quick path: sketches

CREATE EXTENSION kingres_sketch;                 -- schema kingres_sketch, no preload, no restart
SET search_path = public, kingres_sketch;

SELECT approx_count_distinct(user_id) FROM events;
SELECT approx_percentile(0.95, latency_ms) FROM requests;
SELECT * FROM topn_list(topn_add_agg(url, 100), 10);         -- item, frequency, max_error

-- a rollup: one sketch per day, united later
CREATE TABLE daily_rollup AS
  SELECT date_trunc('day', ts) AS day, hll_add_agg(user_id) AS users
  FROM events GROUP BY 1;
SELECT hll_cardinality(hll_union_agg(users)) FROM daily_rollup;

Sketches of different precision, capacity or compression cannot be united (only an hll can be folded to a lower precision with hll_fold). A rollup must either rebuild a whole window or add each source row exactly once: uniting a window with itself leaves an hll as it was but counts twice in a topn and a tdigest. topn accepts only types whose text does not depend on a setting. Function tables are on Analytics Extensions.

Quick path: time partitioning

CREATE EXTENSION kingres_timepart;     -- superuser; objects in schema kingres
-- a table partitioned by RANGE on one date, timestamp or timestamptz column, with no DEFAULT partition
SELECT kingres.timepart_set_policy('public.events', '1 day',
                                   create_ahead => '3 days',
                                   retention => '30 days',
                                   columnar_after => '2 days');
SELECT * FROM kingres.timepart_plan('public.events');      -- what a run would do
CALL kingres.timepart_run('public.events');                -- cannot run inside a transaction block
SELECT * FROM kingres.timepart_check();                    -- problems: ahead_low, last_run_failed, ...
SELECT * FROM kingres.timepart_run;                        -- history of runs (view; your own tables)

A run happens only when something calls it: psql, pg_cron, or, in a cluster that kingresd runs, the scheduler of the control plane, which runs the policies that are enabled (policies, plans and runs are also in the console and the REST API). columnar_after needs kingres_columnar. Execute rights are revoked from PUBLIC; the README lists the grants. A policy restored from a dump does nothing until a superuser runs timepart_adopt(). Manual creation and removal: create_time_partitions, drop_old_time_partitions; manual conversion: CALL kingres.convert_partition(parent, partition).

Quick path: columnar storage

-- postgresql.conf: shared_preload_libraries = 'kingres_columnar'   (every node that writes or replays)
CREATE EXTENSION kingres_columnar;     -- superuser; objects in schema kingres
CREATE TABLE events (ts timestamptz, device int, value float8) USING columnar;
INSERT INTO events SELECT now(), g % 10, random() FROM generate_series(1, 1000000) g;
SELECT * FROM kingres.columnar_info('events');
SELECT kingres.columnar_compact('events');           -- merge small stripes after many small loads
SELECT kingres.columnar_set_options('events', compression => 'zstd', compression_level => 5);
ALTER TABLE events SET ACCESS METHOD heap;           -- converts back; "columnar" converts forward

Columnar tables are append-only: UPDATE, DELETE and MERGE that match a row, row locks, TABLESAMPLE, CLUSTER, indexes other than B-tree, foreign keys, row-level AFTER triggers and temporary or unlogged tables are refused (SQLSTATE 0A000). Load in big transactions: many tiny transactions make tiny stripes. Run columnar_check() or columnar_check_clean() as a superuser to find damage; any returned row means "not clean".

Where the same things are done from the REST API and the console

The control plane runs the cluster-level work: creating and joining a cluster, databases, roles, rebalance, failover, configuration and the ledger publication. The SQL on this page is for data and tables. See Web Console and REST API Reference.

Sources

Clone this wiki locally