SQL API and metadata reference
Functions for application SQL
These are available to every application's SQL (region sources, processes, RLS policies, triggers, your own functions).
| Function | Returns | Description |
|---|---|---|
meta.app_user() | text | The signed-in application user, or nobody. In PostgREST requests: the token's user (chapter 13) |
meta.app_id() | int | The current application's id (in PostgREST: the app named in the token) |
meta.has_role(role) | boolean | Whether the current user has the role in this application (roles are resolved at sign-in; in PostgREST: the token's roles claim or the account's roles in the token's app) |
meta.jwt_claims() | jsonb | The verified JWT claims of a PostgREST request, or NULL |
meta.app_language() | text | The language of the request (nl, en-GB, …) |
meta.message(name, variadic params) | text | A text message in the current language, %0…%9 replaced; falls back to the base and primary language |
meta.lang(text, language default null) | text | A dynamic translation of a value from a table in the session's (or the given) language, else the text (APEX: APEX_LANG.LANG) |
meta.get_app_setting(name), meta.set_app_setting(name, value) | text / void | An application setting of the current application (APEX: APEX_APP_SETTING); application code only |
meta.get_preference(name, user default null), meta.set_preference(name, value, user default null), meta.remove_preference(name, user default null) | text / void | A user preference of the signed-in (or the given) user in the current application (APEX: APEX_UTIL.*_PREFERENCE) |
meta.data_export(query, format default 'csv', options jsonb default '{}') | bytea | A query's rows as a CSV, JSON, XML or HTML file, run with the caller's privileges (data export; APEX: APEX_DATA_EXPORT) |
meta.csv_field(value, separator default ',', is_text default true) | text | One CSV field: quoted when needed, a formula neutralised |
meta.password_days_left(username) | int | Days until the password expires (0: must change now, NULL: never) |
meta.v(name) | text | The session-state value of an item (use it inside functions and DO blocks) |
meta.make_password_hash(password, format, cost) | text | (sprint 248) A password hash custom authentication's hash query checks: 'bcrypt' (default, cost 4–16, default 12) or Django's 'pbkdf2_sha256' / 'pbkdf2_sha1' (iterations 1,000–10,000,000, default 1,000,000) (chapter 8) |
meta.set_auth_user(name), meta.auth_user_problem(name) | void / text | (sprint 241) In a custom authentication scheme's post-authentication code only: the user name the session gets, e.g. lower(p_username) (APEX: apex_custom_auth.set_user); an error anywhere else. auth_user_problem says why a name can't be one (NULL: it can) (chapter 8) |
meta.set_tenant(tenant) | void | Sets (or with NULL or '' clears) the current session's tenant (APEX: apex_session.set_tenant_id): at once and for the session's next requests. Workflows and tasks then carry it and show only to that tenant (chapter 6) |
meta.tenant_id() | text | The current session's tenant, or NULL (APEX: sys_context('APEX$SESSION', 'APP_TENANT_ID')); in a workflow step, the workflow's tenant |
meta.v_boolean(name) | boolean | An item's value as a boolean (APEX 26.1: BOOLEAN session state): true, t, yes, y, 1, on → true; false, f, no, n, 0, off → false; empty or anything else → NULL. Switches and checkboxes store true / false, so :P3_ACTIVE::boolean works in SQL too |
meta.page_url(page, items jsonb default '{}', clear boolean default true, p_absolute boolean default false) | text | A URL to a page of the current app, with a valid checksum for the items: meta.page_url(3, jsonb_build_object('P3_EMPNO', empno)). (sprint 250) p_absolute => true: with the installation's public address in front (PUBLIC_URL), for links in mail (absolute URLs) |
meta.app_url(p_absolute boolean default true) | text | (sprint 250) The current application's address, https://apps.example.com/a/hr (false: /a/hr) |
meta.public_url() | text | (sprint 250) The installation's public address the server recorded at start-up from PUBLIC_URL (fallback http://127.0.0.1:<PORT>); an error where no server has recorded it. Never the request's Host header |
meta.html_escape(text) | text | Escapes & < > " ' for HTML (use it in dynamic content regions) |
meta.url_encode(text) | text | Percent-encodes a URL component |
meta.temp_files (view) | rows | The current session's uploaded files: id, item_name, filename, mime_type, size, content, created_at (like APEX_APPLICATION_TEMP_FILES; chapter 16) |
meta.delete_temp_file(id) | void | Removes one of the current session's uploaded files |
meta.debug(level, text), meta.debug(text) | void | A debug message (APEX: apex_debug.message): recorded with the request when the app's debug level is at least level (1 error, 2 warning, 4 information (the default), 6 trace, 9 everything); otherwise it returns at once. Texts are cut at 4000 characters |
meta.debug_enabled(level default 4) | boolean | Whether a message of this level would be recorded (skip building expensive texts) |
meta.debug_level() | int | The request's debug level (0: off, and outside a request) |
meta.web_request(url, method default 'GET', body default null, headers jsonb default null, credential default null, timeout_s default 10, max_attempts default null, callback default null, ordering_key default null, idempotency_key default null, idempotency_header default 'Idempotency-Key') | bigint | Queue an HTTP request (APEX: apex_web_service.make_rest_request); the server makes it, see web requests from SQL. Returns the request's id. (sprint 177) The last five parameters make it an outbox: retries, a callback function, delivery in order and an idempotency key |
meta.web_request_source(source, params jsonb default null, timeout_s default null, max_attempts default null, callback default null, ordering_key default null) | bigint | Queue a call of a REST data source of the app (its URL, method, headers and web credential; parameter values as text) |
meta.web_response(id) | jsonb | The request's state and response: status (queued, running, retry, ok, error, gave_up, cancelled), status_code, headers, content_type, body (text), json (the body parsed when it is JSON), size, url, message, times, and (sprint 177) attempts, max_attempts, next_attempt_at, ordering_key, idempotency_key, callback, callback_state (pending, running, done, failed), callback_error. NULL for a request of another application |
meta.web_request_cancel(id) | boolean | (sprint 177) Cancel a request of the current application that still waits (queued, or retry between two attempts); true when it did |
meta.webhook_event() | jsonb | (sprint 177) In the block of a webhook handler: the event it runs for, {"id", "event_id", "received_at", "attempt", "content_type", "headers"} |
meta.web_response_blob(id) | bytea | The response body as bytes (files, images) |
meta.parse_data(content bytea, file_name, format, headers, delimiter, row_selector, skip_rows, max_rows) | table | The rows of a CSV/TSV, JSON, XML or Excel file (APEX: apex_data_parser.parse): line_number, cols (text[] by position), data (jsonb by column name). See parsing files |
meta.parse_data_columns(…the same arguments) | table | The file's columns (APEX: apex_data_parser.get_columns): column_position, column_name, heading, data_type |
meta.zip_add(zip bytea, name, content bytea), meta.zip_finish(zip) | bytea | Build a zip (APEX: apex_zip.add_file, apex_zip.finish); see zip files |
meta.zip_agg(name, content order by …) | bytea | Aggregate: one zip of the rows' files |
meta.zip_entries(zip), meta.zip_entry(zip, name) | table / bytea | The files in a zip and one file's content (APEX: apex_zip.get_files, apex_zip.get_file_content) |
The runtime sets these settings in each request's transaction (don't set them yourself): pgkiln.app_user, pgkiln.app_id, pgkiln.session_id, pgkiln.tenant_id, pgkiln.debug_level, pgkiln.public_url (the server's PUBLIC_URL; absolute URLs use meta.public_url() instead, which application code can't change), pgkiln.web_pending (set by meta.web_request).
Web requests from SQL
PostgreSQL can't make an HTTP request without an extension (see chapter 15 for http and pg_net), so meta.web_request() doesn't wait for the answer: it queues the request in meta.web_request_log and returns its id. The pgkiln server makes the request and stores the response, which meta.web_response(id) returns. When that happens depends on where the SQL runs:
| Queued in | Made | Read the response |
|---|---|---|
A page process of type sql (also inside a chain or a background chain) | Right after that process, in the same transaction, before the next process runs (at most 5 per process; more wait for the scheduler) | In the next process of the same submit |
(sprint 240) An Ajax callback (also each SQL step of a chain called as one) or an execute_sql dynamic action | Right after it, in the same transaction, like a page process; the requests of one call get 30 seconds together (each time limit cut to what is left; one with less than a second left is made after the commit) | In the chain's next step (the callback answers with it), or the event's next action |
Anything else: automations, workflow steps, computations, validations, region sources, other dynamic actions (set_value), triggers, PostgREST requests, psql; and every request with a callback or an ordering key | After the transaction commits, at once: queueing notifies the server (sprint 177; NOTIFY pgkiln_web_request). The scheduler pass (SCHEDULER_INTERVAL_S, default 30 seconds) stays as the fallback; up to 50 at a time are claimed, 5 run at once | Later: from another page view, an automation, a workflow step, or in the request's callback |
A rolled-back transaction takes its queued requests with it (one made in a page process has been sent anyway, as with the invoke_api process). With AUTOMATIONS=off on every server, requests outside page processes are never made (they end as error after 24 hours).
-- process 1 (button FETCH): queue the request, keep its id in an item
select meta.web_request('https://api.example.com/rates?base=' || meta.url_encode(:P5_CURRENCY),
p_credential => 'RATES_API') as p5_request;
-- process 2: the server has made it by now
select r -> 'json' ->> 'rate' as p5_rate,
case r ->> 'status' when 'ok' then null else r ->> 'message' end as p5_error
from meta.web_response(:P5_REQUEST::bigint) r;
-- POST with a JSON body and headers; a REST data source with parameters
select meta.web_request('https://api.example.com/orders', 'POST', json_build_object('id', 42)::text,
'{"Content-Type": "application/json"}');
select meta.web_request_source('EXCHANGE', '{"currency": "EUR"}');- The same protections as REST data sources (chapter 19): the host must be on
PGKILN_REST_ALLOWED_HOSTS(unset: no calls), private and loopback addresses are refused when the connection is made unless the host is inPGKILN_REST_PRIVATE_HOSTS, redirects (at most 3) go through the same checks, the response is cut off atPGKILN_REST_MAX_BYTES(default 5 MB) and the time limit is 1–60 seconds. A workspace's network access list (sprint 118) narrows the hosts for its applications: a refused request ends withstatuserrorand the reason inmessage, and is logged (debug log, Refused calls). - Web credentials are named, never passed:
p_credential => 'NAME'signs the request with a credential of the current application (basic, bearer, header, OAuth2), and only for the URLs it is valid for. The secret is decrypted by the server for the request only and is never stored with it or visible to SQL. statusisokwhen an answer came back, whatever its status code (checkstatus_code, likeapex_web_service.g_status_code);errormeans no answer (messagesays why: the host is not allowed, a time-out, the size limit, the credential).- Limits per call: URL ≤ 4000 characters, body ≤ 1 MB (text; a file goes in
p_body_blob, below), ≤ 30 headers (noHost,Content-Length,Connectionand the like, no line breaks), methodsGET,HEAD,POST,PUT,PATCH,DELETE; at most 100 requests of an application waiting at a time. - Requests and responses are kept 24 hours (at most 500 finished ones per application; a request that gave up is kept 7 days, so it can be queued again), then removed by the scheduler. They belong to the application, not to a user: any code of the app that knows an id can read the response, so don't let users choose the id when responses differ per user.
- Application roles can't read
meta.web_request_log. Developers see the queue of their workspace's applications in the builder: SQL Workshop → RESTful Services → Web requests (status, attempts, next attempt, last error, the callback's state; Re-queue, Cancel, Call back again).
The outbox: retries, callbacks, ordering
(sprint 177, migration 160) A request queued in the same transaction as your data change is an outbox: it exists only if the change committed, and the server keeps trying to deliver it.
-- in a trigger, a process, an automation: tell the warehouse about a shipped order
select meta.web_request('https://api.example.com/shipments', 'POST',
json_build_object('order', :P3_ID, 'status', 'shipped')::text,
'{"Content-Type": "application/json"}', p_credential => 'WAREHOUSE_API',
p_callback => 'sales.order_sent', -- called when the request is final
p_ordering_key => 'order-' || :P3_ID, -- this order's requests go out one at a time, in order
p_max_attempts => 8);
create function sales.order_sent(p_request bigint) returns void language plpgsql as $$
declare r jsonb := meta.web_response(p_request);
begin
update sales.orders set sync_status = r ->> 'status', synced_at = now() where id = (r -> 'json' ->> 'order')::int;
end $$;
grant execute on function sales.order_sent(bigint) to sales_app;- Retries. A request the server delivers after the commit is tried up to
p_max_attemptstimes (default 5, at most 20). Worth another attempt: the service could not be reached or did not answer in time, a 5xx answer, a 429 answer. The request then hasstatusretryuntilnext_attempt_at: 30 seconds after the first attempt, doubling each time (±20 %), at most one hour (QUEUE_RETRY_S,QUEUE_RETRY_MAX_S); aRetry-Afterheader is honoured up to that maximum. After the last attempt the status isgave_up(with the last answer'sstatus_code, if there was one). Not retried: any other answer (okwith its status code, also a 4xx) and a request that can't be made (error: the host is not allowed, the credential has no secret, the response is too large). Every attempt goes through the allow-list and address checks again. A request a page process queues keeps its single attempt in the process's transaction, as before; givep_max_attemptsto have a failed one retried after the commit. - Callback.
p_callback => 'schema.function'names a function with onebigintargument, the request's id, that the application's database role may execute (checked when the request is queued; the name is looked up in the catalog, never run as text; functions ofmetaandpg_catalogare refused). The server calls it once the request is final (ok,error,gave_up), as the application's database role on the application's own connection, withmeta.app_user()the user who queued it and the session's tenant, in a transaction of its own, so triggers fire as usual. It reads everything withmeta.web_response(id). A callback that raises is rolled back and called again (3 times in all, with the same backoff), then itscallback_stateisfailedwith the error incallback_errorand in the application's error log; the HTTP request is never sent again because of it. Design the callback to be harmless when called twice (a server that stops right after it ran calls it again). It never runs as pgkiln's owner, a superuser or a role that bypasses row level security. - Ordering. Requests of one application with the same
p_ordering_keyare delivered strictly one at a time, in the order their transactions committed. One that waits for a retry holds the later ones of its key back until it succeeds or gives up; other keys, and requests without a key, are not held up. - Idempotency. Every attempt of a request carries the same key in a header, so the receiver can drop a repeat:
p_idempotency_keyif you give one (for example your own event id), otherwise a generated UUID forPOST,PUT,PATCHandDELETE. The header isIdempotency-Key;p_idempotency_headernames another one, ornullfor none. A header of that name inp_headerswins. (meta.web_request_sourcesends the source's own headers only.) - Several servers. A request is claimed with
FOR UPDATE SKIP LOCKEDand a lease; a server that stops while a request is in flight loses the lease and another server makes the next attempt. Delivery is therefore at least once: that is what the idempotency key is for. meta.web_request_cancel(id)cancels a waiting request. The HR example's page 35 has Fetch in the background (examples/hr/hr_86_web_request_outbox.sql).
Binary request bodies (files)
(sprint 243, migration 200) p_body_blob sends a bytea as the body, for a file API: OneDrive or SharePoint through Microsoft Graph, an object store with a bearer token, a scanner or signing service. It is sent with POST, PUT or PATCH instead of p_body (not both); its Content-Type is the one in p_headers (default application/octet-stream).
-- a file item's upload, sent to a file API (the server makes it right after this process)
select meta.web_request('https://graph.microsoft.com/v1.0/me/drive/root:/Werkbonnen/' || meta.url_encode(f.filename) || ':/content',
'PUT',
p_body_blob => f.content,
p_headers => jsonb_build_object('Content-Type', f.mime_type),
p_credential => 'GRAPH',
p_timeout_s => 60) as p5_request
from meta.temp_files f where f.id = :P5_FILE::uuid;
-- a large file: PUT in ranges to an upload session's URL (from createUploadSession; no credential, the URL is the key)
select meta.web_request(:P5_UPLOAD_URL, 'PUT', p_body_blob => :P5_CONTENT::bytea,
p_chunk_bytes => 3276800); -- 10 × 320 KiB per request
-- a REST data source's URL, method (POST, PUT or PATCH), headers and credential with a binary body
select meta.web_request_source('DRIVE_UPLOAD', '{"name": "scan.pdf"}', p_body_blob => v_pdf, p_content_type => 'application/pdf');- The same checks as a text body: the allow-list, the address checks when the connection is made, the workspace's network access list, redirects, and the credential's Valid for URLs. A
307/308redirect sends the body again to the new URL (through the same checks); a303turns the request into aGET. - Size. At most
PGKILN_REST_MAX_UPLOAD_BYTES(default 25 MB), separate from the 1 MB of a text body and from the response limitPGKILN_REST_MAX_BYTES. The server checks it when it makes the request: a larger body ends inerror(the message names the variable) and is never retried. SQL refuses more than 256 MB at once. - Retries (
p_max_attempts, the outbox) send the same bytes, with the same idempotency key. The blob stays inmeta.web_request_loguntil the request succeeded (ok): a request that gave up keeps it, so it can be queued again.meta.web_response(id)hasbody_blob_bytes, the size sent. - In ranges (
p_chunk_bytes, 64 KiB to 60 MiB,PUTonly): the blob goes in consecutive requests withContent-Range: bytes first-last/total, as a resumable upload URL expects (Microsoft Graph upload sessions for files over 4 MB: ranges a multiple of 320 KiB). An answer202before the last range continues with the next one; when it namesnextExpectedRanges(Graph does), the next range starts there. Any other answer ends the upload and is the request's answer: a200/201(the service has the whole file), or an error status (retried as usual for 5xx and 429; the upload then starts again from the first byte). Each range has the whole time limit (p_timeout_s). - The time limit is still at most 60 seconds per request: for a large file on a slow line, send it in ranges.
- HR example page 71 Send a file (
examples/hr/hr_107_send_file.sql) sends a file item's upload to the sample CRM's REST module, whole and in ranges; the receiving handler reads it with"body": "blob".
E-mail from SQL
Sending e-mail (APEX: APEX_MAIL). The application needs a mail service (an administrator chooses it under Workspace utilities → Mail services); with several, the From address chooses the service, else the application's default.
| Function | Returns |
|---|---|
meta.send_mail(p_to, p_subject, p_body, p_body_html, p_from, p_cc, p_bcc, p_reply_to) | Queues a mail and returns its id (APEX_MAIL.SEND). p_to, p_cc, p_bcc: addresses separated by commas or semicolons, at most 50 together (plain addresses, no display names); p_subject: one line, at most 998 characters; p_body (plain text) and/or p_body_html, each at most 1 MB; p_from: an address one of the application's services may send as, which chooses that service (default: the default service's From address); p_reply_to: one address |
meta.send_mail_template(p_template, p_placeholders jsonb, p_to, p_cc, p_bcc, p_from, p_reply_to) | The same with an e-mail template and its placeholder values (APEX_MAIL.SEND with p_template_static_id) |
meta.add_mail_attachment(p_mail_id, p_content bytea, p_filename, p_mime) | Adds a file to a mail queued in the same transaction (APEX_MAIL.ADD_ATTACHMENT); at most 20 files and 20 MB per mail, 10 MB per file |
meta.document_pdf(p_template, p_items jsonb) | (sprint 237) The PDF of one of the application's document templates, for meta.add_mail_attachment (APEX_PRINT.GENERATE_DOCUMENT). p_items: item values (jsonb_build_object('P3_EMPNO', 7839)) over the session state. Returns a reference that the server replaces with the PDF when the process ends (how); at most 50 per transaction |
meta.document_temp_file(p_template, p_items jsonb, p_filename) | (sprint 245) The id (uuid) of a temporary file of the session (meta.temp_files) that the server draws as the PDF of a document template when the process ends; read it from the next process on (store it in a table, attach it, send it). p_filename gets .pdf (null: the template's file name). Calling it outside a page's process fails at commit |
meta.mail_status(p_mail_id) | queued, sending, sent, error or cancelled; NULL for another application's mail |
meta.mail_available() | (155) Whether the application may send e-mail now: it has an enabled mail service with a From address. Without one, meta.send_mail and a Send E-Mail process raise an error (rolling back the submit), so use it as their condition when mail is optional |
The mail is sent by the server after the transaction commits. Over the application's limit per day meta.send_mail raises an error. (sprint 250) With the application's Redirect all mail to or the server's MAIL_REDIRECT_TO, every mail goes only to that address, [TEST] before the subject and the original recipients in X-Original-To/-Cc/-Bcc (redirect all mail); meta.mail_queue.redirected_to records it. Application roles can't read the queue; the owner can: select id, app_id, to_addresses, redirected_to, subject, status, attempts, message from meta.mail_queue order by id desc.
Push notifications from SQL
APEX_PWA push notifications (chapter 17); the application needs push notifications on (Settings → Progressive Web App).
| Function | Returns |
|---|---|
meta.send_push(p_user, p_title, p_body, p_page, p_items, p_tag, p_urgency, p_ttl_s) | Queues a notification for every device of p_user that turned notifications on, and returns its id. p_title (required, at most 200 characters), p_body (at most 1000), p_page + p_items (a page of the application and item values: the link, signed for the recipient), p_tag (1–32 letters, digits, -, _: replaces an older notification with the same tag), p_urgency (very-low, low, normal, high), p_ttl_s (how long the push service keeps it for an offline device, default 86400, at most 28 days) |
meta.has_push_subscription(p_user) | Whether the user (default: the current one) has a device with notifications on (APEX_PWA.HAS_PUSH_SUBSCRIPTION) |
The message is sent by the pgkiln server after the transaction commits (a rolled-back transaction sends nothing), at once when the server is notified, otherwise on the scheduler's next pass. At most 1000 messages per application wait at a time. Application roles can't read the queue; the owner can: select id, username, status, devices, delivered, message from meta.push_message order by id desc (sent: at least one device received it; no_device; error). Messages are kept 7 days.
In-app notifications from SQL
Sprint 165: the notification bell; the application needs notifications on (Settings → User Interface → Notifications).
| Function | Returns |
|---|---|
meta.notify(p_user, p_title, p_body, p_page, p_items, p_icon, p_push) | Adds a notification for p_user of the current application and returns its id. p_title (required, at most 200 characters), p_body (at most 1000), p_page + p_items (the page it opens with item values: the link, signed for the recipient), p_icon (an icon name), p_push (also to the user's devices when push notifications are on; default false) |
meta.unread_notifications(p_user) | The number of unread notifications of the user (default: the current one), e.g. as a badge query |
meta.mark_notifications_read(p_id) | Marks the current user's notification p_id read, or all of them (null); returns how many |
meta.my_notifications | A view: the current user's notifications (id, title, body, url, icon, created_at, read_at, unread) |
A notification exists once the transaction commits. A user keeps the newest 500; read ones go after 90 days. Application roles reach the table only through these functions and the view.
AI requests from SQL
meta.ai_generate(service, prompt, system, schema) queues a request to an AI service the current application may use and returns its id; meta.ai_result(id) returns {"id", "status", "service", "text", "json", "message", times} (status: queued, running, ok, refused, error; json is the parsed answer when a schema was given). Like web requests, the server makes the call right after the sql page process that queued it (at most 3 per process), in the same transaction, so the next process can read the answer; anything else is made by the scheduler after the commit.
-- process 1 (button SUMMARISE)
select meta.ai_generate('CLAUDE', 'Summarise this complaint in one sentence: ' || :P5_TEXT,
'You help a customer service team.') as p5_request;
-- process 2
select meta.ai_result(:P5_REQUEST::bigint) ->> 'text' as p5_summary;
-- structured: a JSON schema of an object
select meta.ai_generate('CLAUDE', 'Classify: ' || :P5_TEXT, null,
'{"type": "object", "properties": {"category": {"type": "string", "enum": ["billing", "delivery", "other"]}},
"required": ["category"], "additionalProperties": false}');- The prompt is sent as your SQL built it (no
&ITEM.substitutions and no data wrapping): when it contains user input, say in the system prompt that it is data, and treat the answer as untrusted. - Limits: the prompt 1–200,000 characters, the system prompt 50,000, the schema 50 KB; at most 20 requests of an application waiting. The service's daily limits apply and every call is logged in
meta.ai_usage(without prompt or answer). - Requests and answers are kept 24 hours. Application roles can't read
meta.ai_request, only their own application's requests throughmeta.ai_result. meta.ai_available(service): true when the application may use the service (it exists, is enabled and the application is allowed); whether the provider accepts the key shows only when a request is made.
Embeddings in SQL
(sprint 136) meta.embed(text, provider [, app_id]) returns the embedding of a text by a vector provider of the current application (or of app_id, one the login may see) as real[]; cast it for pgvector: meta.embed(:P1_Q, 'DOC_EMBEDDINGS')::vector. It works for function providers and calls the function as the role of the query (security invoker: its grants apply), checking the dimensions. A provider that uses an AI service is called by the pgkiln server, never from SQL: meta.embed raises an error that says so (use a vector search configuration, a Retrieve tool or a vector column's queue). meta.vector_provider(name [, app_id]) returns a provider's definition (they hold no secrets).
-- the nearest documents to a text, as the application's role (row level security applies)
select title from sales.doc
order by embedding <=> meta.embed('how do I return an order?', 'DOC_EMBEDDINGS')::vector
limit 5;Parsing files in SQL
meta.parse_data() reads CSV/TSV and JSON in a bytea (an uploaded file in meta.temp_files, a file column, a web response) with the same rules as the data loader (chapter 16):
-- the columns: names (SQL names, the keys of "data"), headings and inferred types
select * from meta.parse_data_columns((select content from meta.temp_files where item_name = 'P8_FILE'));
-- the rows, typed through a table's row type
insert into app.employee (name, hire_date, salary)
select e.name, e.hire_date, e.salary
from meta.parse_data((select content from meta.temp_files where item_name = 'P8_FILE')) p,
jsonb_populate_record(null::app.employee, p.data) e;
-- or by position
select p.cols[1] as name, p.cols[3]::numeric as salary from meta.parse_data(:file) p;| Argument | Default | Meaning |
|---|---|---|
p_content | The file | |
p_file_name | null | Helps detecting the format (.csv, .tsv, .json, .jsonl, .ndjson) |
p_format | auto | csv, tsv, json; auto looks at the name and the first bytes |
p_headers | true | CSV: the first row holds the headings (else column_1, column_2, …) |
p_delimiter | detected | CSV: one character; detected from the first line (, ; tab |) |
p_row_selector | null | JSON: the path to the array of records (data, result.items); without it an array, an object holding one array, or JSON Lines |
p_skip_rows | 0 | Rows to skip before the headings |
p_max_rows | 100000 | More rows is an error (at most 1,000,000) |
- Values are text (blank → NULL), as written in the file; nested JSON values are JSON text. Column names are lower-case SQL names made from the headings (
Hire Date→hire_date, made unique); types are inferred over all rows:integer,bigint,numeric,boolean,date(ISO),timestamp, elsetext. - Text is read as UTF-8 (with or without a byte order mark), else as Windows-1252.
- XML (
.xml, or text starting with<): the rows of a repeating element, as the data loader reads them.p_row_selectornames the row element (employee, or a path ending in it:employees/employee); without it the element path that occurs most often among elements with children or attributes. Columns are the row's attributes (@id→ columnid), its child elements (name) and deeper elements by path (address/city→address_city); namespace prefixes are ignored. Documents with a DTD or entity declarations are refused. - Excel (.xlsx): an
.xlsxfile is a zip archive of compressed parts, and PostgreSQL can't decompress. pgkiln reads the sheets when it receives the file: a file item's upload (someta.temp_filescontent works) or ameta.web_request()response, and keeps them for 24 hours, found by the file's content.p_row_selectornames the sheet (default: the first); cells are text as the data loader writes them (datesYYYY-MM-DD). Other.xlsxcontent (e.g. a file column of a table) gives an error that says so: load it with adata_loadprocess. - It runs as the caller (no special rights) and within the statement time limit (a 4 MB CSV file of 100,000 rows takes about a second).
Zip files in SQL
APEX_ZIP in SQL. Build a zip from files, for a download process or a web request body:
-- one row per file
select meta.zip_agg(d.filename, d.content order by d.filename) as content, 'documents.zip' as file_name, 'application/zip' as mime_type
from hr.emp_document d where d.empno = :P3_EMPNO;
-- or step by step, like apex_zip.add_file / finish
declare z bytea;
begin
z := meta.zip_add(z, 'report.csv', convert_to(csv_text, 'UTF8'));
z := meta.zip_add(z, 'images/logo.png', logo);
z := meta.zip_finish(z);
end;Entries are stored uncompressed (PostgreSQL has no compression in SQL); names are relative paths in UTF-8 (.. and leading / are refused). For big downloads a download process with several rows makes a compressed zip in the server instead (chapter 6).
Read one:
select name, size from meta.zip_entries((select content from meta.temp_files where item_name = 'P8_ZIP'));
select meta.zip_entry(:zip, 'data/employees.csv'); -- bytea, or null when there's no such file
select * from meta.parse_data(meta.zip_entry(:zip, 'data/employees.csv'), 'employees.csv');meta.zip_entries and meta.zip_entry read zips built in SQL directly. Compressed zips (nearly all others) are unpacked by pgkiln when it receives them, like Excel files above (a file item's upload or a web response; at most 2,000 files and 200 MB unpacked), and read from there for 24 hours; for any other compressed zip they say so.
From APEX_JSON
PostgreSQL's JSON functions do what APEX_JSON does, in SQL:
| APEX_JSON | PostgreSQL |
|---|---|
apex_json.open_object … write('name', value) … close_object | jsonb_build_object('name', value, …) |
open_array … close_array over a cursor | jsonb_agg(jsonb_build_object(…) order by …) from a query |
write(p_cursor) | select jsonb_agg(to_jsonb(t)) from (…) t (column names become keys) |
get_clob_output | the value itself (::text for text) |
parse(text) then get_varchar2('a.b'), get_number, get_count | doc #>> '{a,b}', (doc ->> 'n')::numeric, jsonb_array_length(doc -> 'items') |
apex_json.find_paths_like | jsonb_path_query(doc, '$.**.name') |
apex_json.to_xmltype / JSON_TABLE | json_table(doc, '$.items[*]' columns (…)) (PostgreSQL 17) or jsonb_to_recordset(doc -> 'items') |
Web services return JSON through meta.web_response(id) -> 'json', and meta.parse_data turns a JSON file into rows.
APEX views
(sprint 217) Schema apex has APEX 26.2's dictionary views that an application's administration pages read, with APEX's names and the columns pgkiln has data for, read-only over pgkiln's own tables. The APEX importer qualifies them (apex_activity_log → apex.apex_activity_log); in your own SQL write apex. too.
| View | From | Notes |
|---|---|---|
apex_applications, apex_application_pages | the application and its pages | theme_number is 42 (APEX's Universal Theme) |
apex_application_build_options | build options | build_option_status: Include or Exclude |
apex_application_lov_entries | static lists of values (STATIC:) | a query's entries are its rows |
apex_application_themes, apex_application_theme_styles | the base styles Standard, Iris, Lavender | is_current for the application's |
apex_activity_log | page views and errors of the activity log | flow_id, step_id, time_stamp (a timestamp in the session's time zone, as sysdate is), userid, elap (seconds), sqlerrm (an error's text) |
apex_team_feedback | feedback | feedback_rating 1 to 3 (pgkiln's 1–2, 3, 4–5); feedback_status 0 declined, 1 in progress, 3 open, 4 done |
apex_appl_acl_roles, apex_appl_acl_user_roles, apex_appl_acl_users | the roles an application uses (role authorization schemes, identity-provider groups, its users' roles) and its users | role_id is a number made from the role's name; role_names comma-separated, role_ids colon-separated |
apex_appl_automations, apex_automation_log, apex_automation_msg_log | automations, their runs, each run's message and row errors | status: SUCCESS, FAILURE, SUCCESS_WITH_ERRORS, RUNNING |
Who sees which rows: at run time only the running application's; in the SQL Workshop a workspace's developer login its own workspace's applications; pgkiln's owner every application; any other login none. No password hash, secret or session id is in them. They are read-only: APEX's APIs that change these (apex_acl, apex_util.set_build_option_status, apex_theme …) are PL/SQL to port to pgkiln's (Access control, build options, the theme in Shared Components). apex_collections has no counterpart: pgkiln has no collections (use a table, or jsonb in session state).
Functions for developers and scripts
Run these as the owner (in the SQL Workshop, psql or migrations):
| Function | Description |
|---|---|
meta.generate_crud(app, table, report_page, form_page, label default null, icon default 'table') | Report page + modal form page + menu entry for a table, with the column names as labels (kept as it was for existing scripts; meta.generate_page report_form makes the labelled pages of the wizards) |
meta.generate_grid(app, table, page, label default null, icon default 'grid') | Interactive grid page + menu entry |
meta.generate_page(app, kind, table, page, options default '{}') | The create page wizards: kind is form, cards, calendar, chart, map, facets, master_detail (or report_form, grid); (137) also report, smart_filters, tree, timeline, media_list, content_row, comments, data_load, wizard, and without a table (null) search, tasks, workflows. Options left out take the defaults of meta.wizard_defaults; JSON null means none. Returns the new page's id (below; a wizard: its first page's) |
meta.wizard_defaults(kind, table) | The options a wizard proposes for a table, from the catalog |
meta.wizard_catalog(table) | The columns as the wizards see them: kind (text, number, date, timestamp, boolean, point, geometry, binary, other), key, unique, foreign key and the parent's display column |
meta.wizard_label(name), meta.wizard_table_label(table, plural default true), meta.wizard_column_label(table, column) | (097) The labels of the wizards: hiredate → Hire Date, hr.emp → Employees / Employee, deptno → Department; short comments win (what the generated pages look like) |
meta.wizard_report(table, columns default null) | (097) A report on a table as the wizards make it: {"source", "hidden", "headings", "formats"} (foreign keys joined to their parent's display column) |
meta.wizard_grid_labels(table) | (100) An interactive grid's {"headings", "formats"} as the wizards make them: the labels of meta.wizard_column_label and the number format masks (keys get none) |
meta.app_activity(days default 30) | (098) The current application's page views, sign-ins and errors of the last days (1 to 366, at most 10,000 rows, no IP addresses), for a signed-in user with the admin role of that application; others get an error. The Activity page of the Create Application wizard reads it |
meta.configurable_options(), meta.set_configurable_options(names) | (137) The current application's configurable build options (name, description, enabled), and switching them (names colon-separated: those are included, the other configurable ones excluded). Only as the application's own role, for a user with the admin role; other options are refused |
meta.send_activity_report(to, days default 7) | (137) Queue a mail with a summary of the current application's activity of the last days and the rows as activity.csv. For the application's automations and its signed-in administrators; empty to: nothing is sent. The E-mail reporting feature's automation calls it |
meta.copy_page(from_app, page, to_app, new_page, name default null, map default '{}') | (137) Create page as copy (owner only); map is {"lov:JOBS": "JOB_TITLES"}: a shared component to use instead of copying it. meta.page_shared_refs(page_id, target_app) lists what a page refers to by name |
meta.wizard_files(table) | (097) The bytea columns and the columns holding their file name, mime type, size and change time |
meta.export_app(alias) | The application as JSON (pgkiln/2 format) |
meta.import_app(json, alias default null) | Import an export, optionally under a new alias; returns the new app id |
meta.hash_password(text) | A bcrypt hash for meta.app_user.password_hash / meta.developer.password_hash |
meta.authenticate(app_id, username, password) | Username on success, NULL otherwise, including when the account has no access to the app (used by the login page) |
meta.account_roles(app_id, username) | The account's roles in an application |
meta.set_password(username, password, change_on_first_use default true) | Set a password (ends the account's sessions) |
meta.expire_password(username), meta.unexpire_password(username) | Require (or no longer require) a new password at the next sign-in |
meta.change_password(app_id, username, old, new, keep_session) | Change a password knowing the current one (used by My account; runtime only) |
meta.api_check() | PostgREST's pre-request function (db-pre-request): rejects tokens whose app doesn't use the current role as its API role, or whose account is inactive or has no access |
Options of meta.generate_page (all optional; column names must be columns of the table):
| Kind | Options |
|---|---|
| all | label (page name and menu entry; default the table's plural label, singular for form), form_label (the title of a form page; default the singular label), icon, nav (add a navigation entry; default true, false for form) |
form | columns (array), mode (normal or modal), return_page |
cards | title, subtitle, body, badge, form_page |
calendar | start, end, title, drag (boolean), form_page |
chart | chart (bar, column, line, area, donut, pie, funnel), label_column, function (count, sum, avg, min, max), value_column |
map | location (geometry, point or lat,lng text) or lat + lng, title, body, report (boolean), form_page |
facets | columns (report columns, array), facets (array), search (boolean), form_page |
master_detail | detail (a table), detail_column (its column referring to this table) |
report_form | form_page (required) |
report | form_page (137: an interactive report alone) |
smart_filters | facets (array), form_page |
tree | id_column, parent_column (proposed: a foreign key to the table itself), label_column, expanded (levels open), form_page |
timeline | title, when, who, body, form_page |
media_list, content_row | title, description, badge (also its colour), misc (content row), form_page |
comments | user, date, comment |
data_load | definition (a data load definition's name: made for the table unless it exists), mode (append, merge, replace), skip_errors |
wizard | columns (array; NOT NULL columns without a default always), steps (1–10), return_page |
search | configs (search configurations by name); with a table: a new configuration on it, and form_page |
tasks | context (my, initiated, admin), completed (boolean) |
workflows | context (initiator, admin) |
select meta.generate_page('shop', 'calendar', 'shop.meeting', 12, '{"form_page": 13, "drag": true}');
select meta.generate_page('shop', 'facets', 'shop.product', 14, '{"facets": ["category_id", "price"]}');
select meta.generate_page('shop', 'master_detail', 'shop.orders', 15);Metadata tables
All in schema meta. id columns are generated; seq orders siblings (default 10).
Application level
app: an application.
| Column | Type | Description |
|---|---|---|
alias | text | URL name (^[a-z][a-z0-9_-]*$), unique |
name | text | Display name |
home_page | int | Page opened by /a/<alias> |
authentication | text | app_users, header, database, custom or none |
custom_auth_function, custom_auth_code, custom_auth_post_code | text | Custom authentication: a function (p_username text, p_password text) returns boolean, or a PL/pgSQL body, and post-authentication code (chapter 8) |
custom_auth_hash_query | text | (204) Custom authentication: or a query with p_username returning the stored password hash (Django pbkdf2_sha256$/pbkdf2_sha1$, bcrypt), checked by the server (chapter 8) |
nav_list, navbar_list | text | A list shown as the navigation menu (instead of nav_entry) and as the navigation bar |
access_control | text | assigned (only accounts with access) or any_user |
local_login | boolean | Offer username and password sign-in |
sso_providers | text[] | Names of identity providers (OpenID Connect or SAML) offered on the login page |
ldap_directories | text[] | LDAP directories the password form checks, after local accounts |
remember_me_days | int | Days a "Keep me signed in" sign-in lasts; NULL = not offered |
mfa, mfa_roles | text, text[] | Two-factor sign-in: off, optional, required or roles (required for mfa_roles) |
pwa, pwa_short_name, pwa_icon, pwa_offline_pages, pwa_offline_submit | boolean, text, bytea, boolean, boolean | Progressive Web App (chapter 17) |
db_role | text | Database role every request runs as |
api_role | text | Database role of REST API tokens for this app (PostgREST switches to it) |
language, languages, language_from | text, text[], text | Primary language, translated languages, browser / user / primary |
date_format, timestamp_format | text | Display masks (e.g. DD-MM-YYYY); NULL: the language's default |
debug | boolean | Show database error details to users |
debug_level | smallint | Debug messages: 0 off, 1, 2, 4, 6 or 9 (APEX levels) |
debug_retention_days | int | Days debug messages are kept (1–90, default 7) |
theme | jsonb | {"accent": "#0b63c5", "header": "#13294b", "nav": "side" | "top", "mode": "auto", "user_choice": true, "styles": [{"name": "Ocean", "accent": "#0b7285", "font": "serif", "font_size": "large", "radius": "small"}], "style": "Ocean", "style_choice": true} (style variants) |
account (the user directory): username (unique, case-insensitive), display_name, email, password_hash (bcrypt; NULL = no password), active, created_at, last_login_at.
app_access: app_id, account_id, roles (text[]); who may use which application.
account_style: account_id, app_id, style ('' = Standard); the style variant a user chose in an application (installation data: not exported).
app_user: a view over account + app_access (id, app_id, username, password_hash, roles, active, last_login_at), kept for compatibility. Inserting creates the account if needed and grants access; deleting revokes access.
app_group_role: app_id, group_name, role; identity-provider group → application role.
authz_scheme: app_id, name (uppercase), type (role / sql), value, error_message.
nav_entry: app_id, parent_id (sub-menu), seq, label, icon, target_page, authz.
lov: app_id, name (uppercase; used as LOV:NAME), query, rest_source (the query then reads the source's rows from rest).
list: app_id, name (uppercase), type (static / sql), query, description (chapter 4).
list_entry: app_id, list_name, parent_id (an entry of the same list), seq, label, icon, target_page, target_items (jsonb), target_url (a path inside the app or an http(s) address), badge, description, condition, authz, build_option.
supporting_script: app_id, name, kind (install / upgrade / deinstall), seq, script (chapter 3).
web_credential: app_id, name (uppercase), description, type (basic / header / bearer / oauth2), username (or client id), header_name, token_url, scope, valid_for (text[] of URL prefixes), secret_enc (encrypted by the server; not readable by the runtime role, never exported) (chapter 19).
rest_source: app_id, name (uppercase), description, url (with {param}), method, credential, headers (jsonb), params (jsonb), body, row_selector, columns (jsonb), cache_seconds, timeout_s, max_rows (chapter 19).
app_item: app_id, name, description.
app_process: app_id, seq, name, point (after_login / before_page), code, authz.
app_computation (102): app_id, seq, item_name, point (after_authentication / before_header / after_submit), type, expression, condition_type, condition_expr, condition_value, authz, build_option, comments (chapter 6).
shortcut (103): app_id, name (uppercase, unique per app), type (text / html / function_body), value, comments (chapter 2).
report_query (104): app_id, name (uppercase, unique per app), description, query, format (pdf / xlsx / csv / json / xml / html), layout, file_name, title, authz, comments (chapter 16).
component_group (105): app_id, name, description, members (text[] of kind:name) (chapter 3). meta.app.component_settings (105): report_rows, grid_rows, popup_lov_rows, lov_max_rows, rating_max (chapter 3).
build_option: app_id, name (uppercase, unique per app), status (include / exclude), description (chapter 6). meta.build_option_on(app_id, ref) tells whether a component with that build_option value is part of the application.
Page level
page
| Column | Description |
|---|---|
app_id, page_no | Unique together |
name, title | Title supports &ITEM. |
requires_auth | boolean |
parent_page | Breadcrumb parent |
mode | normal / modal |
protection | checksum / unrestricted |
authz | Authorization scheme |
page_template | standard, left_side_column, right_side_column, minimal (a sign-in page) or (sprint 241) no_navigation (chapter 4) |
build_option | NAME / !NAME: only while the build option is included / excluded |
Regions, items, buttons, dynamic actions, validations, processes, computations, branches, navigation entries and application processes have the same build_option column.
region
| Column | Description |
|---|---|
page_id, seq, title | |
type | report, grid, form, chart, cards, calendar, facets, smart_filters, display_selector, map, tree, template_component, list, data_reporter, form_designer, json_form, ai_assistant, tasks, workflows, static, dynamic |
source | SELECT (or HTML for static) |
table_name, pk_column | For form and grid |
pk_item | For form: the item holding the key |
columns | 1–12 |
template | standard, plain, collapsible |
condition, authz | Visibility |
config | Attributes per type (chapter 4) |
rest_source | A REST data source the region reads; source is then SQL over rest (chapter 19) |
template_options | text[]: CSS classes from a fixed list (template options) |
position | banner, breadcrumb, left, body (or null), right, footer (display positions) |
item: page_id, region_id, seq, name, label (&ITEM. substitutions), placeholder (sprint 241), type, lov, source_column, default_value, required, help, readonly_condition, authz, config (chapter 5).
button: page_id, region_id, seq, name, label, action (submit / redirect / da / document / menu), target_page, target_items (jsonb), condition, authz, hot, confirm, menu (jsonb, for menu), badge, badge_query (chapter 6), template_options (text[], template options), slot (a region button's button position: create, edit, change, copy, help, up, previous, close, delete, next or region / null).
dynamic_action: page_id, seq, name, event, trigger_element, condition_type, condition_value, action, affected_items, affected_region_id, code, items_to_submit, message, css_classes, authz (chapter 7).
validation: page_id, seq, name, item_name, type (not_null / sql / regex), expression, message, when_button.
process: page_id, seq, name, type (form_dml / grid_dml / sql / data_load / invoke_api), region_id, code, config (jsonb, for data_load and invoke_api), point (submit / load), when_button, authz, success_message.
computation: page_id, seq, item_name, point (before_header / after_submit), type (static / item / sql_query / sql_expression / function_body), expression, condition_type, condition_expr, condition_value, authz (chapter 6).
branch: page_id, seq, name, point (after_processing / before_header), when_button, condition_type, condition_expr, condition_value, target_type (page / url), target_page, target_items (jsonb), target_url, authz (chapter 6).
Runtime and instance
| Table | Contents | Readable by the runtime role |
|---|---|---|
session | Sessions: token_hash (SHA-256 of the cookie), app_id (NULL = builder), username, roles (resolved at sign-in), csrf_token, state (jsonb session state), created_at, last_seen | yes |
activity_log | at, app_id, page_no, username, event (page_view, page_prefetch (168: a page fetched for offline use), login, login_failed, login_locked, login_unlocked, logout, error, forbidden, api_token, password_expired, password_changed; builder: lock_broken, lock_released (233: a removed developer's lock, or one of a name that is no developer), supporting_objects, sample_data, …), ip, elapsed_ms, detail | yes (insert/select) |
debug_view | Debug messages: one row per recorded request: app_id, page_no, username, session_id, method, path (without the query string), status, level, started_at, elapsed_ms, entries. Written through meta.debug_save() (runtime role only), not exported | no |
debug_message | The entries of a recorded request: view_id, seq, elapsed_ms (since the start), duration_ms (timed steps), level, component, message | no |
web_request_log | Web requests from SQL: app_id, status, the request (url or source + params, method, headers, body, credential name, timeout_s), requested_by, times, the response (status_code, response_url, response_headers, response_body), message; (160) attempts, max_attempts, next_attempt_at, lease_until, ordering_key, idempotency_key, callback and its state. Kept 24 hours (given up: 7 days), not exported | no (through meta.web_response) |
webhook_event | (161) Events received by webhook handlers: app_id, module, path, event_key (the sender's id, unique per handler), headers, content_type, body (the raw bytes), received_at, purge_after, state, attempts, error. Removed after the handler's retention, not exported | no |
push_key | The VAPID key pair of an application with push notifications: public_key, private_key (encrypted with PGKILN_SECRET_KEY). Not exported | no |
push_subscription | Devices with notifications on: app_id, username, endpoint (the push service URL), the device's keys p256dh and auth, user_agent, created_at, last_sent_at, failures. Not exported | no (through meta.has_push_subscription) |
push_message | Push notifications from SQL: app_id, username, title, body, url, tag, urgency, ttl_s, status, attempts, devices, delivered, message, requested_by, times. Kept 7 days, not exported | no |
ai_service | AI services of the installation: name, provider (anthropic, openai, gemini, openai_compatible: 121), model, effort, refusal_fallback, max_tokens, timeout_s, base_url, api_key_enc (encrypted with PGKILN_SECRET_KEY, write-only), enabled. Not exported | no |
app_ai_service | Which applications may use which AI service, with daily limits max_requests and max_tokens (null: no limit). Not exported | no (through meta.ai_available) |
ai_usage | One row per AI request: at, app_id, page_no, username, service, provider, model, source, input_tokens, output_tokens, duration_ms, status, message (an error class, never prompt or answer text). Not exported | no |
ai_tool_call | (121) Every tool call of an AI assistant or agent: at, app_id, page_no, region_id, username, agent, tool, type, arguments (the model's, cut to 4 KB), status (ok, error, refused), duration_ms, message. Kept 30 days, not exported | no |
embedding_queue | (136) Rows whose vector column the server re-embeds: app_id, provider, tbl (the table's oid), vector_column, key_column, source_columns, key_value, queued_at, next_at, attempts, last_error. Filled by meta.embedding_enqueue triggers and Backfill; not exported | no |
ai_conversation | AI assistant conversations: one per session and region (messages: the provider's history, turns: what the page shows); deleted with the session. Not exported | no |
ai_table_note | Descriptions of tables and columns for models (App Builder AI): schema_name, table_name, column_name ('' for the table), note. Installation data, not exported | no |
blueprint | Saved blueprints: name, spec (the JSON), app_id (the application last created from it), created_by. Builder data, not exported | no |
builder_ai | The App Builder's AI service (one row, service_id; administrators). Not exported | no |
ai_request | AI requests from SQL and their answers, kept 24 hours. Not exported | no (through meta.ai_result) |
developer | Builder accounts (is_admin: manages developers, breaks locks) | no |
builder_lock | Page (page_no) and application (page_no 0) locks: locked_by, locked_at, note | no |
dev_comment | Developer comments on an application (page_no 0) or page: author, body, created_at | no |
auth_provider | OpenID Connect and SAML providers (protocol; SAML: idp_sso_url, idp_cert): name, display_name, issuer, client_id, client_secret, scopes, username_claim, groups_claim, auto_create, enabled | no |
account_identity | Links an account to a provider's subject (provider_id, subject, account_id) | no |
sso_pending | Sign-ins in progress (state, PKCE verifier, nonce or SAML request ID; kept for 10 minutes) | no |
saml_request | SAML AuthnRequest IDs awaiting their response (used once) | no |
ldap_directory | LDAP directories: URL, service account (write-only password), user and group search | no |
task_definition | Approval and action task definitions per app | yes (read) |
rest_module | REST modules per app: name, title, handlers (JSON) | yes (read) |
workflow_definition | Workflow definitions per app: the active version's steps as JSON, a development version and the inactive ones | yes (read) |
workflow, workflow_event | Workflow instances (state, current step, variables, their version and a copy of its steps) and their history; reached through meta.workflows / meta.workflow_events and the functions | no |
workflow_branch | The parallel branches of workflow instances (step, wait, task and state of each) | no |
task, task_event | Tasks and their history; reached only through meta.tasks, meta.task_events and the meta.*_task functions | no |
list, list_entry | Lists and their entries per app (see above) | yes (read) |
supporting_script | Supporting objects per app (see above) | no |
document_template | Document templates per app: name, description, query, template, layout, filename, authz | yes (read) |
ldap_identity | Links an account to a directory entry (directory_id, subject = entryUUID or DN) | no |
persistent_login | "Keep me signed in" tokens: token_hash, account_id, app_id, groups, method (+2fa after a second step), expires_at | no |
account_factor, account_recovery_code | An account's authenticator apps (secret encrypted with the instance key) and recovery codes (SHA-256) | no |
instance_setting | Secrets, e.g. the URL checksum key | no |
setting | Account settings: password_min_length, password_require_mixed, password_lifetime_days | yes (read) |
text_message | Per app: name, language, text | yes |
translation | Per app and language: source (primary-language text) → target | yes |
temp_file | Uploaded files per session (deleted with the session; at most 20 per session). Read through the view meta.temp_files | no (through the view) |
Outside meta: public.pgkiln_migration (applied migrations), public.pgkiln_seed (applied example scripts) and public.pgkiln_install_log (each migration run that applied or failed a file: started_at, finished_at, version, kind install/upgrade, applied files, status, error, db_user), shown under Workspace utilities → Installation.
Retention: expired sessions are purged automatically; debug messages after the application's debug_retention_days (and at most 5000 requests per application), and web requests after 24 hours (at most 500 per application), and AI requests from SQL after 24 hours, by the scheduler. The AI usage log (meta.ai_usage) is kept until you delete from it. The activity log is kept until you delete from it, for example with a scheduled delete from meta.activity_log where at < now() - interval '90 days'.
URL parameters
| Parameter | Used by | Meaning |
|---|---|---|
<ITEM>=value | pages | Set an item (the page's items are cleared first) |
cs | pages | Checksum of the item values |
clear=1 | pages | Clear the page's items |
dialog=1 | pages | Render for display inside a modal dialog |
r<id>_q | report, grid | Search text |
r<id>_s, r<id>_d=desc | report, grid | Sort by column position, descending |
r<id>_p | report, grid | Page number |
r<id>_n | report | Rows per page |
r<id>_a=fn|column | report, grid | An aggregate (repeatable); fn is sum, avg, count, min, max |
r<id>_sel=value, r<id>_selcs | master grid | Select a master row: the value goes into the grid's select_row item; selcs is its signature (made by the runtime) |
r<id>_dup=key | grid | Show the row with this key again as a new, unsaved row (Duplicate without JavaScript) |
r<id>_f=column|op|value | report | Column filter (repeatable); op is eq, ne, contains, not_contains, gt, ge, lt, le, null, not_null |
r<id>_x_<column>=value | report + facets, smart filters | Facet selection (repeatable) |
r<id>_xn_<column>=1 | report + facets | Exclude the selected values (facet with exclude) |
r<id>_rg_<column>=from|to | report + facets, smart filters | One of a range or star facet's ranges (~: the custom range) |
r<id>_rf_<column>, r<id>_rt_<column> | report + facets | Custom range from / to, inclusive (facet with custom) |
r<id>_csv=1 | report | Download CSV |
r<id>_xlsx=1 | report | Download Excel |
r<id>_load=1 | lazy region | Show the region in the page (the link of its placeholder without JavaScript) |
r<id>_pdf=1 | report | Download PDF |
r<id>_m=YYYY-MM | calendar | Month shown |
Icons
136 line icons of pgkiln's own (public/icons.svg, listed below), and (0.31) the Lucide set of about 1,600 more in the same 24×24 line style (lucide.dev/icons, ISC licence, shipped with pgkiln; APEX: Font APEX), usable in navigation entries, list entries, cards (icon column) and template components. An icon value is a name followed by optional modifiers:
users pgkiln's own icon
car-front a Lucide icon (pgkiln's own wins where both have the name)
fa-car-front fa-lg Font APEX style: the fa- prefix is dropped, so Font APEX names work where Lucide has the icon
refresh spin modifiers: xs sm lg 2x 3x 4x · spin pulse · rotate-90 rotate-180 rotate-270 · flip-h flip-v
truck flip-h success · colours success warning danger info mutedUnknown names show no icon; unknown modifiers are ignored. spin and pulse stand still for users who ask for reduced motion. Each Lucide icon is its own small file (/static/icon/<name>.svg, cached for good, versioned with the package), so a page loads only the icons it shows. In the builder the icon picker shows pgkiln's icons; its filter box also searches the Lucide icons by name and search word (vehicle finds car, bus, …), and Or any icon, with modifiers takes any value (checked on save).
home users user building chart table list calendar shield history settings org gridfile check menu logout plus download filter database code activity inbox closechevron edit layers bolt key play upload printer clock search alert map scancloud-off arrow-up arrow-down arrow-left arrow-right chevron-down chevron-up chevron-leftexternal refresh undo redo compass info help check-circle x-circle plus-circle minusban power trash copy save share send link paperclip lock unlock eye eye-off bellstar heart bookmark tag flag pin globe hash at chat comments phone megaphonefolder archive image camera video book clipboard note qr barcode briefcase cartcredit-card wallet coins percent calculator receipt truck box store factory targettrophy gift id-card user-plus graduation lightbulb pie-chart line-chart trend-uptrend-down kanban dashboard sliders server cloud wifi cpu tool car plane routehome-heart hospital heart-pulse leaf sun moon droplet thermometer
HTTP endpoints
| Method and path | Purpose |
|---|---|
GET /a/:alias/:page | Show a page (and CSV downloads) |
POST /a/:alias/:page | Submit a page |
POST /a/:alias/:page/da/:id | Run a server-side dynamic action (JSON) |
POST /a/:alias/:page/lov/:item | Re-render a cascading list (JSON) |
GET/POST /a/:alias/login, POST /a/:alias/logout | Sign in and out |
GET /a/:alias/sso/:provider | Start single sign-on with a provider |
GET /sso/callback/:provider | OpenID Connect redirect URI |
POST /sso/saml/:provider, POST /sso/saml/:provider/finish | SAML assertion consumer service (and the same-site step after it) |
GET /sso/saml/:provider/metadata | SAML service provider metadata |
GET/POST/PUT/PATCH/DELETE /a/:alias/rest/:module/…, GET …/openapi.json | REST module endpoints (bearer token) and their OpenAPI description |
POST /a/:alias/workflows/:id | Workflow console action (terminate, retry) |
POST /a/:alias/tasks/:id | A task list action (claim, release, approve, reject, complete, delegate, cancel, comment) |
GET /a/:alias/manifest.webmanifest, /sw.js, /icon-192.png, /icon-512.png, /offline | Progressive Web App files (only when the app has PWA on) |
any page ?doc=NAME | Download a document template filled with the page's values |
POST /a/:alias/account/devices | Sign out on all devices ("Keep me signed in") |
POST /a/:alias/password | Change an expired password while signing in |
GET/POST /a/:alias/login/2fa, POST /a/:alias/login/2fa/done | The second step of signing in: a code, or adding the first app and seeing the recovery codes |
POST /a/:alias/account/2fa/start, …/cancel, …/confirm, …/codes, …/codes/confirm, …/:id/delete | My account → Two-factor sign-in |
GET/POST /a/:alias/account, POST /a/:alias/account/password, POST /a/:alias/account/theme, POST /a/:alias/account/style | My account, own password, the light/dark switch, the style variant switch |
POST /a/:alias/tz | The browser's time zone for the session (automatic time zone; sent by app.js, CSRF token required) |
any page ?lang=xx | Switch the language for the session |
POST /a/:alias/telemetry | (0.72) Browser spans of a page whose trace goes to an OpenTelemetry collector (sent by app.js; a signed token of the page, 204) |
GET /metrics | (0.72) Metrics in the Prometheus text format, when switched on: an administrator's builder session or Authorization: Bearer <metrics token> (chapter 1) |
GET /healthz | ok when the database is reachable (503 otherwise) |
/builder/... | Builder |
PostgREST (separate service, API_URL) | REST API of each app's api schema, see chapter 13 |
/static/... | CSS, JavaScript, icons |