Buttons, validations, processes and page logic
Buttons
| Property | Meaning |
|---|---|
name | The request (SAVE, CREATE, APPROVE, …); uppercase. Processes and validations can run "when button pressed" |
label | Button text, translated like other texts; (sprint 249) &ITEM. substitutions are replaced, HTML-escaped, as in item labels: Save &P3_ENAME., Back to page &APP_PREVIOUS_PAGE. (menu entries' labels too) |
action | submit: submit the page with this request. redirect: go to target_page without submitting. da: do nothing except trigger dynamic actions. document: download a document template. menu: a menu of links and submit requests |
target_page | For redirect: where to go. For submit: where to go after success when no branch applies; empty = stay on the page |
target_items | For redirect: items to set on the target page, e.g. {"P3_ID": "&P2_ID."} |
target_region | (sprint 238) For redirect: the static ID of an inline dialog or drawer region it opens, on this page (empty target_page), else on the target page once it shows |
condition | SQL expression; the button only exists when it is true |
authz | Authorization scheme |
hot | Primary styling. The first visible hot submit button is also the one Enter presses |
confirm | A confirmation question before the action (e.g. "Delete this record?") |
region_id, seq | Placement: region header (reports, cards, …), region footer (forms, static) or page bottom |
menu | For menu: the entries (JSON), see below |
badge, badge_query | A small count or label on the button, see below |
build_option | Only part of the application while the build option is included |
The condition and authorization are checked again when the button is pressed: a request for a button that isn't visible to this user in this state is refused (403) and logged. So a condition like :P3_ID is null on Create really does prevent creating from an existing record.
In a modal dialog, a redirect button whose target is not a modal page (typically Cancel) simply closes the dialog.
Staying in the dialog
(sprint 240) A submit from a modal dialog page closes the dialog. A button with Stay in the dialog (stay_in_dialog, Behaviour group) shows the dialog page again after its processes instead, with their success message, so one dialog can hold several steps: upload → preview → import. Validation errors keep the dialog open as always. Rules:
- A close_dialog process that runs still closes the dialog.
- When a branch applies, the branch decides: one with Stay in the dialog (Target group) opens its target inside the dialog (also a
before_headerbranch of a dialog page); one without closes the dialog as before. A branch to another application never stays. - An editable grid's own Save stays in the dialog (as an APEX interactive grid's Save does).
- Outside a dialog (the page opened by itself, or without JavaScript) the option changes nothing.
The Advisor notes Stay in the dialog on a page that isn't a modal page, and on a branch to another application. HR example, page 67 (Import contacts, opened from page 35): Read the file stays, Start over stays through its branch, the grid's Save stays, and Import closes the dialog (examples/hr/hr_103_import_dialog.sql).
Menu buttons and badges
A button with action menu opens a dropdown (an HTML <details> element, so it works without JavaScript). menu is a JSON array of at most 20 entries; each is a link to a page of the application, a submit request or an action that runs dynamic actions:
[{"label": "Leave requests", "page": 6, "icon": "list"},
{"label": "Details", "page": 3, "items": {"P3_EMPNO": "&P22_EMPNO."}},
{"label": "Start over", "request": "RESET", "confirm": "Clear the form?", "authz": "ADMIN"},
{"label": "Export", "action": "EXPORT", "icon": "download"}]| Key | Meaning |
|---|---|
label | The entry's text (1–100 characters) |
page, items | A link: the page and the items to set (signed with a checksum, like any link) |
request | A submit: the page is submitted with this request, as if a button of that name was pressed. Validations, processes and branches with when_button see it |
action | Runs the dynamic actions of event menu_entry with this name (capitals, digits and _) as trigger (APEX: Menu entry chosen) |
confirm | A confirmation question first |
authz | The entry only exists for users who pass this authorization scheme |
icon | An icon name |
A request entry is allowed on submit only when the menu button itself is visible to the user and the entry's authorization passes; a request that is also the name of a real button on the page follows that button's condition and authorization instead.
A badge is a short value shown on the button (a count of open items, "new", …). badge is text with &ITEM. substitutions (an empty result shows no badge); badge_query is a SELECT whose first column of the first row is shown, and wins when both are set. The query runs as the application's database role with bind variables, like any region source. (sprint 165) With live badges on, a badge query's value is refreshed while the page is open.
What happens on submit
POST ──> CSRF check ──> page authorization ──> "before page" app processes
──> visibility (with the state as rendered) ──> button allowed?
──> copy posted values of editable items into session state
──> computations (after_submit) ── error ──> roll back, re-show page with message
──> validations (DELETE: its own only) ── error ──> re-show page with messages (422)
──> processes, in sequence ── error ──> roll back, re-show page with message
──> branches (after_processing): the first that applies
──> COMMIT ──> success message ──> redirect to the branch's target,
else to the button's target page, else to the pageWhen the page is shown (GET), the order is: before_header branches (one that applies redirects at once), form fetch, before_header computations, load processes, rendering.
Everything from the first validation to the last process runs in one transaction: if a later process fails, earlier inserts and updates are rolled back too.
Validations
APEX's validation types (sprint 154–155; APEX: Validation → Type):
type | APEX | Passes when |
|---|---|---|
sql | Expression | expression (a SQL boolean expression, binds allowed) is true |
exists / not_exists | Rows returned / No rows returned | the query in expression returns a row / no row |
function_body | Function Body (returning Boolean) | the PL/pgSQL body in expression returns true |
function_error | Function Body (returning Error Text) | the body returns null or empty; otherwise its text is the error message |
not_null | Item is NOT NULL | the associated item has a value |
not_null_or_zero | Item is NOT NULL or zero | the item has a value that is not zero |
not_zero | Item is NOT zero | the item is empty or not zero |
no_spaces | Item contains no spaces | the item has no white space |
alphanumeric | Item is alphanumeric | the item has only letters and digits (any script) |
numeric | Item is numeric | the item is a number (a number item's format mask is read back first) |
valid_date | Item is a valid date | the item is a date in the application's date format, or ISO |
valid_timestamp | Item is a valid timestamp | the item is YYYY-MM-DD HH:MI[:SS] (or with a T) |
equals / not_equals | Item = Value / Item != Value | the item's value is / isn't expression |
in_list / not_in_list | Item is (NOT) contained in Value | the item's value is / isn't one of expression's values, colon separated (CLERK:ANALYST) |
chars_only / chars_any / chars_none | Item contains only / at least one / none of the characters in Value | checked against the characters of expression |
regex | Item matches Regular Expression | the item's value matches expression (a POSIX regular expression, checked in Postgres) |
The format checks (no_spaces … valid_timestamp, chars_*, regex, not_zero, not_in_list, not_equals) pass an empty item, as APEX's do: add not_null (or Value required) when it must have one. The database refuses a type without the associated item or expression it needs. The SQL types run as the application's role; the Advisor names SQL validations a type says exactly (:P3_SAL is not null → not_null).
Plus: every required editable item must have a value.
| Property | Meaning |
|---|---|
item_name | The message is shown next to this item (otherwise at the top of the page) |
message | The error message; (sprint 166) &ITEM. substitutions are filled in with the submitted values (The name &P3_NAME. is taken.) |
when_button | Only validate for this request. A DELETE request runs only the validations with when_button DELETE (e.g. "approved requests can't be deleted"), not the item checks |
condition_type, condition_expr, condition_value | Only validate when the server-side condition holds, e.g. request_in SAVE,CREATE (sprint 154) |
authz | Only validate for users the authorization scheme lets through (sprint 155) |
always_execute | Also validate for a DELETE request (APEX: Always Execute) |
display_location | Where the error shows: inline_and_notification (next to the item and at the top), inline (empty: next to the item, with "correct the errors below" at the top) or notification (at the top only). Without an associated item it is at the top |
Example: commission only for salesmen.
:P3_COMM is null or :P3_COMM::numeric = 0 or :P3_JOB = 'SALESMAN'Validations in the application are for usability. Rules that must always hold belong in the database (constraints, triggers, functions), where they also protect other access paths. The two combine well; see error handling below.
Processes
type | What it does |
|---|---|
form_dml | Insert/update/delete the row of a form region (see forms); on a REST data source through its operations (chapter 19) |
grid_dml | Save the changes of an interactive grid region; runs on the grid's Save button (a grid on a REST data source saves through the source's operations) |
sql | Run code: one or more SQL statements with bind variables |
data_load | Load the CSV/XLSX file of a file item into a table (chapter 16) |
invoke_api | Call a web service (a REST data source or a URL, with a web credential) and put values of the response into items (chapter 19) |
download | Send a file made by a query instead of the page (below) |
chain | An execution chain: run the processes that name it as their chain, in sequence, optionally in the background (below) |
workflow | Start a workflow, or terminate or retry an instance (below) |
send_push | A push notification to a user's devices (below) |
send_notification | (sprint 165) An in-app notification: the user's notification bell (below) |
plugin | A process plug-in: calls its PL/pgSQL function with the attribute values (config: {"plugin": "log_event", "attributes": {"DETAIL": "&P40_NOTE."}}, &ITEM. filled in) as the application's role; the text it returns is the message |
| Property | Meaning |
|---|---|
point | submit (after validations) or load (when the page is shown, after form fetch) |
when_button | Only for this request (empty = every submit with a button) |
condition_type, condition_expr, condition_value | Only when the condition holds (server-side condition, as for computations and branches) |
parent_process | The name of a chain process on the page: this process then runs only inside that chain |
region_id | The form or grid region, for form_dml / grid_dml |
config | Settings of a data_load, invoke_api, download, chain, workflow, send_push or plugin process (JSON) |
success_message | Shown after the redirect; messages of several processes are joined. (sprint 166) &ITEM. substitutions are filled in with the values after the process (Order &P3_ID. created.) |
open_region | (sprint 238) submit: the static ID of an inline dialog region the page that comes back opens, after a submit in which this process ran ("Save and add another"); a branch's open_region wins |
authz | Skipped when the user isn't authorized |
seq | Order |
Calling PL/pgSQL
Keep business logic in database functions and call them from a process:
select hr.request_leave(:P7_START_DATE::date, :P7_END_DATE::date, :P7_REASON) as p7_idIf the last statement returns a row, each column named like an item (page item or application item) sets that item. Here the new request id lands in P7_ID. Casting binds (::date, ::int) selects the right function signature.
Procedures work too (call my_proc(:P1_X)), as do several statements separated by ;. For DO blocks, read items with meta.v('P1_X').
A web request queued in a process with meta.web_request() is made by the server right after that process, so the next process can read meta.web_response(id); the process that queued it can't wait for it. (sprint 240) The same holds for Ajax callbacks (also a chain of them) and execute_sql dynamic actions, within 30 seconds per call. A request with a callback or an ordering key is sent after the submit commits instead, with retries: the outbox (sprint 177).
Error handling
In PL/pgSQL, raise errors with messages written for the end user:
if p_end < p_start then
raise exception 'The end date must be on or after the start date.'
using column = 'end_date'; -- optional: show the message on this field
end if;- The message (SQLSTATE
P0001) is shown as written, next to the item whosesource_column(or name) matchescolumn, or at the top of the page. - Unique, foreign-key, not-null and check violations get friendly messages.
- Other errors show "An unexpected error occurred (reference #id)"; the details are in the activity monitor (or on screen in debug mode).
All changes of the submit are rolled back, and the page is shown again with the entered values so the user can correct them.
A process that fails while the page is shown (point load) is rolled back to where it started (sprint 209): its error shows at the top of the page, the load processes after it don't run, and the rest of the page (regions, lists of values, conditions) still works.
Error handling function (Settings → Errors and sessions; APEX: Error Handling Function). A function of your own rewrites every error message users see: those raised in PL/pgSQL, the friendly constraint messages and the "reference" messages of unexpected errors.
create function sales.error_message(e jsonb) returns jsonb language plpgsql as $$
begin
if e->>'constraint' = 'order_customer_fk' then
return jsonb_build_object('message', 'Choose an existing customer.');
end if;
if (e->>'internal')::boolean then
return jsonb_build_object('message', 'Something went wrong. Quote ' || (e->>'reference') || ' to the help desk.');
end if;
return null; -- keep the message
end $$;It gets message (what pgkiln would show), original_message, code (SQLSTATE), constraint, table, column, detail, hint, component (where it happened, e.g. process "Save order"), page, user, internal (true for an unexpected error) and reference (its activity log id), and returns {"message": "…"} or null. It runs as the application's role, in a transaction of its own, with a 2-second limit; when it fails or returns null the message stays as it was. Debug mode shows the real error and doesn't call it.
Ajax callbacks
A process with point ajax runs when JavaScript calls it by name, pgkiln.server.process('NAME') (APEX: On Demand processes, apex.server.process), and answers JSON; see chapter 7. (sprint 240) It may also be a chain of SQL processes, and the web requests it queues are made right after it (or after each step of the chain), so the callback answers with their responses.
Debug messages
Like APEX's debug, pgkiln can record what each request of an application did and how long every step took. Set the debug level under Activity → Debug messages (or follow the link in the application's settings):
| Level | Records |
|---|---|
| 0 | Nothing (the default): no extra work and no writes |
| 1 errors | Errors: failed processes and computations, database errors (also those shown as "reference #id"), unhandled errors |
| 2 warnings | Also refused requests (403), failed validations and SQL WARNINGs |
| 4 information | Also the request (method, path, the names of URL parameters), the steps of the page (authorization, application processes, form rows, computations, load and submit processes, visibility, rendering) with their durations, the pressed button and branches |
| 6 trace | Also each region, process, application process and computation with its duration, and the session (page, user, language, time zone) |
| 9 everything | Also the posted item values, computed values, skipped processes, hidden regions and other SQL notices |
A developer can also switch debug on for their own session only, from the developer toolbar on the running application: the application stays out of debug for everyone else.
Each recorded request lists its entries with the time since the start of the request and, for timed steps, their duration. Add your own from any application SQL (processes, region sources, conditions, your PL/pgSQL functions), as with apex_debug.message:
select meta.debug('Recalculating the totals for ' || :P3_DEPTNO); -- level 4
perform meta.debug(6, format('%s rows changed', n)); -- inside PL/pgSQL
if meta.debug_enabled(9) then -- skip expensive texts
perform meta.debug(9, (select string_agg(ename, ', ') from hr.emp));
end if;meta.debug() raises a NOTICE that the runtime collects on its connection, so the messages written before an error, or in a transaction that rolls back, are kept too. With the level below the message's, it returns at once. Texts are cut at 4000 characters, and a request keeps at most 2000 entries.
Background work and REST requests (sprint 218; APEX debugs jobs too): with the application's debug level on, three more kinds of work are recorded with the page views, each with its meta.debug() messages:
| Kind | Recorded as | Entries |
|---|---|---|
| An automation's run (scheduled or Run now) | AUTOMATION automation "name", the user it runs as | the run, the actions with their duration (level 6), each failed row (level 2), the outcome; status 500 when the run failed |
| A background process chain | JOB process job 12: "chain", the page and the user who started it | the chain's processes as on a page, the outcome (status 500: failed and rolled back) |
| A REST module request | GET /a/hr/rest/v1/employees/7839, the caller | the module and handler, the names of the parameters (never their values, nor the body's), a refusal or error, the status |
Activity → Debug messages filters them with Kind (page views, REST requests, background work) and tags each row. A developer's session debug from the toolbar doesn't reach them: a job runs after the request, without the session.
The entries are stored after the response is sent (meta.debug_view, meta.debug_message) and deleted after the retention you choose (1–90 days, default 7; at most 5000 requests per application). Recording costs some time and space on every request: turn it off when you are done, and don't leave it on in production.
What is and isn't recorded:
- Only developers (in the builder) see debug messages; application users and application roles can't read the tables. Messages of
meta.debug()hold whatever your SQL writes into them: don't write secrets. - Values of password items are never recorded, at any level; URL parameter values and the query string are left out (only their names). Posted and computed item values appear at level 9 only, cut at 200 characters.
Download
A download process answers the request with a file instead of the page (APEX: Download). Its code is a query that returns the file's content (bytea, or text sent as UTF-8), its file name and its MIME type, by default the first three columns:
select content, filename, mime_type from hr.emp_document where empno = :P28_EMPNO::intOne row is sent as it is; several rows go into one zip file (duplicate names get " (2)"). No rows: the page shows "There is no file to download". config (all optional):
| Key | Meaning |
|---|---|
content_column, filename_column, mime_column | Column names, when not the first three |
zip_name | Name of the zip file, &ITEM. substitutions allowed (default download.zip) |
disposition | inline lets a browser show a single image or PDF; everything else is an attachment |
On submit, the file is the answer to the button (the page stays as it was in the browser); on load, the file is sent instead of the page (a download page, e.g. linked with item values). The query runs as the application's database role, like every process, so grants and row level security decide what can be downloaded. File names lose path separators and control characters; a MIME type that doesn't look like one becomes application/octet-stream; the response is never sniffed (nosniff), is sandboxed by its Content-Security-Policy and isn't cached. At most 1000 files and 100 MB per download.
Data export
With {"export": "<format>"} the query returns rows, and the download is those rows as one file (APEX: APEX_DATA_EXPORT): csv, json, xml, html, xlsx (Excel) or pdf.
{"export": "xlsx", "file_name": "employees-&P43_DEPTNO.", "title": "Employees"}| Key | Meaning |
|---|---|
export | The format |
file_name | The name without extension, &ITEM. substitutions allowed (default: the process name) |
title | The title of an HTML or PDF file |
layout | A report layout for the PDF (paper, margins, logo) |
separator | CSV: one character instead of , |
Column names are the headings (hire_date → Hire Date, translated like report headings in Excel and PDF). Excel keeps numbers and dates as numbers and dates; Excel and PDF hold at most 100,000 rows. From SQL, meta.data_export makes the same CSV, JSON, XML and HTML (below).
Execution chains
A chain process runs its children: the processes of the page whose parent_process is the chain's name, in their sequence, each with its own button, condition and authorization (APEX: Execution Chain). The chain itself has a point, button, condition and authorization like any process; a child's point doesn't matter. A chain can contain chains (five levels deep). A failing child stops the chain and, like any failing process, rolls back the whole submit.
With config {"background": true} the chain runs in the background: the submit only queues it (in the same transaction, so nothing is queued when the submit fails) and the server runs it shortly after, in one transaction as the application's role, with the user who submitted as :APP_USER / meta.app_user() and their roles (meta.has_role). Its binds are the page's and the application's items as they were when it was queued (passwords left out); what the processes set isn't written back to the session. form_dml, grid_dml, data_load and download need the request and can't run in the background (the job fails with a message).
config key | Meaning |
|---|---|
background | true: queue the chain as a background job |
status_item | An item that receives the job's id |
The job's state is visible to the developer in the page designer (the chain's Jobs tab: the last runs for every user) and to the user through the view meta.process_jobs (the user's own jobs: id, name, state = queued / running / completed / failed, steps_done, steps_total, current, message, error, times), for example in a report region. Several pgkiln servers can share the queue: each job is claimed once (FOR UPDATE SKIP LOCKED). A job whose server stopped while running it is marked failed after two minutes rather than run twice. Servers that should not run background processes set BACKGROUND_PROCESSES=off; PROCESS_JOB_INTERVAL_S (default 10) is how often a server looks for jobs besides being woken (NOTIFY pgkiln_process_job). Finished jobs are kept for 30 days.
Workflow processes
A workflow process starts a workflow or acts on an instance (APEX: Workflow process), without SQL:
{"action": "start", "definition": "ONBOARDING", "version": "2", "detail_pk": "&P28_EMPNO.",
"variables": {"ENAME": "&P28_ENAME.", "SAL": "&P28_SAL."}, "id_item": "P28_WORKFLOW_ID"}
{"action": "terminate", "instance": "&P28_WORKFLOW_ID.", "comment": "Stopped from the toolkit."}
{"action": "retry", "instance": "&P28_WORKFLOW_ID."}version is optional: the active version, or an inactive or development version by its label. Item values are passed as query parameters, never as SQL. The new instance's id goes into id_item. Terminating and retrying check, in the database, that the user may (the initiator or the workflow's administrator for terminate, the administrator for retry). From SQL, the same is meta.start_workflow_version(name, version, detail_pk, variables).
HR example, page 28 (Employee toolkit). Business card downloads a vCard made by a query; Documents downloads the employee's documents, several in a zip file; Onboard is a chain that looks up the employee (a sql child) and then starts the ONBOARDING workflow (a workflow child); Stop onboarding terminates it; Year-end check is a background chain whose jobs the region "My background jobs" lists from meta.process_jobs.
Send e-mail
A send_email process (APEX: Send E-Mail) queues a mail through the application's mail service, without SQL:
{"to": "&P5_EMAIL.", "cc": "&P5_MANAGER_EMAIL.", "subject": "Order &P5_ID. shipped",
"body": "Dear &P5_NAME., your order is on its way.",
"body_html": "<p>Dear &P5_NAME.,</p><p>your order is on its way.</p>",
"attachments": "select content, filename, mime from sales.invoice where order_id = :P5_ID"}or with an e-mail template:
{"to": "&P5_EMAIL.", "template": "ORDER_SHIPPED", "placeholders": {"NAME": "&P5_NAME.", "ORDER_ID": "&P5_ID."}}Without a mail service the process raises an error and the submit is rolled back. When the mail is optional, give the process the condition sql meta.mail_available() (sprint 166): it runs only when the application has an enabled mail service with a From address.
to, cc, bcc (several addresses separated by commas), from, reply_to, subject and body take &ITEM. substitutions as they are; in body_html the item values are HTML-escaped. attachments is a SELECT (binds allowed) with the columns content (bytea), filename and mime, one attachment per row; (sprint 237) a document template drawn as PDF; or a list of both:
{"to": "&P5_EMAIL.", "subject": "Invoice &P5_ID.", "body": "Attached is your invoice.",
"attachments": [{"document": "INVOICE", "items": {"P5_ID": "&P5_ID."}, "filename": "invoice-&P5_ID."},
"select content, filename, mime from sales.terms where current"]}A document attachment is drawn on the server like the template's download: its query runs as the application's role with the session state, items (&ITEM. filled in) over it; filename (.pdf is added) defaults to the template's. The template's authorization applies to the user. The mail is queued in the page's transaction: when a later process fails, nothing is sent. It can run in a background chain too.
Send push notification
A send_push process (APEX: Send Push Notification) sends a push notification to the devices of one user, without SQL:
{"to": "&P5_APPROVER.", "title": "Leave request from &APP_USER.", "body": "&P5_DAYS. days from &P5_START.",
"page": 5, "items": {"P5_ID": "&P5_ID."}, "tag": "leave-&P5_ID.", "urgency": "high"}to, title and body take &ITEM. substitutions; page and items are the page the notification opens (signed for the recipient); tag (letters, digits, -, _) makes a newer notification replace an older one; urgency is very-low, low, normal (default) or high. The notification is queued in the page's transaction and sent after the submit commits; a user without a device gets nothing (no error). The application needs push notifications on (Settings → Progressive Web App). From SQL the same is meta.send_push(...) (chapter 9).
Send notification
Sprint 165. A send_notification process adds an in-app notification for one user: their notification bell shows it and its page opens from there.
{"to": "&P5_APPROVER.", "title": "Leave request from &APP_USER.", "body": "&P5_DAYS. days from &P5_START.",
"page": 5, "items": {"P5_ID": "&P5_ID."}, "icon": "calendar", "push": true}to, title and body take &ITEM. substitutions; page and items are the page it opens (signed for the recipient); icon is an icon name (default bell); push: true also sends it to the user's devices when push notifications are on. It is added in the page's transaction (a later failing process leaves nothing) and can run in a background chain. The application needs notifications on (Settings → User Interface → Notifications). From SQL the same is meta.notify(...) (chapter 9).
Declarative process types
Sprint 157 (APEX: page process types). Each type calls what pgkiln already has; its settings go in the process's attributes (config), checked when it is saved and again when it runs.
type | APEX | Settings | What it does |
|---|---|---|---|
close_dialog | Close Dialog | {"items": ["P5_ID"]} | Closes the modal page after the submit (a modal page closes after a submit anyway; this one also hands the items' values to the page below, where items of the same name take them before its Dialog Closed actions run) |
clear_session_state | Clear Session State | {"items": ["P3_NAME"], "pages": [3, 4], "all": false} | Empties the items, every P<n>_ item of the pages, or all page and application items |
reset_pagination | Reset Pagination | – | An interactive grid saved from a later page starts on its first page again (a report starts on its first page after any submit anyway: its page number is in the URL) |
user_preferences | User Preferences | {"action": "set", "preference": "DEFAULT_DEPT", "item": "P1_DEPT"}, or "reset" | Stores (or removes) a user preference; nothing for the public user |
server_geocoding | Server Side Geocoding | {"address_item": "P3_ADDRESS", "coordinates_item": "P3_LOCATION", "country": "nl"} | The installation's geocoder (GEOCODER_URL); the first place's lat,lng goes into the coordinates item |
print_report | Print Report | {"document": "EMPLOYEE_SHEET"} | A document template or report query, sent as the answer to the submit |
human_task_create | Human Task – Create | {"definition": "LEAVE_APPROVAL", "detail_pk": "&P7_ID.", "parameters": {"DAYS": "&P7_DAYS."}, "id_item": "P7_TASK_ID"} | Creates a task (approvals) and puts its id in the item |
human_task_manage | Human Task – Manage | {"action": "approve", "task": "&P8_TASK_ID.", "comment": "&P8_COMMENT."} | approve, reject, complete (with "outcome"), claim, release, delegate (with "to") or cancel; the task functions decide who may |
form_init | Form – Initialization | – | Nothing: a form region fetches its row by itself. Kept so imported pages show it |
Generate text with AI
An ai_generate process (APEX: Generate Text with AI) sends a prompt to a large language model and puts the answer into page items. The model is reached through an AI service that an administrator configures under Workspace utilities → AI services (chapter 3): Claude (Anthropic), OpenAI, Gemini (Google) or an OpenAI-compatible service (Ollama, vLLM, Azure OpenAI, a gateway), the model, the API key and optional daily limits per application. An application can only use the services an administrator allowed for it.
The prompt goes to the provider. Everything in the prompt, including the item values it contains, is sent to the AI service's provider (Anthropic, OpenAI or Google, or the OpenAI-compatible endpoint or gateway in its base URL) and is handled under that provider's terms. Don't put data in a prompt that may not leave your organisation, and tell your users when what they type is sent to an AI service.
The process is configured in its JSON (config), in one of three forms:
{"service": "CLAUDE", "system": "You write short, friendly summaries.",
"prompt": "Summarise: &P5_NOTES.", "output_item": "P5_SUMMARY"}
{"service": "CLAUDE", "prompt": "Extract the contact from: &P5_TEXT.",
"output_items": ["P5_NAME", "P5_EMAIL", "P5_BIRTH_DATE"]}
{"service": "OPENAI", "prompt": "Extract: &P5_TEXT.",
"schema": {"type": "object", "properties": {"name": {"type": "string"},
"address": {"type": "object", "properties": {"city": {"type": "string"}},
"required": ["city"], "additionalProperties": false}},
"required": ["name", "address"], "additionalProperties": false},
"items": {"P5_NAME": "name", "P5_CITY": "address.city"}}output_item: the answer as text goes into one item.output_items(structured output): pgkiln builds a strict JSON schema from the items (the property names come from the item names withoutP5_, the descriptions from their labels; number items are numbers, checkboxes and switches booleans, date items dates asYYYY-MM-DD) and asks the model for exactly that JSON; each property goes into its item.schema+items(structured output with your own schema): a JSON schema of an object, and which property (or path,address.city) goes into which item. OpenAI's strict mode needs every property inrequiredand"additionalProperties": false.- Optional:
system(the system prompt),max_tokens(at most the service's maximum) anderror_message(shown instead of the error, which then goes to the debug messages).
Structured outputs use the providers' own JSON schema support (Claude: output_config.format, OpenAI: response_format with strict: true), so the answer is valid JSON of that shape; pgkiln checks it once more and fails the process when it isn't (for example when it was cut off at the output limit).
Substitutions are data, never instructions. &ITEM. in the prompt and the system prompt is replaced by the item's value wrapped as <data name="ITEM">…</data>, with <, > and & escaped, and the system prompt then tells the model that such text is content to work on and that instructions inside it are not to be followed. This makes prompt injection by users harder, not impossible: treat the answer as untrusted text. The session id and password items are never substituted.
The answer is untrusted. It only ever becomes item values: shown escaped like any value, never run as SQL or HTML. If you use it in SQL, use it as a bind value (:P5_SUMMARY), never as SQL text.
Errors (no key, a service the application may not use, the daily limit, the provider's rate limit, a refusal, a time-out, an answer that isn't the JSON asked for) fail the process with a message the user may see (no keys or provider details); like other processes, the page shows it and keeps the values. Claude may decline a request for safety reasons; with refusal fallbacks on (the default for Claude services) Anthropic then re-runs it on its recommended fallback model, and the usage log shows which model answered.
Without a page submit: the dynamic action ai_generate (chapter 7) runs the process through AJAX and updates its output items.
Usage log. Every request is logged in meta.ai_usage: when, application, page, user, service, provider, the model that answered, source (process, dynamic action, SQL, builder test), input and output tokens, duration and status (ok, refused, error, limited). Prompts and answers are never logged; at debug level 9 the application's debug messages show them (the system prompt, the prompt and the answer), at level 6 the service, model and tokens. See the log under the application's Activity → AI usage, and for all applications on the AI services page.
From SQL, meta.ai_generate() queues a request and meta.ai_result() reads the answer (chapter 9); meta.ai_available('SERVICE') tells whether the application may use a service (e.g. as a region or button condition).
HR example, page 37 (Leave assistant). Paste an employee's message about leave: Summarise writes a summary for the manager (output_item), Fill in the request reads the first and last day and the reason into date and text items (output_items), and Request leave files it. With JavaScript both AI buttons run through dynamic actions. The example creates no AI service: until an administrator adds one named HR_ASSISTANT and allows the HR application, the page says so (a region with the condition not meta.ai_available('HR_ASSISTANT')) and hides the AI buttons.
Computations
A computation sets a page item or an application item without a process: a default, a value looked up by SQL, a derived value.
| Property | Meaning |
|---|---|
item_name | The page item or application item it sets |
point | before_header: when the page is shown (after the form fetch, before the load processes). after_submit: after the posted values are stored, before the validations |
type | How expression is read, see below |
expression | The value, item, query, expression or function body |
condition_type, condition_expr, condition_value | Only when the condition holds |
authz | Only for users who pass this authorization scheme |
seq | Order; later computations see the values of earlier ones |
type | expression |
|---|---|
static | A value; &ITEM. substitutions allowed. An empty result clears the item |
item | The name of another item whose value is copied |
sql_query | A SELECT; the first column of the first row (empty without rows) |
sql_expression | A SQL expression, e.g. round(:P22_DAYS::numeric) |
function_body | A PL/pgSQL function body that returns the value: return upper(:P3_NAME);, or a whole declare … begin … end block |
SQL runs as the application's database role with bind variables, each computation in its own savepoint. A failing computation before the page is shown leaves the item as it was and shows the error on the page; after a submit it stops the submit (everything is rolled back) and shows the error, like a failing process.
Application computations
Shared Components → Application Computations (APEX: Application Computations) are computations for every page of the application, with the same types, conditions, authorization and build option as a page's (migration 102, meta.app_computation). Their point:
point | When |
|---|---|
after_authentication | Once, when a user signs in (after the application processes after_login) |
before_header | Every page shown, before the page's own before_header computations |
after_submit | Every page submitted, before the page's own after_submit computations (and the validations) |
They usually set application items, e.g. a user's sales region once at sign-in:
select region from sales.rep where lower(username) = lower(:APP_USER) -- AI_REGION, sql_query, after_authenticationAn application computation of a page item runs on that item's page only (elsewhere it is skipped, without the unknown item error a page's computation gives). A failing one behaves like a page computation at the same point.
Branches
After a successful submit pgkiln redirects (POST-redirect-GET). Branches decide where to: the first branch, in sequence, whose button, authorization and condition match is taken; when none applies, the pressed button's target_page, or back to the same page. In a modal dialog, the dialog closes instead, and the calling page reloads, unless the button or the branch taken stays in the dialog (sprint 240) or the branch goes in the page below (sprint 249).
| Property | Meaning |
|---|---|
name | A description, shown in the page designer |
point | after_processing (after a submit's processes) or before_header (before the page is shown: a redirect instead of the page, e.g. "nothing to do here, go to the list") |
when_button | after_processing only: the request (button) it is for; empty = any |
target_type | page, url, function, app or (sprint 249) item |
target_item | item: the item holding the target page, a page number or page alias of this application: a page item, an application item or the built-in APP_PREVIOUS_PAGE (Back to the calling page). target_items are signed for that page |
target_page, target_items | A page of the application (empty = this page) and the items to set there, e.g. {"P7_EMPNO": "&P22_EMPNO."}; the link is signed with a checksum. For app: the page and items in the other application |
target_url | A path inside the application (after /a/<alias>/), e.g. 12?view=month or account; &ITEM. values are URL-encoded. Other sites are refused (no scheme, //, \ or ..) |
target_function | function: a PL/pgSQL function body that returns such a path (APEX: Function returning a URL), run as the application's role with binds; checked like target_url (meta.branch_path_ok). An empty result: the branch doesn't apply; a refused one shows a message and is logged |
open_region | (sprint 238) The static ID of an inline dialog or drawer region the target page (of this application) opens when it shows, e.g. a confirmation after the save |
target_app | app: the alias of another application of this installation (APEX: Branch to page in another application). It must exist with that page (else the branch doesn't apply and a message is shown); the items are signed for that application, page and user. That application's own sign-in and authorization apply when the browser gets there |
condition_type, condition_expr, condition_value | Only when the condition holds |
stay_in_dialog | (sprint 240) In a modal dialog page: open the target inside the dialog instead of closing it (Staying in the dialog) |
in_page_below | (sprint 249) In a modal dialog page: the dialog closes and the page below goes to the target (A dialog that sends the page below elsewhere). Not with stay_in_dialog |
authz, seq, build_option | As for other components |
A before_header branch to the page itself is skipped (it would loop).
Back to the calling page
(sprint 249, MG-22) A page opened from several lists needs no branch per list:
&APP_PREVIOUS_PAGE.(:APP_PREVIOUS_PAGEin SQL) is the page the user came from: pgkiln notes each page the user views (not a modal dialog, a download or an offline prefetch) in the session. A page viewed again (a submit that comes back with an error, another report page) keeps the page it came from; in a modal dialog it is the page below.&APP_PREVIOUS_URL.is that page's URL as the user opened it, with its search, report page and signed items (one-shot parameters such asclearleft out), for a link:<a href="&APP_PREVIOUS_URL.">Back</a>. Both are null before the user has viewed another page, and a request can't set them. They follow the session, not the browser tab: two tabs share them.- A branch with target type
itemreads its page from an item:target_item=P11_BACK(an item the calling link sets, e.g.{"P11_ID": "#ID#", "P11_BACK": "5"}), an application item, orAPP_PREVIOUS_PAGE. The value must be a page number or alias of this application that the user may open (its authorization and sign-in); anything else (another site, a path, a page that doesn't exist or isn't allowed, the global page) sends the user to the page itself, so an item value can't make an open redirect.target_itemsare signed for the target page with a checksum, as for a page branch. - When the page is the previous page and the branch sets no items, the browser goes back to
APP_PREVIOUS_URL: the list keeps its search, report page and selection.
The Advisor warns about a target_item that is not an item of the page, an application item or APP_PREVIOUS_PAGE. APEX has no such built-in (there, a hidden item and a branch per caller).
HR example, page 51 (Employee profiles): the button Back to page &APP_PREVIOUS_PAGE. (the label names the page) and its one branch (target_type item, target_item APP_PREVIOUS_PAGE) go back to Employees or Departments, whichever the profile was opened from (examples/hr/hr_113_navigation.sql).
A dialog that sends the page below elsewhere
(sprint 249, MG-23) A branch of a modal dialog page with In the page below (in_page_below) closes the dialog and sends the page below to the branch's target, with its items and checksum, instead of refreshing it: a Find dialog that opens the record it found, a New dialog that continues on the record's page. The success message shows on the target page, and open_region works there too. It also works for a before_header branch of a dialog page. Without JavaScript, or with the dialog page opened in a tab of its own, the Continue link (and, with JavaScript, the tab itself) goes to the target. The Advisor notes the option on a page that isn't a modal page; the database refuses it together with Stay in the dialog.
HR example, page 76 (Find an employee, opened from Employees and from Departments): Open the profile closes the dialog and shows that employee's profile (page 51) in the page below.
-- function returning a URL (HR page 28, "Open")
begin
if exists (select 1 from hr.leave_request where empno = :P28_EMPNO::int and status = 'PENDING') then
return '6';
end if;
return '12';
endServer-side conditions
(sprint 183) The application's Pages report (the application's home) has a Conditions column: per page, how many of its regions, items, buttons, validations, processes and dynamic actions have a server-side condition, and, opened, each of them with its condition in words (the same words as the Page Designer's badges). Pages without one show a dash.
Every component has the same server-side condition (sprint 154; APEX: Server-side Condition): regions, items, buttons, dynamic actions, validations, processes, computations, branches and application computations. In the Page Designer it is the Server-side condition group: Condition type, Expression / item and Value.
condition_type | Holds when |
|---|---|
| (empty) | always (a region's or button's condition without a type: the SQL below) |
sql | the expression, a boolean SQL expression, is true |
exists / not_exists | the query in the expression returns a row / no row |
function_body | the PL/pgSQL body in the expression returns true (return :P3_QTY::int > 0;) |
request_in / request_not_in | the request (the button pressed) is / is not one of the value's names, comma separated (SAVE,CREATE) |
item_null / item_not_null | the item named in the expression is empty / has a value |
item_zero / item_not_zero | that item is / is not zero (an empty item is not zero) |
item_null_or_zero / item_not_null_or_zero | that item is empty or zero / neither |
item_equals / item_not_equals | that item's value is / is not the value |
item_equals_item / item_not_equals_item | that item's value is / is not the value of the item named in the value |
item_in_list / item_not_in_list | that item's value is / is not one of the value's entries, separated by colons (CLERK:ANALYST) |
item_contains | (sprint 235) that item is a multi-value item (checkbox group, multiselect, shuttle, select many: values separated by colons, DESK:LAPTOP) and has the value among its values (LAPTOP; one value, no colon) |
item_contains_any | (sprint 235) that multi-value item has one of the value's entries, separated by colons (TEST:A11Y) |
page_in / page_not_in | the current page is / is not one of the value's page numbers (1,3) |
page_is_dialog / page_is_not_dialog | the page is / is not a modal dialog |
user_signed_in / user_public | the user is signed in / is the public user |
language_in / language_not_in | the application's language for this request is / is not one of the value's codes (de,pt-br; pt also matches pt-br) |
always / never | always / never (for a component you want to keep but switch off: a build option does it for a release) |
Only sql, exists, not_exists and function_body run SQL, as the application's database role, in the request's transaction; the others are decided by the server without a query. The database refuses a condition whose expression or value doesn't fit its type (meta.condition_ok).
A condition whose SQL fails counts as false and shows the error. Regions and buttons keep their condition column as the expression: without a type it is SQL, as before, so older exports keep working. Dynamic actions name theirs server_condition_type, server_condition_expr and server_condition_value (their condition_type is the client-side condition): when it doesn't hold, the dynamic action isn't on the page.
The Page Designer's tree shows the condition in words on the component's filter badge (When P3_JOB is one of CLERK, ANALYST), in the builder's language. The Advisor names SQL conditions a type can say exactly (:P3_ID is not null, :REQUEST in ('SAVE', 'CREATE'), :P3_JOB = 'CLERK') as information; <> and not in stay SQL, because in SQL an empty item makes them false.
item_equals and item_in_list compare a multi-value item's whole value (DESK:LAPTOP is not LAPTOP); item_contains and item_contains_any look at its values one by one, as text (the value is never run as SQL). HR example, page 50 (Project team, part 98): a Laptop order region shows when the needs checkbox group item_contains LAPTOP, a Quality checklist when the skills item_contains_any TEST:A11Y.
HR example, page 22 (Leave planner). Computations fill the employee (yours, when none is chosen: sql_query with condition item_null), the name (function_body) and the pending requests before the page is shown, and round the days after a submit (sql_expression). Branches: Check with more than 10 days goes to the leave calendar (sql condition); Plan goes to a new leave request for the employee (target_items); the More menu's Start over request comes back to the page with the days cleared (request_in).
Build options
Shared Components → Build options are named switches (include or exclude) for features that are not ready, or only for some installations. Pages, regions, items, buttons, dynamic actions, validations, processes, computations, branches, navigation entries and application processes have a build_option property:
build_option | The component is part of the application |
|---|---|
| (empty) | always |
NAME | while the option is included |
!NAME | while the option is excluded (shown as "Not" in the builder) |
An excluded component is left out when the runtime loads the application: it is not rendered, not run, and not accepted on submit (a page left out answers 404). A name that does not exist leaves the component out (fail closed); the Advisor reports it. Build options are part of an application export. On HR page 22, the Forecast region needs LEAVE_FORECAST (excluded), and Planner tips (!LEAVE_FORECAST) takes its place until it is included.
Configurable build options (sprint 137; APEX: the Configuration Options feature): tick Configurable on a build option, and Create page → Feature → Configuration options adds page 9020 Configuration where the application's administrators switch those options on and off while it runs (a checkbox group shown as switches, {"switches": true}). From SQL, as the application's own role and for a user with the admin role only: meta.configurable_options() (name, description, enabled) and meta.set_configurable_options('EXPORT:BETA') (the named ones included, the other configurable ones excluded; an option that is not configurable is refused). The change applies to every user at once, like a change in the builder. An import of a newer version of the application sets the options as the export has them.
Application processes
Shared Components → Application processes run for the whole application:
point | When |
|---|---|
after_login | Once, right after a successful sign-in |
before_page | Before every page view and every submit |
Their SQL can set application items by returning columns named like them. The HR sample maps the signed-in user to an employee:
select (select empno from hr.emp where lower(username) = lower(:APP_USER)) as ai_empno,
coalesce((select initcap(ename) from hr.emp where lower(username) = lower(:APP_USER)), :APP_USER) as ai_ename&AI_ENAME. then greets the user on the dashboard.
Application settings
Shared Components → Application settings (APEX: Application Settings, APEX_APP_SETTING) are named values an administrator changes after deployment: a support address, a limit, a switch. Each has a name (SUPPORT_EMAIL), a value, a description, optionally a list of valid values, and Value required. Application code reads and changes them:
select meta.get_app_setting('SUPPORT_EMAIL');
select meta.set_app_setting('LEAVE_APPROVAL', 'hr'); -- one of its valid valuesBoth work for the current application only, called as its own database role (application code), and raise an error for an unknown name, a value outside the valid values or an empty required one. Settings are exported with the application, values included. An import over an installed application (CLI, MCP, a working copy merge) keeps the installed value of every setting marked Keep the installed value on upgrade (the default); with the mark off, the file's value wins. When the application's build status is Run only, its existing settings can still be edited.
User preferences
Values kept per user and application across sessions (APEX: APEX_UTIL.GET_PREFERENCE, SET_PREFERENCE, REMOVE_PREFERENCE):
select meta.set_preference('report.rows', '50'); -- the signed-in user
select meta.get_preference('report.rows'); -- null when there is none
select meta.remove_preference('report.rows');
select meta.get_preference('report.rows', 'blake'); -- another user of the applicationNames are letters, digits, _, . and - (at most 100); values at most 32,000 bytes; at most 500 preferences per user. Setting one needs a signed-in user. Items with {"persist": "user"} keep their values this way (Keeping values per user). Preferences are data of the installation: not exported, kept by an import over the application, deleted with it.
Data export from SQL
meta.data_export(query, format, options) (APEX: APEX_DATA_EXPORT.EXPORT) returns a query's rows as a file (bytea): csv, json (an array of objects), xml (query_to_xml) or html (a table). It runs with the caller's privileges, so grants and row level security apply as to the query itself. Attach the file to a mail, store it, or send it with a download process:
select meta.add_mail_attachment(
meta.send_mail('boss@example.com', 'Staff', 'Attached.'),
meta.data_export('select empno, ename, sal from hr.emp order by ename', 'csv', '{"separator": ";"}'),
'staff.csv', 'text/csv');Options: separator (CSV, one character), header (false: no heading line), bom (false: no UTF-8 byte order mark, which Excel needs to read UTF-8), title (HTML). CSV fields are quoted when needed, and text that a spreadsheet would run as a formula (=, +, -, @) gets a leading apostrophe, as in report downloads. Excel and PDF come from the download process.
Automations
Shared Components → Automations run SQL or PL/pgSQL on a schedule, like APEX automations: nightly clean-ups, reminders, recalculations. The pgkiln server schedules them, so no extension is needed (pg_cron isn't available on every managed PostgreSQL service).
Automations are the application's logic: pgkiln runs them as the application, and they are exported and imported with it. Database housekeeping that should run even when pgkiln is down (vacuum, refreshing materialized views, purging old rows) is a pg_cron job in SQL Workshop → Scheduling instead (administrators; chapter 3 compares the two). The Automations list says so in one line, with a link.
| Setting | |
|---|---|
| Schedule | cron syntax, minute hour day-of-month month day-of-week: 0 7 * * 1-5 (07:00 on weekdays), */15 * * * * (every 15 minutes), 0 2 1 * * (02:00 on the 1st), 30 6 1 jan,jul *; or @hourly, @daily, @weekly, @monthly, @yearly. When both day fields are set, either may match, as in cron |
| Time zone | the schedule's time zone, e.g. Europe/Amsterdam (daylight saving included) or UTC |
| For each row of | optional query: the actions then run once per row, with the row's columns as binds (APEX's query-based automations). Empty: the actions run once |
| Error handling | stop (default): an error rolls the whole run back · skip: a failing row is rolled back and recorded, the other rows go on (APEX: Ignore; needs a query) · disable: like stop, and the automation is switched off (APEX: Disable Automation) |
| Roles | what meta.has_role() returns true for while it runs (read at every run) |
| Timeout | the statement timeout of a scheduled run or Run now (default 300 s) |
Actions
An automation has one or more actions, run in order (by sequence) for each row, or once (the Actions box under the automation: Add action, the arrows reorder, click an action to edit or delete it). Each action has:
| Field | |
|---|---|
| Name | e.g. Remind the manager; it appears in error messages and the run history |
| Sequence | the order |
| Code | one or more SQL statements, a do $$ … $$ block or call. Binds: :APP_ID, :APP_ALIAS, :APP_USER (automation:<name>), :AUTOMATION_NAME and the row's columns. Binds aren't replaced inside $$ … $$: pass them to a function instead |
| Server-side condition | optional boolean SQL expression with the same binds: the action runs only when it is true, e.g. :DAYS_PENDING::int >= 7 |
All actions of a run share one transaction as the application's database role, so grants and row level security apply, and a later action sees what an earlier one wrote. With error handling skip, every row runs in a savepoint: when an action of a row fails, that row's changes are undone, the error is recorded and the next row runs. A statement timeout always stops the whole run.
The editor shows the next run, a Run now button (it also works while the automation is disabled) and the last runs: who started them (schedule, manual or sql with the user), the status (ok; warning when some rows failed; error), the rows processed, the failed rows with each row's error (row number, action, message and the row's values), and the error message. The last 100 runs are kept in meta.automation_log.
The HR sample's Remind managers runs at 08:00 on weekdays (examples/hr/hr_08_automations.sql, hr_33_automation_actions.sql):
-- For each row of (error handling: skip)
select id, current_date - created_at::date as days_pending
from hr.leave_request
where status = 'PENDING' and created_at < now() - interval '2 days'
-- Action 10 "Remind the manager"
select hr.remind_pending_leave(:ID::int);
-- Action 20 "Escalate after a week", condition :DAYS_PENDING::int >= 7
select hr.escalate_pending_leave(:ID::int);Running an automation from SQL
Application code (a page process, an application process, a workflow, another automation) runs an automation of the current application with meta.run_automation, like APEX_AUTOMATION.EXECUTE:
select meta.run_automation('Remind managers'); -- raises an error if the run fails
select meta.run_automation('Remind managers', p_raise => false); -- returns {"status": "error", …} insteadIt runs synchronously, in the caller's transaction, as the caller's database role (the application's role), with the automation's roles and user (automation:<name>) while it runs; afterwards the caller's user and roles apply again. It returns {"status": "ok" | "warning" | "error", "rows": …, "failed": …, "errors": [...], "message": …} and records the run (trigger sql, with the calling user). Because it is part of the caller's transaction, a rollback of the caller undoes the run and its log entry; with p_raise => false a failed run is undone on its own and the log entry is kept when the caller commits. The automation need not be enabled. While the run's transaction is open nobody else can run the same automation (the scheduler and Run now report it as busy, another run_automation raises an error), and an automation can't run itself. The caller's statement timeout applies, not the automation's.
The HR sample's Leave requests page (6) has a Send reminders now button for admins whose process is select meta.run_automation('Remind managers');.
Running more than one pgkiln server? Every server runs the scheduler (every 30 seconds, SCHEDULER_INTERVAL_S). Due automations are claimed with FOR UPDATE SKIP LOCKED and a run holds an advisory lock, so an automation never runs twice at the same time. Set AUTOMATIONS=off on servers that shouldn't run them. Exported applications include their automations and actions; an imported copy starts with them switched off, so a copy never runs the original's jobs unasked. Export files of pgkiln 0.23 and older (one code field per automation) still import: the code becomes the automation's single action. Scripts may still write meta.automation.code: it creates or replaces the single action (the column itself stays empty).
If you prefer the database to schedule work, pg_cron still works next to this: the Docker setup includes it (sprint 213), and SQL Workshop → Scheduling manages its jobs.
Sending e-mail
Like APEX's APEX_MAIL, applications send e-mail from SQL, from a Send e-mail process and from e-mail templates. Where APEX sends only through an SMTP server with a user name and password, pgkiln sends through any of these mail services (Workspace utilities → Mail services, administrators):
| Provider | How pgkiln hands mail over | Credentials |
|---|---|---|
| SMTP | Any SMTP server or relay, STARTTLS or TLS | User name and password, or OAuth2 (SASL XOAUTH2 with a token from the client credentials grant: Microsoft Entra for Exchange Online, or another identity provider's token URL) |
| Microsoft 365 (Graph) | Microsoft Graph sendMail as the From mailbox | An Entra application (tenant, client ID, client secret) with the application permission Mail.Send; restrict it to the sending mailboxes with an application access policy |
| Amazon SES | SES API v2, the raw MIME message, Signature Version 4 | Region, access key ID and secret access key (an IAM user allowed ses:SendEmail) |
| Resend, Postmark, SendGrid, Mailgun | Their HTTP APIs | An API key (Postmark: a server token; Mailgun: also the sending domain and region) |
| Log only | Nothing is sent: the server's log shows each mail | – (development and demos) |
Microsoft retires basic authentication (a password) for SMTP in Exchange Online: use SMTP with OAuth2 or the Graph provider. Secrets are stored encrypted with PGKILN_SECRET_KEY, are write-only in the builder, never exported and never readable by applications. Each service lists the From addresses it may send as (an address, or @example.com for a whole domain); an administrator chooses each application's services, their From addresses and an optional limit per day (an application may have several). A workspace's administrators can also set up the workspace's own mail service (sprint 118): the workspace's applications that an administrator gave no service send through it, with its default From address. Administration → Mail queue shows the delivery per hour and per application, the slowest provider calls and the failures with the provider's answer, with Retry and Purge.
How mail is sent. meta.send_mail and the others only queue the mail, in the caller's transaction: a transaction that rolls back sends nothing. After the commit, the server sends it at once (NOTIFY), or on the scheduler's next pass. A failure that may pass (a network problem, HTTP 429 or 5xx, an SMTP 4xx answer) is tried again after 1, 4, 16 and 64 minutes; the fifth failure, or a refusal (an unknown recipient, a sender the provider doesn't accept), marks the mail error. Applications → Activity → Mail shows each mail with its outcome, and sends a failed one again or cancels a queued one. Mail is kept 30 days.
From SQL
-- APEX_MAIL.SEND
select meta.send_mail(
p_to => 'jane@example.com, john@example.com',
p_subject => 'Your leave was approved',
p_body => 'Enjoy your holiday!', -- plain text
p_body_html => '<p>Enjoy your <b>holiday</b>!</p>', -- HTML (optional)
p_cc => null, p_bcc => null, p_reply_to => 'hr@example.com',
p_from => null); -- null: the application's From address
-- APEX_MAIL.ADD_ATTACHMENT, in the same transaction
with m as (select meta.send_mail('jane@example.com', 'Invoice 42', 'Attached.') as id)
select meta.add_mail_attachment(m.id, i.pdf, 'invoice-42.pdf', 'application/pdf')
from m, sales.invoice i where i.id = 42;A document as attachment
(sprint 237) meta.document_pdf(template, items) (APEX: APEX_PRINT.GENERATE_DOCUMENT) gives the PDF of one of the application's document templates for meta.add_mail_attachment, from SQL or PL/pgSQL, without building the PDF in the browser:
-- a process of the order page
select meta.add_mail_attachment(m.id,
meta.document_pdf('INVOICE', jsonb_build_object('P5_ID', :P5_ID)),
'invoice-' || :P5_ID || '.pdf', 'application/pdf')
from (select meta.send_mail(:P5_EMAIL, 'Your invoice', 'Attached is your invoice.') as id) mThe renderer is pgkiln's (in the server, not in the database), so the function returns a short reference, and the server draws the PDF when the process ends: in the same transaction, on the same connection, as the application's role (grants and RLS apply), with the data as the process left it (a row the process just inserted is in the document), the session state and items over it. It puts the PDF in place of every mail attachment that holds the reference, before the submit commits; a template that fails, or one the user's authorization doesn't allow, fails the process and rolls the submit back. The same happens after an application process, an Ajax callback and a dynamic action's SQL. The function names only the current application's templates and works only as the application's role.
Use the value as a mail attachment only: stored anywhere else it stays the reference (to keep the PDF in a table, use (sprint 245) meta.document_temp_file, a temporary file the server draws the same way and the next process reads). The server draws references in the processes it runs; SQL that runs elsewhere (an automation, a workflow activity, pg_cron, the SQL Workshop) can queue the mail, but the server sends no mail with an undrawn reference: it marks it error ("was not drawn"). A send_email process can attach a template without SQL ({"document": …}, above).
HR example. The employee form (page 3) has Mail sheet: a process queues a mail to the employee with EMPLOYEE_SHEET attached, drawn this way.
See chapter 9 for every function and its limits. The functions work for the current application only when the caller runs as that application's database role (pages, processes, automations, workflows and background chains do); the SQL Workshop is not an application.
Several mail services
An application can send through more than one mail service (sprint 236): orders as orders@example.com through one SMTP account and safety notices as safety@example.com through another, or two providers. An administrator links each service to the application under Workspace utilities → Mail services → Applications; one of them is the application's default (the first one linked, until another is made the default there). Which service a mail goes through follows from its From address:
meta.send_mailandmeta.send_mail_template(p_from) and the Send e-mail process ("from") choose the linked, enabled service whose allowed senders include the From address (the default first when several do);- without a From address (also a workflow's
send_mailstep and task events), or when none of the others may send as it, the mail goes through the default service, with its From address. A From address that the default may not send as either is refused, as before; - an application with one service sends exactly as before. Its workspace's own service is used only when an administrator linked none; a service of another workspace can't be linked;
- the limit per day is per service: the application's mail of the day through that service;
- the service is noted with the queued mail; the server sends through it while it is still one of the application's services (else through the service for the From address at that moment). Sign-in codes and password reset mail go through the default service.
meta.mail_available()answers for the default service.
select meta.send_mail('jane@example.com', 'Fire drill at 10:00', 'Please leave by the stairs.',
p_from => 'safety@example.com'); -- through the service that may send as safety@HR example (part 99, examples/hr/hr_99_mail_services.sql): HR has a second service SAFETY_LOG (senders @safety.example.org, not the default) next to DEVELOPMENT_LOG; hr.send_safety_notice(to, text) sends from alerts@safety.example.org and so goes through SAFETY_LOG, all other HR mail through DEVELOPMENT_LOG.
The activity report by mail
meta.send_activity_report(to, days default 7) (sprint 137; APEX: the Email Reporting feature) queues a mail with the current application's activity of the last days (page views, users, sign-ins, failed sign-ins, errors and the most viewed pages) and the rows as activity.csv. It is for the application's automations and its signed-in administrators; others get an error. Create page → Feature → E-mail reporting adds the application setting EMAIL_REPORT_TO and an automation EMAIL_REPORTING that sends it every Monday at 07:00 UTC; without addresses nothing is sent.
Redirect all mail (test and acceptance systems)
(sprint 250, MG-24; APEX has no such switch: a test instance needs its own SMTP trap) A copy of an application on a test or acceptance system must not mail real customers. Two settings send every mail only to one address:
- the application's Redirect all mail to (Applications → Activity → Mail, the form Redirect all mail;
meta.app.mail_redirect_to): one address for that application's mail. It is exported and imported with the application; - the environment variable
MAIL_REDIRECT_TOon the server (chapter 1): one address for every mail of the installation, which wins over the applications' setting. Set it on every test server: an import of the production application (without a redirect) can't switch it off.
The redirect applies when the server sends, whatever put the mail in the queue (meta.send_mail, meta.send_mail_template, the Send e-mail process, workflows' send_mail steps, task events, automations and scheduled reports, sign-in codes by mail) and whichever of the application's services it goes through. The mail then goes
- to the redirect address only: Cc and Bcc are dropped (Reply-To and the From address stay as they are);
- with
[TEST]before the subject; - with the original recipients in the headers
X-Original-To,X-Original-CcandX-Original-Bcc(andX-Pgkiln-Redirected: which setting did it) and in a line at the top of the body (plain text and HTML), e.g.[TEST] Redirected to test-inbox@example.com (MAIL_REDIRECT_TO). Originally To: jane@example.com; Bcc: hr@example.com.
The queue keeps the original recipients; Activity → Mail shows redirected to … next to each mail that went to the redirect address, and a notice above the list while a redirect is on. Because it is decided when the mail is sent, mail queued before a redirect was set goes to the redirect address too (and mail still queued when it is emptied goes to its recipients). A MAIL_REDIRECT_TO that is not one plain address stops all mail (each fails with that message) rather than letting it out. Builder mail (Find my workspace, two-factor notices) and the Send test mail of a mail service follow MAIL_REDIRECT_TO as well.
Example (App Gallery → Sample Processes): its customers are made up, so the sample sets Redirect all mail toshop-test@example.com; shipping an order mails the customer, which arrives at shop-test@example.com as [TEST] Your order 7 is on its way.
Links in mail: absolute URLs
(sprint 250, MG-25; APEX: apex_page.get_url(p_absolute_url => true)) A link in a mail needs the server's address: meta.page_url(page, items, clear, p_absolute => true) puts it in front, and meta.app_url() is the application's address (its home page):
select meta.send_mail(o.email, 'Your order ' || o.id || ' is on its way',
'Follow it: ' || meta.page_url(8, jsonb_build_object('P8_ID', o.id), p_absolute => true))
from sales.orders o where o.id = :P4_ORDER::int;
-- https://apps.example.com/a/shop/8?clear=1&P8_ID=7&cs=…The address is the server's PUBLIC_URL, which the server records in the database when it starts (so automations, workflows and pg_cron jobs have it too); never the request's Host header, and not something application code can change. Without PUBLIC_URL it is the server's own fallback, http://127.0.0.1:<PORT>: set PUBLIC_URL before mailing links. Where no pgkiln server has started yet, p_absolute => true and meta.app_url() raise The public address of pgkiln is not known here: set PUBLIC_URL …. The checksum is the relative link's: bound to the page, the items and the user who builds the link (meta.app_user(), in an automation its user), so a link with items mailed to someone else works on a page whose items are not protected (session state protection Unrestricted, like the sample's tracking page 8), or without items.
E-mail templates
Shared Components → E-mail templates (APEX: Email Templates): a name, a subject, an HTML body and a plain text body with #PLACEHOLDERS#. In the HTML body #NAME# is the value HTML-escaped and #NAME!RAW# the value as it is (trusted HTML only); in the subject and the plain text the value is as it is. Names are case-insensitive; a placeholder without a value stays as written.
select meta.send_mail_template('LEAVE_DECIDED',
jsonb_build_object('NAME', 'Jane', 'STATUS', 'approved', 'START', '1 Aug 2026'),
'jane@example.com');Templates are exported with the application; mail services, the application's service and the mail log belong to the installation and are not.
HR example. The template LEAVE_DECIDED tells an employee that a leave request was approved or rejected: a trigger on hr.leave_request queues it when the status changes. The example's mail service DEVELOPMENT_LOG is of provider log only, so nothing leaves the server until an administrator gives HR a real service.
Approvals and the task list
Approvals (APEX: Task Definitions, the Approvals component and the Unified Task List) let an application ask someone to approve, reject or complete something, and act on the answer.
1. A task definition (Shared Components → Task definitions) describes one kind of task:
| Field | Meaning |
|---|---|
| Name | EXPENSE_APPROVAL; application SQL refers to it by name |
| Type | approval (Approve / Reject) or action (Complete) |
| Subject | e.g. Expense claim of &NAME.: &AMOUNT. — &KEY. comes from the task's parameters, &DETAIL_PK. is the record key |
| Potential owners (roles) | Users with one of these roles may act on the task (plus the users named when it is created) |
| Business administrator (role) | Sees every task of this definition, delegates and cancels them |
| The person who requested it may complete it | Off by default: nobody approves their own request |
| Priority, Due in | 1 (urgent) – 5 (low); e.g. 2 days. Overdue tasks are marked |
| When overdue, Maximum renewals, Escalation role | The expiration policy (below); empty: overdue tasks stay open |
| Details page, Details item | The subject links to this page, setting the item to the record key |
| On completion (SQL) | Runs as the application's role when the task is approved, rejected or completed (below) |
| Outcomes | Custom outcomes instead of Approve / Reject (below) |
| Events, When the completion SQL fails | Actions when a task is completed, expires or its completion SQL fails (below) |
| Notifications | E-mail templates pgkiln sends when a task is created, completed or expires |
2. Application SQL creates tasks, for example in the process that saves a request or in a trigger:
select meta.create_task('EXPENSE_APPROVAL', -- the definition
:P5_ID, -- the record it is about (detail_pk)
jsonb_build_object('NAME', :P5_NAME, 'AMOUNT', :P5_AMOUNT),
array[:P5_MANAGER_USERNAME]); -- users who may act, besides the rolesThe signed-in user is the task's initiator.
3. Users act in a task list, a region of type tasks. A task list region shows, depending on its settings, the tasks waiting for me (to act on, to claim, or assigned to me), the ones I requested, or the ones I administer, optionally with completed ones. Each task offers what the user may do:
| Action | Who |
|---|---|
| Approve / Reject / Complete (with an optional comment) | The actual owner, or a potential owner while the task is unassigned |
| Claim | A potential owner, while unassigned: it becomes theirs |
| Release | The actual owner: unassigned again |
| Delegate | The actual owner or an administrator, to any user of the application |
| Cancel | The initiator or an administrator |
| Comment | Everybody who sees the task |
Every step is in the task's history.
Vacation rules (APEX: vacation rules): a task list of my tasks has a Vacation rule section where users name the user who stands in for them, from one day until another (at most a year ahead). While the rule is active, the stand-in may act on, claim, release and delegate the tasks the user may act on as a named owner (the users given to meta.create_task) or as the actual owner, and sees them in their own task list; the decision is recorded under the stand-in's name. The rule is checked on every request, so the stand-in's access ends with it. Owners by role are not passed on (the role's other members are there for that). From SQL: meta.set_vacation_rule(delegate, from, until), meta.clear_vacation_rule() and meta.vacation_rule() (the signed-in user's own rule).
4. On completion, the definition's SQL runs as the application's role, in the same transaction as the decision, with these binds: :TASK_ID, :DETAIL_PK, :OUTCOME (APPROVED, REJECTED or COMPLETED), :COMMENT, :APPROVER, :INITIATOR, and the task parameters by name. An error in it (a business rule, row level security) shows the message and undoes the decision, so a task is never completed without its effect:
select expenses.decide(:DETAIL_PK::int, :OUTCOME, :COMMENT)When a record is decided somewhere else (for example with buttons on its own page), close its open tasks so they don't linger: select meta.close_tasks('EXPENSE_APPROVAL', :P5_ID::text, 'approved') (no completion SQL runs).
Custom outcomes (APEX 26.2: task outcomes). A task definition may list its own outcomes instead of Approve / Reject (or Complete):
[{"name": "YES", "label": "Yes", "colour": "success"},
{"name": "NO", "label": "No", "colour": "danger"},
{"name": "UNDECIDED", "label": "Undecided", "colour": "warning"}]The task list then shows one button per outcome, with its label and colour (default, primary, success, danger or warning: a fixed list, so a definition can't add other classes). The outcome is stored in lower case (meta.tasks.outcome = 'yes'), :OUTCOME in the completion SQL is the name (YES), and the history shows the label. A task ends only with an outcome of its definition: meta.complete_task refuses any other (also Approve / Reject on a definition with its own outcomes), and so does meta.close_tasks(name, detail_pk, outcome). A workflow branches on them in a task step's next ({"yes": "PAY", "no": "END"}) or a switch case {"outcome": "UNDECIDED", "next": "ASK_AGAIN"}. Names are letters, digits and underscores (at most 30, at most 10 outcomes); cancelled, expired and default are reserved.
Task events and notifications (APEX 26.2: Human Task events). A definition's Events are actions on what happens to its tasks:
[{"on": "complete", "type": "sql", "code": "select expenses.log_decision(:DETAIL_PK::int, :OUTCOME, :APPROVER)"},
{"on": "expire", "type": "mail", "to": "select email from staff where role = 'manager'", "template": "TASK_EXPIRED"},
{"on": "fail", "type": "workflow", "workflow": "FIX_REQUEST", "vars": {"REASON": "&ERROR."}}]on | When |
|---|---|
complete | The task was completed, with any outcome (also by meta.close_tasks with an outcome) |
expire | The task expired (below) |
fail | The definition's completion SQL raised an error |
type | Does | Fields |
|---|---|---|
sql | Runs statements as the application's role | code |
mail | Queues an e-mail through meta.send_mail_template or meta.send_mail | to (a SELECT returning addresses, or addresses with &NAME.), template, or subject and body with #NAME# placeholders |
workflow | Starts a workflow with the task's record key and parameters | workflow, vars (variable → text, &NAME. allowed) |
Binds (and #NAME# placeholders): the task's parameters, :TASK_ID, :DETAIL_PK, :SUBJECT, :OUTCOME, :APPROVER, :INITIATOR, :EVENT, and for fail :ERROR and :COMMENT. Complete and expire events run right after the commit: a trigger queues them (meta.task_hook, closed to applications) and the server runs each in a transaction of its own, as the application's role with the person who completed the task (or the initiator) as meta.app_user() and the task's tenant; one that fails is tried three times and keeps its error on the meta.task_hook row. Fail events run in the request that completed the task: the completion SQL's effect is undone, the failure is in the task's history, the actions run, and When the completion SQL fails says what happens to the task: reopen (the default) undoes the decision so the task stays open, complete keeps it completed without the SQL's effect. The user sees the error either way. Without fail events or a recovery, an error undoes the decision as before.
Notifications are e-mails pgkiln sends itself, from the application's e-mail templates: {"create": "TASK_CREATED", "complete": "TASK_DONE", "expire": "TASK_EXPIRED"}. create goes to the potential owners (the named users, the actual owner and the application's users with one of the owner roles), complete to the initiator, expire to both, at the e-mail address of their account. The placeholders are those of the events. They need a mail service, like meta.send_mail.
Overdue tasks: expire, renew, escalate
A task definition with Due in can say what happens to a task that is still open after its due date (APEX: expiration policy). The server checks every minute:
| When overdue | What happens |
|---|---|
| (empty) | Nothing: the task stays open and is marked overdue |
expire | The task ends with the state expired and no outcome; the completion SQL doesn't run |
renew | The due date moves on by Due in, up to Maximum renewals times (default 3); then it expires |
escalate | Once: the Escalation role becomes a potential owner, the priority 1, the task unassigned (its actual owner loses it) with a new due date; overdue again, it expires |
Each step is in the task's history, by system. A workflow waiting for a task that expires goes on with the outcome expired ("next": {"approved": "…", "expired": "…"}); without an expired branch it ends, like a workflow whose task is cancelled.
SQL API (application code; meta.app_user() is the acting user):
| Function | |
|---|---|
meta.create_task(name, detail_pk, params jsonb, owners text[], priority) | Returns the task id |
meta.close_tasks(name, detail_pk, outcome) | Closes a record's open tasks; returns how many |
meta.claim_task(id), meta.release_task(id), meta.delegate_task(id, username), meta.cancel_task(id, comment), meta.add_task_comment(id, text) | The task list's actions, with the same checks |
meta.tasks | View: the tasks the user may see, with may_act, may_claim, may_release, may_delegate, may_cancel |
meta.task_events | View: the history and comments of those tasks |
The task tables themselves are closed to the application's role: rights are checked by these functions and views, for every call. To tell owners by e-mail, use the definition's notifications, call meta.send_mail from the task definition's SQL or from an automation that reminds owners of overdue tasks; or put a task list on the home page.
Example: in the HR sample application, a leave request creates a LEAVE_APPROVAL task for the employee's manager; My tasks (page 14) approves or rejects it through hr.decide_leave, the same function as the leave request page's buttons, and a request decided there closes its task. A leave request nobody decides on within two days escalates to the administrators; managers going on holiday set a vacation rule on page 14.
Workflows
A workflow (APEX: Workflow) runs a process of several steps that can take days: tasks for people, SQL, decisions, waits. A workflow definition (Shared Components → Workflows) is a list of named steps; the builder checks them and draws the flow.
| Step type | Does | Fields |
|---|---|---|
task | Creates a task (task definitions) and waits until it is completed or cancelled | task (definition name), owners (a SELECT returning usernames, optional), next (a step, or per outcome: {"approved": "PAY", "rejected": "END"}) |
sql | Runs SQL; the columns of the row it returns become variables | code, next |
switch | Goes to the first case whose condition is true | cases: [{"when": ":AMOUNT::numeric > 1000", "next": "DIRECTOR"}], otherwise |
wait | Waits before going on | for (30 minutes, 2 days), next |
invoke_api | Calls a REST data source or a URL on the server; values of the response become variables (below) | source + params, or url, method, credential, body; variables, status_variable, response_variable, timeout, next |
parallel | Starts a branch at each of its steps; they run side by side | branches (the first step of each, at least two), join |
join | Where the branches of a parallel step meet | wait_for (all, the default, or any), next |
send_mail | Queues an e-mail (below) | to, template (or subject and body), cc, next |
draft | A placeholder while modelling: only in a development version (below) | note, next |
end | Ends the workflow |
next is optional: the following step in the list (after the last one, the workflow is complete). A task step's next per outcome names the outcomes of its task definition, custom ones too, plus cancelled, expired and default. A switch case is either {"when": "SQL condition", "next": …} or {"outcome": "YES", "next": …}, which compares the outcome of the last task (:TASK_OUTCOME); the builder checks that a task of the workflow can end with it.
[{"name": "CHECK", "type": "switch", "cases": [{"when": ":AMOUNT::numeric > 1000", "next": "DIRECTOR"}], "otherwise": "MANAGER"},
{"name": "DIRECTOR", "type": "task", "task": "EXPENSE_APPROVAL", "owners": "select username from staff where role = 'director'",
"next": {"approved": "PAY", "rejected": "END"}},
{"name": "MANAGER", "type": "task", "task": "EXPENSE_APPROVAL", "owners": "select manager from staff where id = :DETAIL_PK::int",
"next": {"approved": "PAY", "rejected": "END"}},
{"name": "PAY", "type": "sql", "code": "select expenses.pay(:DETAIL_PK::int) as paid_on"},
{"name": "END", "type": "end"}]Starting one. Application SQL, typically a page process:
select meta.start_workflow('EXPENSE', :P5_ID, jsonb_build_object('AMOUNT', :P5_AMOUNT))The variables (upper case) are binds in every step, with :DETAIL_PK, :WORKFLOW_ID and :INITIATOR; after a task step also :TASK_OUTCOME (APPROVED, REJECTED, COMPLETED, CANCELLED, EXPIRED or a custom outcome such as YES) and :TASK_APPROVER. The title may use &VAR..
How it runs. The pgkiln server runs workflows: right after they start or a task of theirs ends (NOTIFY), and it checks for waits that are over every few seconds (WORKFLOW_INTERVAL_S, default 10; WORKFLOWS=off on servers that shouldn't run them). Each step runs in its own transaction as the application's database role, with the initiator as meta.app_user(), so grants and row level security apply (meta.has_role() is false: there is no session). Several servers can share a database: each instance is locked while it runs.
A step that fails puts the workflow in faulted with the error; an administrator (the definition's administrator role) fixes the cause and retries the step. A task that is cancelled ends the workflow unless the step has a cancelled branch.
Tenants (APEX: multi-tenant workflows and tasks, APEX_SESSION.SET_TENANT_ID). An application that serves several customers (tenants) from the same tables sets the session's tenant once the user signed in, e.g. in a post-authentication or page process:
select meta.set_tenant((select company_code from staff where username = meta.app_user()))From then on (in the same transaction already, and in the session's next requests) meta.tenant_id() returns it, and the workflows and tasks the session starts carry it. A task created by a workflow gets the workflow's tenant, and the workflow's steps run with it. The task list, the workflow console, the views meta.tasks and meta.workflows, and every action (claim, complete, delegate, cancel, terminate, retry) only reach the workflows and tasks of the session's tenant: a user with the same roles in another tenant doesn't see them. A session without a tenant sees only those without one, so existing applications are unchanged. An execution chain in the background runs with the tenant of the session that queued it. Filter your own tables the same way (where tenant_id = meta.tenant_id(), or a row level security policy). Use row level security in the tenant's tables as well: the tenant is a value the application sets, not a database boundary.
Workflow diagram region
Sprint 160 (APEX 24.2+: Workflow Diagram region). A region of type workflow_diagram draws one workflow instance in a running application: its version's steps, the ones it went through (green), where it is now (blue, several with parallel branches) and a failed step (red, with the error above the diagram). Each reached step's tooltip lists when it was reached and what happened. The instance id comes from an item:
{"instance_item": "P9_WORKFLOW_ID"}It is read through meta.workflows as the application's role, so a user sees only workflows they started or administer (the Workflow Console's rule); others see the empty text. The diagram is SVG drawn on the server: it needs no JavaScript.
The workflow console region draws each of its instances the same way (sprint 172): under Diagram, the steps the instance went through, where it is now and a failed step, with each step's history as its tooltip, for finished and terminated instances too.
Send e-mail steps
A send_mail step (APEX 26.1: the Send E-Mail activity) queues an e-mail through the application's mail service, as the application's role, like meta.send_mail in a sql step:
{"name": "TELL", "type": "send_mail", "to": "select email from staff where id = :DETAIL_PK::int", "template": "REQUEST_DONE"}
{"name": "NOTE", "type": "send_mail", "to": "desk@example.com, &MANAGER_EMAIL.", "subject": "Request #TITLE# done", "body": "Decided by #TASK_APPROVER#."}to is a SELECT returning addresses, or addresses with &VAR. substitutions; cc likewise addresses. With a template (e-mail templates), or a subject and a plain-text body, the placeholders #NAME# are the variables, DETAIL_PK, WORKFLOW_ID and INITIATOR. No recipient: the step goes on (the history says so). A mail that can't be queued (no mail service, an address that isn't one, the daily limit) faults the step. The history records the mail's id; it is sent after the step's transaction commits.
Draft steps (APEX 26.2: Draft activities). A step of type draft stands for something not modelled yet ({"name": "BUDGET_CHECK", "type": "draft", "note": "check the budget", "next": "APPROVE"}). It may be in a development version only: the builder shows a warning and doesn't offer Activate while a version has one, meta.activate_workflow_version refuses it, and the database refuses draft steps in a definition's active steps (so a new definition can't have them either: create it, then a new version to model with drafts). The diagram draws them dashed. An instance can never reach one; if it did (steps changed with SQL), the step faults.
Invoke API steps
An invoke_api step (APEX: the Invoke API activity) calls a web service: a REST data source of the application (its URL, method, parameters and web credential), or a URL. It is the same code as the invoke_api page process, with the same protections: only hosts on the server's allow-list (PGKILN_REST_ALLOWED_HOSTS, PGKILN_REST_PRIVATE_HOSTS), addresses checked when the connection is made, a credential only sent to its valid for URLs, a size limit on the response.
[{"name": "RATE", "type": "invoke_api", "source": "EXCHANGE", "params": {"currency": "&CURRENCY."},
"variables": {"RATE": "rates.EUR", "RATE_DATE": "date"}, "status_variable": "HTTP_STATUS", "timeout": 20},
{"name": "ORDER", "type": "invoke_api", "url": "https://shop.example.com/api/orders/&ORDER_ID./confirm", "method": "POST",
"credential": "SHOP_API", "body": "{\"note\": &NOTE., \"rate\": &RATE.}", "response_variable": "CONFIRMATION"},
{"name": "BOOK", "type": "sql", "code": "select expenses.book(:DETAIL_PK::int, :RATE::numeric) as booked_at"}]| Field | |
|---|---|
source, params | A REST data source and its parameter values; parameters left out take their default |
url, method, credential, body | Or a URL (GET by default; POST, PUT, PATCH, DELETE), a web credential and a JSON body. The host is fixed: &VAR. only after it, URL-encoded; in the body a value becomes a JSON string |
variables | Variable → JSON path in the response (rates.EUR, items[0].id). Without it, the first row's columns of a source become variables |
status_variable | Gets the HTTP status; then an error status doesn't fault the step (the response isn't read), so a switch can decide |
response_variable | Gets the whole JSON response |
timeout | Seconds (1–60); default the source's time limit, 10 for a URL |
&VAR. in parameters, the URL and the body is a variable (or DETAIL_PK, WORKFLOW_ID, INITIATOR, TASK_OUTCOME, TASK_APPROVER); a name that is no variable is sent as written. A call that fails (a refused host, a time-out, an error status without status_variable, a response that isn't JSON) faults the step like a failing SQL step, with the reason in the console; an administrator retries it there, which calls again.
No transaction during the call. The step first commits its path as waiting at the step, with a lease well past the time limit (the history says calling REST data source EXCHANGE); the server makes the call, then a new transaction checks that the path still waits at that step with that lease and goes on with the response. A workflow terminated meanwhile keeps its state and the response is dropped; other parallel branches go on during the call. If the server stops during a call, the lease runs out and the step faults (didn't finish) instead of calling again, since a POST may not be safe to repeat: retry it from the console. While a call runs the server's runner waits for it, so long time limits delay other workflows on that server.
The builder checks the fields; the Advisor also reports a REST data source, parameter or web credential that doesn't exist (errors), a required parameter without a value, and a &VAR. that no step sets and the title doesn't name (warnings: give it to meta.start_workflow). The diagram shows the step as invoke API with its source.
Parallel branches. A parallel step (APEX: parallel activities) starts a branch at each step in branches; every branch runs on its own (its own step, wait and task) until it reaches the join step, while the workflow waits there. With "wait_for": "all" the join goes on when every branch has arrived; with "any" when the first one has, and the others are cancelled with their open tasks. Branches share the variables (a later value wins), and a branch may itself contain a parallel step with its own join.
[{"name": "SPLIT", "type": "parallel", "branches": ["ORDER", "NOTIFY"], "join": "BOTH"},
{"name": "ORDER", "type": "task", "task": "ORDER_LAPTOP", "next": "BOTH"},
{"name": "NOTIFY", "type": "sql", "code": "select staff.notify_facilities(:DETAIL_PK::int) as notified_at", "next": "BOTH"},
{"name": "BOTH", "type": "join", "wait_for": "all"},
{"name": "WELCOME", "type": "sql", "code": "select staff.welcome(:DETAIL_PK::int) as welcomed_at"}]The builder checks the structure: every branch reaches its join and stays inside (no step after the join, no step shared with another branch, no way into the join from outside the branches), and every join belongs to one parallel step. An end step inside a branch, or a cancelled task without a cancelled outcome, ends the whole workflow. A failing step faults its branch; the workflow shows as faulted while the other branches go on, and a retry resumes the failed branch. The diagram draws branches as dashed arrows and marks every step an instance is at.
Versions. A definition has versions (APEX: workflow versions), each development, active or inactive. New instances start the active version, and there is only one. Running instances keep the version they started with (and its steps) until they end, so changing a definition never changes them. The active steps can't be edited: under the definition, Create new version copies them into a development version (the label is optional: the next number), which the property form then edits; Activate makes it the active version (the builder refuses steps with problems), and the active one becomes inactive. Discard throws a development version away. The Versions table shows each version with its instance count and diagram; the Instances table shows which version each instance runs and where it is.
Migrating running instances (APEX 26.2: in-flight workflow migration). Running instances (active, waiting or faulted) of an older version can move to a newer one: the active version or an inactive version activated after theirs. Under the definition, Migrate instances… (shown while there are such instances) opens a page where you choose the version and the instances, and map each step an instance is at to a step of the new version (a step of the same name is proposed). Preview shows per instance where it goes or why it can't; Migrate then moves them all in one transaction, with their variables, the task they wait for and their wait, logged in each instance's history (migrated, version 1 → 2: APPROVE → APPROVE (by admin)) and in meta.workflow_migration. Nothing moves when one of them can't:
- a step without a mapping, or mapped to a step the version doesn't have (or a draft);
- an instance waiting for a task must go to a task step that creates a task of the same definition; one at a
waitstep to awaitstep (its wait goes on), one at a join to a join; - an instance calling a web service at that moment: try again later.
Inside parallel branches (sprint 149, migration 144) an instance is at several steps at once: its main path waits at the join, and each open branch (active, waiting or faulted) is at a step of its own. The page lists those steps with the instance (branches at A, B) and asks a mapping for each; the preview has a row per path (main, branch A), and the instance moves only as a whole. Each branch follows the rules above, and the join it ends at must map to a join step of the new version (a branch can't be mapped onto its own join). The branches' rows then name the new join and the parallel step that splits there (the mapped one, else the one parallel step of the new version that joins at that join), so the join counts them as before, done branches included; each moved branch has its own migrated event (version 1 → 2: branch A: A → A2 (by admin)). A branch the new version adds to a parallel step does not start for an instance already past its split.
The database function is meta.migrate_workflows(definition_id, version, ids, mapping, apply, by) (the owner's, for the builder and scripts; not for applications): one row per path, with the column branch (null for the main path).
The diagram as a file. Under the diagram, Download SVG downloads the whole model of the version shown (/builder/apps/<app>/shared/workflow_definition/<id>/diagram.svg?v=<version>), a standalone SVG with its own colours; Download PNG draws that SVG in the browser (with JavaScript; without it the SVG link remains). Step names and labels are escaped, so a definition can't put markup into the file.
The console. A region of type workflows lists the workflows the user started (or, with "context": "admin", those they administer), with their state, the version, the current steps (several with parallel branches), a diagram and the history. The initiator and administrators can terminate a workflow (its open tasks and branches are cancelled); administrators can retry a faulted one.
| Function / view | |
|---|---|
meta.start_workflow(name, detail_pk, vars jsonb) | Returns the workflow id |
meta.terminate_workflow(id, comment), meta.retry_workflow(id) | The console's actions, with the same checks |
meta.workflows, meta.workflow_events | The workflows the user may see (with version and active_steps), and their history |
meta.new_workflow_version(definition_id, label), meta.activate_workflow_version(definition_id), meta.discard_workflow_version(definition_id) | Versions, for the owner (the builder; scripts that install an application). Not for applications |
Example: the HR example application's employee form starts ONBOARDING when an employee is created. Its version 2 (part 18) prepares the workplace (the manager's task) and, in a parallel branch, the access that employees with a salary of 2500 or more need (a switch and an administrator's task); when both branches are done, the manager is notified (SQL). Version 1, which did this one after the other, is inactive. My tasks (page 14) shows the workflows. Part 67 adds SALARY_CHANGE: a SALARY_DECISION task with the outcomes Yes, No and Undecided (the owners get the SALARY_TASK e-mail, a complete event notifies the initiator), a switch on the outcome (Undecided asks again), SQL that applies the salary and, in version 2, a send_mail step to the employee; version 3 is in development with a draft step. Part 34 adds DEPARTMENT_CHECK, started by Check in a workflow on page 23: an invoke_api step reads the department from the example's own REST API (the DEPARTMENT source of part 23, so the server must allow 127.0.0.1:3100), a switch on HTTP_STATUS, and SQL that notifies the initiator.