Search docs.molo17.com

    Gluesync Courier logo Stored procedures and functions (Courier routine routes)

    Stored procedures and functions

    A routine route (operation EXECUTE) calls a stored procedure or a function of the target database of a pipeline and answers what it returns, as JSON or XML. It turns place_order(customer, amount) into POST /api-inbound/shop/orders, and customer_total(customer) into GET /api-inbound/shop/customers/acme/total, without writing a line of service code.

    It is configured in two places, on purpose:

    • The route is the API’s contract, defined in Courier  Inbound  Procedures: what the request carries (its bindings), how the call runs (read-only, own transaction, timeout) and what it answers (its return type). It names no routine, so the API can be designed, previewed and handed to its clients before anyone picks the database code behind it.

    • The entity is the implementation, configured in the pipeline of the HTTP Source the collection is attached to: its target is the routine, and its mapping says which binding feeds which parameter and which output gives the answer. Every call goes through the entity, so its metrics and its log are where the calls are followed, like any other entity of the pipeline.

    The rest of the inbound model is the one of every route: the collection, its base path, the tokens, the attachment to one HTTP Source and the inbound server are described in HTTP Source.

    HTTP client ── POST /api-inbound/shop/orders ──▶ Core Hub inbound server ──▶ entity of the route
                ◀── 200 {"outputs": …} / 4xx / 5xx ──│ token, bindings                │ binding → parameter
                                                      │                               ▼
                                                      └── answer ◀── Query Studio, as the token's owner ──▶ CALL shop.place_order(?, ?, ?)

    Unlike a write route, a routine call is synchronous: nothing is queued, and the client gets the routine’s answer.

    Prerequisites

    • Core Hub with Courier routine routes (see the agent changelog);

    • A pipeline whose source is the HTTP Source, attached to the collection of the route, and whose target agent is a SQL database that holds the routine (see Supported databases);

    • A Personal API Token with the HTTPS agent permission, owned by a user whose role may run writable queries (a Manager or a Super Admin) and who is under no Query Studio data-access policy that can deny something: a routine runs code the caller cannot read, and the tables it touches cannot be checked against a policy.

    The route: the contract

    In Courier  Inbound open the collection, then the Procedures tab, and choose New endpoint. The form has a Bindings tab and an Options tab.

    • Endpoint name: the source table the pipeline will see.

    • HTTP method and Path: POST, or GET too when the route is read-only; the path is relative to the base path, with {name} placeholders for PATH bindings.

    • Bindings: the values the request carries, as for any route (PATH, QUERY, HEADER and BODY, typed STRING, NUMBER or BOOLEAN, required or with a default). A routine call reads a JSON body, top-level keys only: a dotted BODY binding is refused. A route with no BODY binding reads no body, and ignores whatever a client sends. A HEADER binding reads the request header of its name, ignoring case; credential headers cannot be bound.

    • Options:

      • The routine only reads (read-only): the call runs in a transaction rolled back at the end, so what the routine writes is undone where the database keeps it in that transaction, and the route may be called with GET. It is no permission: any routine call needs the right to write. A SQL Server, MySQL, MariaDB, Oracle or Db2 procedure that commits by itself can still commit.

      • The routine commits or rolls back by itself (own transaction): for a routine that commits or rolls back by itself; the call runs in autocommit (a PostgreSQL procedure that runs COMMIT fails otherwise). Without it a call that may write runs in one transaction, committed when it succeeds and rolled back when it fails or times out. A route cannot be both read-only and own transaction.

      • Timeout (seconds): 1 to 3,600 seconds, 30 by default. Past it the call is cancelled and answered 504. Query Studio’s own ceiling still applies (300 seconds unless GLUESYNC_QUERY_STUDIO_MAX_TIMEOUT_MS raises it).

    • Return type: what every answer of the route is, whatever routine the entity calls:

      Body The answer

      ALL (Whole result)

      An object with outputs (every OUT and INOUT value, and a function’s return), resultSets (each result set as an array of rows) and affectedRows (the update counts the driver reports for the call).

      ROWS (Rows)

      The rows of the first result set, as an array of objects.

      VALUE (First value)

      The first column of the first row of the first result set: typically a document the routine built.

      OUTPUT (One output)

      The value of one OUT or INOUT parameter, or of a function’s return. Which one is the entity’s choice.

      and its Format, JSON or XML. * *Max rows: the most rows a call keeps, all its result sets together (200 by default).

    The preview of the route shows the URL, a sample request and the shape of its answer before any entity exists. The route’s table, as the pipeline sees it, has one column per binding plus _response, the column the entity maps the answer onto; its key is its required PATH bindings, or the request sequence.

    The entity: the implementation

    In the pipeline of the HTTP Source, create an entity whose source table is the route. On the target side the editor lists, for a routine route, the routines of the target agent instead of its tables: choose the schema and the stored procedure or function. Its columns are read from the database’s catalog:

    • one per parameter, in declaration order, typed as the database names it (numeric, varchar, jsonb), so the type mapping compares it with the binding mapped onto it;

    • the pieces of the answer: _result (everything), _rows (the rows of the first result set), _value (the first cell), _return (a function’s return) and each OUT or INOUT parameter by name.

    Then map:

    • each binding onto the IN or INOUT parameter it feeds. A parameter no binding is mapped onto is called with NULL. One binding per parameter.

    • one output onto _response: the piece that gives the route’s return type. _result (or nothing) for ALL, _rows for ROWS, _value for VALUE, _return or an OUT/INOUT parameter for OUTPUT.

    The output is never transformed: it is returned as the database gave it, in the route’s format. An entity with a mapping function, a field function or a UDF is refused, and so is one whose mapping is not a call (a binding onto an OUT parameter or onto a piece, two bindings onto one parameter, two pieces, a piece that is an IN parameter, an output that does not give the route’s return type). The entity needs no key, its target is never written, created or typed by Gluesync, and changing its mapping asks for no re-sync. Start it: a stopped entity answers 503.

    Table 1. Example: place_order
    Route column Routine column Why

    customer (BODY, STRING)

    p_customer (IN varchar)

    The binding feeds the parameter.

    amount (BODY, NUMBER)

    p_amount (IN numeric)

    note (BODY, STRING)

    not mapped

    p_note is called with NULL.

    _response

    _result

    The route answers ALL.

    The MCP tool draft_routine_entity of Core Hub drafts the whole entity from the route and the routine, mapping each parameter from the binding of its name.

    Try it

    The Try it panel of a routine route calls it through its entity, with the values you type, as you (the signed-in user), and shows the answer, its status and whether it was truncated. A route no entity is built on cannot be tried: the panel offers Create the entity, which opens the pipeline’s entity editor on the route. The Entity panel of the route shows the entity built on it, or why there is none (no HTTP Source attached, no entity, several entities). A try runs the routine for real: unless the route is read-only, what it writes is committed.

    Calling a routine route

    A procedure that answers everything (ALL, JSON)
    curl -s -X POST 'https://core-hub-host:8090/api-inbound/shop/orders' \
      -H 'Authorization: Bearer gsp_…' \
      -H 'Content-Type: application/json' \
      -d '{"customer":"acme","amount":12.50}'
    {"outputs":{"p_order_id":42,"p_total":15.25},"resultSets":[],"affectedRows":0}

    affectedRows is the sum of the update counts the database driver reports for the call, which differs from one database to another for the same routine:

    + * SQL Server reports one count per statement the procedure runs, and none under SET NOCOUNT ON; * MySQL and MariaDB report the count of the last statement of the procedure only; * PostgreSQL reports none for a CALL, so it is 0.

    + Return the counts your client needs as OUT parameters when they matter.

    A function’s return (OUTPUT, JSON), read-only, called with GET
    curl -s 'https://core-hub-host:8090/api-inbound/shop/customers/acme/total' \
      -H 'Authorization: Bearer gsp_…'
    1008.50
    The rows of a result set (ROWS, JSON)
    [{"id":1,"amount":120.50,"status":"shipped"},{"id":2,"amount":80.00,"status":"cancelled"}]
    A document the routine built (VALUE, XML)
    curl -s 'https://core-hub-host:8090/api-inbound/shop/orders/1/document' \
      -H 'Authorization: Bearer gsp_…'
    <?xml version="1.0" encoding="UTF-8"?><order><id>1</id><lines><qty>2</qty><sku>A-1</sku></lines><lines><qty>1</qty><sku>B-7</sku></lines><amount>120.50</amount><status>shipped</status><customer>acme</customer></order>
    An error the routine raises on purpose
    HTTP/1.1 422 Unprocessable Entity
    Content-Type: application/json
    
    {"error":"Order 999 does not exist"}

    How the answer is rendered

    • Every value is typed: numbers keep the database’s digits (120.50, never 120.5 or 1.205E2), booleans are true/false, NULL is null.

    • A document is parsed only where it is one: a column, an OUT parameter or a function’s return of a document type (xml, json, jsonb), SQL Server’s FOR JSON and FOR XML results (which the server splits over several rows, joined first), and the single value of a VALUE or OUTPUT answer. Any other text stays text. An XML document reaches a JSON caller as a JSON object (attributes under @attributes, text under #text, repeated elements as arrays), and a JSON document an XML caller as elements. XML the routine returned reaches an XML caller as the routine wrote it, namespaces and mixed content included, when it is well-formed XML 1.0 with every namespace prefix declared; otherwise it is converted like any other value. DTDs and external entities are refused.

    • In XML, the root element is always response (ALL, ROWS), value (VALUE) or the name of the output (OUTPUT), whatever the value holds: XML the routine returned sits inside it, so SQL Server’s FOR XML without ROOT keeps the same root for one row as for several; in ALL each result set is a resultSet element of row elements. Two names that become the same XML name keep an element each (unit_price, unit_price_2).

    • A row’s keys are its columns' labels, made unique: a column without a label is column<position>, a repeated label <label>_2.

    • Up to 16 result sets are kept, together capped at the route’s Max rows. An answer that holds only part of what the routine returned (rows past the cap, result sets past 16, a character LOB cut at 1,000,000 characters) carries the header X-Gluesync-Truncated: true.

    • While PII masking is on and the agent has any column classified as personal data, a routine’s output is masked failing closed: it has no table to trace, so every OUT value and every result column that names no table is masked, a personal-data column the routine renamed included. On an agent never classified, or whose columns are all dismissed, the output is not failed closed: only the names and values that look personal (an o_email, a card number) are masked. Classify the agent’s tables before you expose routines that return personal data.

    Status codes

    Status When

    200

    The routine ran; the body is the route’s return type.

    400

    A value does not fit its binding or its parameter (a number of more than 38 digits, a text longer than a SQL Server parameter takes), a body that is not a JSON object, or a database error of class 22 (bad value).

    401, 403

    As for any route; 403 also when the token’s owner is under a data-access policy that can deny something, or may not run writable queries.

    404

    No entity is built on the route.

    409

    Several entities are built on the route, the entity’s mapping is not a call, or a constraint of the database refused what the routine wrote.

    422

    The routine raised an error on purpose: PostgreSQL RAISE EXCEPTION (P0001), MySQL and MariaDB SIGNAL (any SQLSTATE), SQL Server THROW/RAISERROR of 50000 or more, Oracle RAISE_APPLICATION_ERROR (-20000 to -20999), Db2 SIGNAL (SQLCODE -438). The body carries the routine’s own first line, unless PII masking is on, which withholds it as it withholds any database message.

    500

    Any other database failure (a missing routine, a permission), a SQL Server document cut at the row limit (the call is rolled back unless it runs in its own transaction), or a PostgreSQL procedure that commits on a route without Own transaction, which no retry fixes.

    503

    The entity is stopped, the pipeline is not running, or 32 routine calls are already running (with Retry-After: 1).

    504

    The routine ran past the route’s timeout, or Query Studio’s ceiling; it was cancelled.

    A client sees the database’s message only for a 422, and never while PII masking is on. A Core Hub user trying the route sees more detail (the settings a 504 or 500 names).

    Supported databases

    Database Status Notes

    PostgreSQL

    ✅ verified

    Procedures (CALL) and functions (SELECT * FROM f(?)), functions returning a table included. OTHER parameters (jsonb, uuid, …) are sent as text for the database to cast. A procedure that commits needs Own transaction. timestamptz and timetz parameters keep their time zone.

    SQL Server

    ✅ verified

    Procedures and scalar functions. Text parameters carry their declared length and a longer value is a 400 (SQL Server would cut it silently). Text OUT values come back whole (nvarchar(max) included). Table-valued functions and datetimeoffset parameters are not supported.

    Oracle

    Supported

    Standalone procedures and functions; package members are not listed.

    MySQL

    ✅ verified

    Procedures and functions; no type with a time zone. A procedure and a function may share a name: each is listed and called as what it is.

    MariaDB

    Supported

    As MySQL.

    Db2

    Supported

    Procedures and functions (VALUES f(?)); table functions are not listed.

    PostgreSQL 16, SQL Server 2022 and MySQL 8 were tested end to end; on MariaDB, Oracle and Db2 the listing, the signature and the call are tested against the database itself. Names are found as the database stores them: place_order finds Oracle’s and Db2’s PLACE_ORDER. Routines in the database’s own schemas (information_schema, and by database pg_catalog, sys, SYSIBM, Oracle’s own accounts and APEX) are never listed nor called, and a routine with overloads is refused.

    Limits and security

    • Calling a routine takes the right to write, whatever the route declares, and is refused to a caller under a restrictive data-access policy. Give routine routes their own collection and tokens when only some clients may call them.

    • At most 32 routine calls run at once on a Core Hub; one more is a 503 with Retry-After: 1. A call is cancelled when the client goes away. Calls are not listed among Query Studio’s running queries.

    • Each call adds a row to Query Studio’s audit (origin courier), with the statement and no value.

    • A routine runs with the database user of the target agent: grant it EXECUTE on the routines you expose, and nothing more than they need.

    • Not supported: a form body, a dotted BODY binding, binary and SQLXML parameters, an xml OUT parameter on SQL Server, Oracle package members, table functions outside PostgreSQL, a second HTTP method per route.

    Guidelines

    • Design the contract first. Write the route with its bindings and return type, share its preview with the client team, then pick or write the routine.

    • Raise errors on purpose for business failures (RAISE EXCEPTION, THROW, SIGNAL): they reach the client as a 422 with your message, while every other database error stays hidden.

    • Mark read-only what only reads, so a mistake in the routine cannot write, and so the route can be a GET.

    • Return a document for nested answers. A routine that builds a JSON or XML document and a VALUE return type give the client exactly the shape you designed.

    • Keep the timeout short and the result sets bounded: a client waiting on a long routine holds a connection.