Skip to main content

Directives

Directives are special instructions you add to a query to control how Kvery responds when the query runs — its error message, its HTTP status code, any webhooks it should fire and the HTTP requests it makes. They are most useful for queries published as an API, where the response and status code matter to the caller.

The editor suggests the directives as autocomplete items, so you can insert the correct syntax without memorising it.

A directive belongs to a statement: write it at the end of the statement, before its ;. A statement can have at most one ON ERROR RETURN '…' (optionally followed by SET HTTPCODE '…') and one webhook directive (ON SUCCESS …, ON ERROR … or ON '<code>' …). A second ON ERROR RETURN makes the run fail with the status 500 and the message Only one "ON ERROR" in a query!<br />Use {% Query1 %} {% Query2 %} for multiple queries! (the <br /> is a line break on the query's page); a second webhook directive is not recognised, stays in the SQL and makes the database report an error. To fire a second webhook, put it on another statement of the run.

A directive written after the ; becomes a statement of its own: an ON ERROR RETURN '…' there answers with its message on every run, and a webhook directive or a SET HTTPCODE there causes a database error. This rule does not apply to return(…);, returnk(…); and HTTP requests such as GET('…');, which are statements of their own.

ON ERROR RETURN​

Return a custom message when the query fails, instead of the raw database error.

SELECT * FROM orders WHERE id = '$id'
ON ERROR RETURN 'Order not found or could not be loaded';

This gives API consumers a clean, controlled error message. The message is also returned when the statement returns no rows or changes no rows. Without SET HTTPCODE the answer has the status 500. The message is the text between the apostrophes, so it cannot contain an apostrophe itself. On the query's page in Kvery the message appears in the error alert as plain text; a <br> in it starts a new line.

SET HTTPCODE​

Set the HTTP status code of the ON ERROR RETURN response. This lets an API endpoint return a meaningful status (for example 404 for "not found" or 422 for a validation problem) rather than a generic one. Write the code as digits between apostrophes (SET HTTPCODE '404'). SET HTTPCODE works only right after ON ERROR RETURN '…'; on its own it makes the query fail.

SELECT * FROM orders WHERE id = '$id'
ON ERROR RETURN 'Order not found' SET HTTPCODE '404';

ON SUCCESS POST '...' TO '...'​

Fire a webhook when the query succeeds (the run answers with a 2xx status). Kvery sends an HTTP request to the URL you specify, carrying the payload you provide — a JSON object or array, or a plain text.

SELECT * FROM orders WHERE id = '$id'
ON SUCCESS POST '{"text": "An order was opened"}' TO 'https://example.com/webhook';

POST is the usual method, but Kvery accepts any of GET, POST, PUT, PATCH or DELETE in this position — use whichever the receiving endpoint expects (a GET request carries no payload):

UPDATE orders SET status = 'sent' WHERE id = '$id'
ON SUCCESS PUT '{"status": "sent"}' TO 'https://example.com/resource';

Use this to notify another system when a query completes — for example to trigger a downstream job after an INSERT.

ON ERROR POST '...' TO '...'​

Fire a webhook when the query fails (the run answers with a 4xx or 5xx status). Same shape as the success variant (any of GET, POST, PUT, PATCH, DELETE), but triggered on error — ideal for alerting.

SELECT * FROM orders WHERE id = '$id'
ON ERROR POST '{"text": "Loading an order failed"}' TO 'https://example.com/alert';

ON '<code>' POST '...' TO '...'​

Fire a webhook when the run answers with one specific status code:

SELECT * FROM orders WHERE id = '$id'
ON ERROR RETURN 'Order not found' SET HTTPCODE '404'
ON '404' POST '{"text": "An order was not found"}' TO 'https://example.com/alert';

Webhooks fire after the response has been sent, according to the final HTTP status of the whole run. Only http:// and https:// URLs are called, also after redirects. See Webhooks for payload details and patterns.

HTTP requests: GET('...'), POST('...'), …​

A query can call another HTTP endpoint while it runs. Write the method with the URL between apostrophes: GET('…'), POST('…'), PUT('…'), PATCH('…') and DELETE('…') send their body form-encoded, RPOST('…'), RPUT('…'), RPATCH('…') and RDELETE('…') send it as JSON; a GET request has no body. The editor offers them in lower case (get(''), rpost(''), …); the method is not case-sensitive.

Declare :headers and :body as JSON objects in earlier statements to add request headers and body fields:

:headers = {"Authorization": "Bearer my-token"};
:body = {"status": "active"};
:result = RPOST('https://api.example.com/items');
return(:result);
  • The request is replaced by the body of the response, so you can store it in a variable (:result = RPOST('…');) or answer with it (return(GET('…'));). An empty body, or a body of only 0, gives NULL; a body that is a quoted JSON string gives the text without its quotes, and a body of true gives 1.
  • The request also passes on the URL parameters, the body values and most headers of the request that runs the query, and Kvery adds the headers query-id, query-hash, executed-by-name, executed-by-email and executed-by-ip. The cookies are not passed on, and neither are the Kvery credentials of the caller: the Authorization and Proxy-Authorization headers of an MCP / REST API call or of a Basic Auth call of the query API, and the device ID of the mobile app. A header you set in :headers takes precedence over a passed-on header of the same name, but it does not replace the five headers Kvery adds; a header with an empty value is not sent, and neither is a passed-on header of that name. The R… methods send Content-Type: application/json. When the request that runs the query uploads files, the header is Content-Type: multipart/form-data instead, and the methods without R pass the files on as a form upload. On an MCP / REST API call, the body values passed on are the parameters the call gives the query.
  • The status code of the response becomes the status of the run's answer. When the endpoint answers with a status of 400 or more, the run stops with an error and that status. When no answer comes at all (the connection is refused or times out, or the address is not called), the run stops with an error and the status 502.
  • The URL is recognised only when it consists of the characters a–z, A–Z, 0–9 and / : . ? & = _ -. A URL with any other character — for example %, +, ,, ~, @, # or a space, also in the value of a $ form variable written into it — is not recognised as an HTTP request, and the statement goes to the database as SQL. In a variable declaration (:result = GET('…');) a :variable in the URL is filled in after the URL is recognised, so its value may also contain other characters of a valid URL (such as % escapes). In a request that is a statement of its own or stands inside return(…) / returnk(…), the :variable is filled in first, so its value has to consist of the characters above as well.
  • Only http:// and https:// URLs are called, also after redirects, and only addresses on the public internet: a URL (or a redirect) that points to an address that is not public (loopback, private, link-local, carrier-grade NAT, reserved or multicast, such as localhost or 10.0.0.5) is not called. At most 20 redirects are followed, and a host name that cannot be resolved is not called either. In these cases the run stops with an error and the status 502; editors of the query see the URL with the message "This address is not called: it is an internal address of the server's network. Use a public address.", "This address is not called: it redirected too many times." or "The host name could not be resolved. Check the host name.". Everyone else gets "Something went wrong!"; the same applies to the other failures of a request (a refused connection, a timeout, a status of 400 or more).
  • A request, with its redirects, may take at most 100 seconds, and the server it calls has to accept the connection within a second. A redirect keeps the method, sends the body again only for 307 and 308, and leaves out the Authorization and Cookie headers when it leads to another scheme, host or port.
  • The certificate of an https address is not verified, so a self-signed or expired certificate is accepted.
  • A statement that contains an HTTP request is not run as SQL: use the request as a statement of its own, as the value of a variable or inside return(…) / returnk(…).

Helpers: return(); and returnk();​

The editor also offers return(); and returnk(); helpers for controlling query output flow. Insert them from autocomplete where you need to short-circuit or shape the returned result.

return(); answers with its value as it is: a JSON object or array as application/json, any other text — also a number such as return('123'); or return('true'); — as an HTML page (text/html). A browser shows the text and the inline styles of such a page, loads its styles, images, fonts and media only from https or data: addresses and its frames only from https addresses, but runs no script in it and sends no form from it. Calls of the public query API keep their JSON content type. returnk(); always answers with JSON, wrapping its value in an envelope: {"status": 1, "response": …}. status is 1 when the status of the answer is 200, 201 or 202 at that point, otherwise 0; response holds the value, as nested JSON when the value is a JSON object or array. Any other value, also a number such as returnk('123');, is a text ("response":"123"), and a value of null (in any letter case) gives an empty text.

Putting it together​

A robust API query often combines several directives, one set per statement:

INSERT INTO signups (email) VALUES ('$email')
ON ERROR RETURN 'Could not register that email' SET HTTPCODE '422'
ON ERROR POST '{"text": "A signup failed"}' TO 'https://hooks.example.com/signup-failed';
SELECT id, email FROM signups WHERE email = '$email'
ON SUCCESS POST '{"text": "New signup"}' TO 'https://hooks.example.com/new-signup';

This returns a clean error message with status 422 and alerts a webhook when the insert fails; after a successful insert the second statement runs and notifies another webhook — all without any backend code. A webhook directive takes effect only when its statement is reached, so the ON ERROR webhook sits on the statement that can fail.