Stored Procedures & PL/pgSQL

Transactional multi-step procedures in SpydQL or PostgreSQL PL/pgSQL with IN/OUT/INOUT params, cursors, savepoints, and try/catch.

5 min read Programmability

Stored procedures execute multi-statement transactional business logic inside SpydDB's storage and MVCC transaction context. Rather than orchestrating N network round-trips from application code while holding locks open, callers invoke CALL my_proc(...) over PostgreSQL Wire, HTTP, gRPC, or any official SDK.

SpydDB compiles both native SpydQL procedural syntax and PostgreSQL PL/pgSQL (LANGUAGE plpgsql / LANGUAGE sql) into a single unified transactional runtime with strict security, savepoint, and recursion guarantees.


1. Creating Procedures (CREATE PROCEDURE)#

Native SpydQL Procedure Syntax#

Inside a native SpydQL procedure block, variable and parameter declarations (let, set, out/inout parameter names, select_into (...), catch <err>) use bare identifiers, while expressions reading a local variable or parameter prefix the identifier with $ ($cents, $from_id, $err):

sql
create [or replace] procedure <name>(
  [in | out | inout] <param>: <type> [= <default_expr>],
  ...
)
[security definer | security invoker]
as {
  <procedural_statements>
}

Example: atomic wallet transfer with explicit balance checks and structured out return values:

sql
create or replace procedure transfer_balance(
  in from_id: i64,
  in to_id: i64,
  in cents: i64,
  out from_remaining: i64
)
security definer
as {
  if $cents <= 0 {
    raise "transfer amount must be positive";
  }

  accounts
  | where id == $from_id
  | set { balance_cents: balance_cents - $cents };

  select_into strict (from_remaining) as
    accounts | where id == $from_id | pick balance_cents;

  if $from_remaining < 0 {
    raise "insufficient balance";
  }

  accounts
  | where id == $to_id
  | set { balance_cents: balance_cents + $cents };
};

PostgreSQL PL/pgSQL Dialect (LANGUAGE plpgsql)#

sql
CREATE OR REPLACE PROCEDURE settle_invoice(
  IN inv_id bigint,
  IN paid_cents bigint,
  INOUT status_out text DEFAULT 'pending'
)
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
DECLARE
  v_due bigint := 0;
BEGIN
  SELECT amount_cents INTO STRICT v_due FROM invoices WHERE id = inv_id;

  IF paid_cents < v_due THEN
    status_out := 'partial';
  ELSE
    UPDATE invoices SET status = 'paid' WHERE id = inv_id;
    status_out := 'settled';
  END IF;
END;
$$;

Calling & Dropping Procedures#

sql
-- Pass null placeholders for OUT parameters, or omit trailing OUT parameters
call transfer_balance(101, 202, 5000, null);
call tail_out(7);

-- Dropping a procedure
drop procedure if exists transfer_balance;

When a caller executes CALL at top level, any OUT and INOUT parameters are returned as a single-row result set containing one column per OUT/INOUT parameter (or accumulated rows if the procedure emits RETURN NEXT). Trailing OUT parameters can be omitted at the call site, or passed as null.


2. Parameter Modes, Defaults & Nested CALL Writeback#

ModePassed by callerReturned / written backDefault expression allowed
in (default)YesRead-only value in calleeYes (= expr / DEFAULT expr)
outOmitted (trailing) or null / caller $varYes (returned in CALL output & written back to caller $var)No
inoutYes (value or $var)Yes (reads initial value, writes updated value back)Yes

When one SpydQL procedure invokes another via nested call, passing $local_var in an out or inout position writes the final callee value straight back into the caller's local variable:

sql
create procedure stats(in a: i64, in b: i64, out sum: i64, out diff: i64, inout scale: i64) as {
  set sum = ($a + $b) * $scale;
  set diff = ($a - $b) * $scale;
  set scale = $scale + 1;
};

create procedure caller(x: i64) as {
  let s: i64 = 0;
  let d: i64 = 0;
  let k: i64 = 10;
  call stats($x, 3, $s, $d, $k);
  return $s + $d + $k;
};

-- Direct call returns (28, 12, 3); caller(5) returns 111
call stats(10, 4, null, null, 2);
call caller(5);

3. Native SpydQL Procedural Statements#

Every DDL/DML statement and pipeline stage is valid inside { ... }, alongside structured control flow and cursors:

Variables & Query Capture (let, set, select_into)#

sql
create procedure summarize_account(in acct_id: i64, out count_out: i64) as {
  let acc: i64 = 0;
  let i: i64 = 0;

  while $i < 5 {
    set i = $i + 1;
    if $i == 3 { continue; }
    case {
      when $i % 2 == 0 {
        set acc = $acc + $i * 10;
      }
      else {
        set acc = $acc + $i;
      }
    }
  }

  -- Assigns columns from a single-row pipeline into local variables
  -- Adding `strict` raises an error if zero rows or more than one row match
  select_into strict (count_out) as
    orders | where account_id == $acct_id | count;
};

Fixed Count & Pipeline Loops (repeat, while, for, case)#

sql
create procedure batch_classify() as {
  let score: i64 = 0;

  -- Fixed repeat loop exposes 1-based $iteration
  repeat 4 {
    case $iteration {
      when 1 { set score = $score + 10; }
      when 2 { set score = $score + 20; }
      when 3 { break; }
      else { set score = $score + 99; }
    }
  }

  -- Iterate every row yielded by any query pipeline
  for item in (orders | where status == "pending" | pick id, amount) {
    accounts | where id == $item.id | set { last_seen_amount: $item.amount };
  }

  return $score;
};

Native SpydQL Cursors#

sql
create procedure scan_orders(target_tier: text) as {
  cursor cur = orders | where tier == $target_tier | pick id, amount | sort id;
  let head: json = null;
  fetch from cursor cur into head;
  let total: i64 = $head.amount;
  for rec in cursor cur {
    set total = $total + $rec["amount"];
  }
  close cursor cur;
  return $total;
};

4. PL/pgSQL Compiler Features#

SpydDB compiles PostgreSQL CREATE FUNCTION / CREATE PROCEDURE ... LANGUAGE plpgsql blocks directly into executable engine steps:

ConstructSupported Forms
DECLARE blockScalar variables, CONSTANT, := / = / DEFAULT initializers, parameterized/unparameterized CURSOR FOR SELECT ...
Assignments & callsvar := expr;, PERFORM query;, CALL proc(...);, SELECT ... INTO [STRICT] vars ...;
ConditionalsIF ... THEN ... [ELSIF / ELSEIF ... THEN ...] [ELSE ...] END IF;, searched and simple CASE ... WHEN ... THEN ... [ELSE ...] END CASE;
LoopsLOOP ... END LOOP;, WHILE cond LOOP ... END LOOP;, FOR i IN [REVERSE] a..b [BY step] LOOP ... END LOOP;, FOR rec IN SELECT ... LOOP ... END LOOP;, FOR rec IN cursor LOOP ... END LOOP;
Loop exitsEXIT [WHEN cond];, CONTINUE [WHEN cond];
CursorsOPEN cur[(args)];, FETCH cur INTO var1, ...;, CLOSE cur;, FOR rec IN cur LOOP ... END LOOP;
Savepoints & exceptionsSAVEPOINT name;, ROLLBACK TO [SAVEPOINT] name;, RELEASE [SAVEPOINT] name;, BEGIN ... EXCEPTION WHEN ... THEN ... END; (exposes SQLERRM / sqlerrm)
Errors & exitsRETURN [expr];, RETURN NEXT expr1, expr2;, RETURN QUERY SELECT ...;, RAISE [EXCEPTION | NOTICE | WARNING] 'fmt %', arg;

5. Savepoints, Nested Transactions & Error Recovery#

Inside procedural SpydQL, try { ... } catch <err> { ... } executes the try block behind an internal savepoint. If any statement fails or executes raise "...", SpydDB rolls back only the mutations inside the try block and binds the error message into <err> (read via $err):

sql
create procedure safe_apply_fee(in acct_id: i64, out applied: bool) as {
  set applied = false;
  savepoint before_fee;

  try {
    accounts | where id == $acct_id | set { balance: balance - 500 };
    ledger | insert { account_id: $acct_id, delta: -500 };
    set applied = true;
    release savepoint before_fee;
  } catch err {
    rollback to savepoint before_fee;
    audit_events | insert { account_id: $acct_id, reason: $err };
  }
};

In PL/pgSQL, BEGIN ... EXCEPTION WHEN OTHERS THEN ... END; provides identical savepoint-isolated error handling and exposes the runtime message through SQLERRM.

Sub-Transactions (transaction { ... })#

Use transaction { ... } in top-level or standalone procedural execution blocks when grouping multiple DML steps into an explicit atomic scope. When a CALL runs outside an explicit BEGIN ... COMMIT transaction, SpydDB automatically wraps the entire procedure invocation in an implicit ACID transaction that commits on normal exit and rolls back cleanly on any unhandled error.


6. Security Model & Runtime Safety Ceilings#

SECURITY INVOKER vs SECURITY DEFINER#

  • SECURITY INVOKER (default): Every table read, write, row-level security (RLS) policy, and field mask runs under the caller's session roles and tenant context.
  • SECURITY DEFINER: Executes collection reads and writes under the procedure creator's identity (similar to PostgreSQL), allowing privileged workflows (for example transferring funds between restricted ledger tables or incrementing audit counters) while keeping raw table privileges locked away from application roles. Tenant boundaries remain enforced.

Built-In Safety Limits#

To prevent infinite recursion or accidental runaway loops from tying up server workers:

  • Maximum call stack depth (CALL recursion): 64 nested procedure invocations.
  • Maximum loop iteration cap: 10,000 loop iterations per procedure invocation (while, loop, integer for, and query for).
  • Exceeding either guard aborts the statement, rolls back uncommitted procedure writes, and returns a clear runtime error.