/* * pg_pure.c * A PostgreSQL procedural language whose functions are written in * Pure (https://agraef.github.io/pure-lang/), embedding libpure. * * The module backs two SQL languages that differ only in trust, each with its * own backend-local interpreter: * * pg_pure trusted; any user may create functions. Its interpreter is * created with libpure's --safe mode and armed after the SPI * bridge and the allowlisted modules are set up, so a function * body cannot escape the language (no extern, inline C, eval, * evalcmd, native/off-allowlist using, or dangerous prelude * functions). DESIGN.md section 9. * pg_pureu untrusted; superuser only. Its interpreter is unrestricted, so * Pure code may call any C function through extern -- the * plperlu analogue. * * A function body is a single Pure expression over the SQL argument names. * It is compiled once per backend as * __pg_pure_ a b = (); * cached per (oid, xmin, tid), and every call is a pure_appxv of the cached * closure. The parentheses around keep a stray ';' in the body from * leaking a global definition into the interpreter. * * Everything pg_pure adds to Pure lives in the "sql" namespace: sql::query, * sql::exec, sql::notice, sql::warning, sql::null, sql::error. * * The Pure/PostgreSQL boundary rules (DESIGN.md section 4) are correctness * invariants: no PostgreSQL ERROR may longjmp through Pure frames (SPI runs * under PG_TRY in an internal subtransaction and turns a SQL error into the * Pure exception sql::error), and no Pure exception may escape into * PostgreSQL (the x-variants hand the exception back and the handler turns it * into ereport after Pure has returned). */ #include "postgres.h" #include "access/htup_details.h" #include "access/xact.h" #include "catalog/pg_proc.h" #include "catalog/pg_type.h" #include "commands/event_trigger.h" #include "commands/trigger.h" #include "executor/spi.h" #include "executor/execExpr.h" #include "fmgr.h" #include "funcapi.h" #include "miscadmin.h" #include "nodes/miscnodes.h" #include "storage/ipc.h" #include "utils/array.h" #include "utils/builtins.h" #include "utils/guc.h" #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/hsearch.h" #include "utils/numeric.h" #include "utils/portal.h" #include "utils/resowner.h" #include "utils/syscache.h" #include "utils/tuplestore.h" /* * max_stack_depth moved from tcop/tcopprot.h (PG <= 17) to miscadmin.h (PG * 18). Include tcopprot.h unconditionally; on 18 it is harmless. */ #include "tcop/tcopprot.h" #include PG_MODULE_MAGIC; PG_FUNCTION_INFO_V1(pg_pure_call_handler); PG_FUNCTION_INFO_V1(pg_pure_inline_handler); PG_FUNCTION_INFO_V1(pg_pure_validator); PG_FUNCTION_INFO_V1(pg_pureu_call_handler); PG_FUNCTION_INFO_V1(pg_pureu_inline_handler); PG_FUNCTION_INFO_V1(pg_pureu_validator); void _PG_init(void); static Datum call_function(const char *lang, bool trusted, FunctionCallInfo fcinfo); static Datum call_trigger(const char *lang, bool trusted, FunctionCallInfo fcinfo); static Datum inline_block(const char *lang, bool trusted, FunctionCallInfo fcinfo); static void validate_function(const char *lang, bool trusted, Oid fn_oid, FunctionCallInfo fcinfo); /* GUC: modules every interpreter loads. */ static char *pg_pure_using = NULL; /* * Two interpreters per backend (backends are processes): an unrestricted one * for pg_pureu, and a sandboxed (--safe, armed) one for the trusted pg_pure. * They must not be shared: once armed, the safe interpreter refuses the * externs the untrusted setup needs. Each is created on first use of its * language. Symbols (sql::null, sql::error) have the same numeric tag in * either interpreter because libpure's symbol table is process-global. */ static pure_interp *interp_untrusted = NULL; static pure_interp *interp_trusted = NULL; /* * A cursor-backed stream is valid only within the pg_pure function call that * created it. Each call_function bumps spi_epoch on the way out (and closes * the call's cursors), so a stream forced after its call returned finds a * stale epoch and throws rather than touching a dropped portal. spi_active is * true only between the call's SPI_connect and SPI_finish. */ static uint64 spi_epoch = 0; static bool spi_active = false; #define PG_PURE_MAX_STREAMS 64 #define PG_PURE_STREAM_BATCH 64 typedef struct StreamState { bool in_use; uint64 epoch; /* the call epoch this cursor belongs to */ char portal[64]; /* cursor name; the Portal is found by name */ bool done; /* the cursor reached end */ } StreamState; static StreamState streams[PG_PURE_MAX_STREAMS]; /* * The trigger currently firing in this backend, or NULL. Set by call_trigger * for the duration of the body's evaluation; the pg_pure_trig_* externs read * it to build new, old and tg inside the body's Pure evaluation frame (where * compound-value construction is legal). Triggers do not nest within one Pure * call, so a single slot suffices. */ static TriggerData *current_trigdata = NULL; static int32_t sym_sql_null = 0; static int32_t sym_sql_error = 0; typedef struct CachedFunc { Oid fn_oid; TransactionId fn_xmin; ItemPointerData fn_tid; pure_expr *fun; /* the compiled closure, pure_new'd */ pure_interp *ip; /* the interpreter it was compiled in */ int nargs; Oid argtypes[FUNC_MAX_ARGS]; Oid rettype; bool retset; /* RETURNS SETOF: the body yields a list */ bool istrigger; /* compiled as a trigger (new old tg params) */ void *domain_extra; /* cached domain constraints, if rettype is one */ MemoryContext domain_cxt; /* context domain_extra lives in */ struct CachedFunc *next; } CachedFunc; static CachedFunc *func_cache = NULL; /* A SQL error caught inside an SPI call, waiting to be re-raised. */ static ErrorData *pending_pg_error = NULL; static pure_expr *datum_to_pure(Datum d, bool isnull, Oid type); static bool pure_to_datum(pure_expr *x, Oid type, Datum *d, bool *isnull, bool *overflow); static void throw_sql_error(const char *sqlstate, const char *msg); static pure_interp *ensure_interp(bool trusted); /* --- cooperative cancel ------------------------------------------------ */ static int interrupt_hook(void) { /* Read-only check of PostgreSQL's flags; no ereport from inside Pure. */ return (QueryCancelPending || ProcDiePending) ? 2 : 0; } static void pg_pure_exit(int code, Datum arg) { if (interp_untrusted) { pure_delete_interp(interp_untrusted); interp_untrusted = NULL; } if (interp_trusted) { pure_delete_interp(interp_trusted); interp_trusted = NULL; } } static void report_pure_failure(const char *lang, const char *what, pure_expr *exc) { char *msg = NULL; /* An uncaught sql::error from SPI: re-raise the original SQL error. */ if (pending_pg_error) { ErrorData *edata = pending_pg_error; bool is_sql_error = false; pending_pg_error = NULL; /* * sql::error st msg is the nested application ((sql::error st) msg), * so peel two levels and check the head symbol. */ if (exc) { pure_expr *f1, *a1, *f2, *a2; int32_t sym; if (pure_is_app(exc, &f1, &a1) && pure_is_app(f1, &f2, &a2) && pure_is_symbol(f2, &sym) && sym == sym_sql_error) is_sql_error = true; } if (is_sql_error) { pure_freenew(exc); /* x-variants return it unreferenced */ ReThrowError(edata); } FreeErrorData(edata); /* Pure caught it and failed otherwise */ } /* Cancel/terminate: let PostgreSQL raise its own error. */ CHECK_FOR_INTERRUPTS(); if (exc) { char *s = str(exc); msg = pstrdup(s ? s : "?"); free(s); pure_freenew(exc); } else { const char *e = lasterr(); msg = pstrdup(e && *e ? e : "failed match"); } ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("%s: %s: %s", lang, what, msg))); } /* --- SPI exported to Pure ---------------------------------------------- */ /* * Run sql in an internal subtransaction, as PL/Python does, so that if it * fails and Pure code catches the error and carries on, the resources the * failed query held (locks, pins, catalog cache references, memory) are * released with the subtransaction. */ /* * Convert one Pure value used as a query parameter into a Datum, inferring * the SQL type from the Pure value's runtime shape. Supported: sql::null * (a SQL NULL), machine int (INT8), double (FLOAT8), string (TEXT), and * bigint (NUMERIC). Anything else is a type mismatch. The value is sent to * SPI as a Datum, never spliced into the SQL text, so it cannot be an * injection vector. */ static void pure_param_to_datum(pure_expr *x, Oid *type, Datum *value, char *nul) { int32_t sym; bool overflow; bool isnull; const char *s; double f; if (pure_is_symbol(x, &sym) && sym == sym_sql_null) { *type = TEXTOID; *value = (Datum) 0; *nul = 'n'; return; } *nul = ' '; if (pure_is_string(x, &s)) *type = TEXTOID; else if (pure_is_double(x, &f)) *type = FLOAT8OID; else if (pure_is_int(x, NULL)) *type = INT8OID; else if (pure_is_mpz(x, NULL)) *type = NUMERICOID; else ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("unsupported pg_pure query parameter"), errdetail("A parameter must be an int, a double, a string, a bigint, or sql::null."))); if (!pure_to_datum(x, *type, value, &isnull, &overflow)) ereport(ERROR, (errcode(overflow ? ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE : ERRCODE_DATATYPE_MISMATCH), errmsg("pg_pure query parameter does not fit its inferred type"))); } /* --- SPI plan cache ---------------------------------------------------- */ /* * A repeated query (the same text and the same inferred parameter types, * e.g. a sql::query called in a loop) is planned once and the saved plan is * reused. SPI_keepplan moves the plan into CacheMemoryContext, so it outlives * the per-call SPI_connect/SPI_finish and the internal subtransaction each * query runs in. PostgreSQL's plan cache revalidates a saved plan on its own * when search_path, the current role, or a referenced object changes, so the * cache key is only the query text and the parameter type Oids: the same text * with int parameters and with double parameters needs, and gets, different * plans. */ #define PG_PURE_PLAN_CACHE_MAX 128 typedef struct PlanCacheEntry { char key[NAMEDATALEN * 4]; /* argcount:oids:sql, truncated to fit */ SPIPlanPtr plan; uint64 last_used; } PlanCacheEntry; static HTAB *plan_cache = NULL; static uint64 plan_cache_clock = 0; /* * Build the cache key for a query: the parameter count, the parameter type * Oids, then the SQL text. Including the Oids keeps differently-typed uses of * the same text in separate entries, which is a correctness requirement, not * an optimization. Returns false if the key would not fit the fixed buffer * (a very long query); the caller then skips the cache and plans inline. */ static bool plan_cache_key(char *buf, size_t buflen, const char *sql, int nargs, const Oid *argtypes) { StringInfoData k; bool fits; initStringInfo(&k); appendStringInfo(&k, "%d:", nargs); for (int i = 0; i < nargs; i++) appendStringInfo(&k, "%u,", argtypes[i]); appendStringInfoChar(&k, ':'); appendStringInfoString(&k, sql); fits = (k.len < (int) buflen); if (fits) memcpy(buf, k.data, k.len + 1); pfree(k.data); return fits; } /* * Return a saved SPI plan for (sql, argtypes), preparing and caching it on a * miss. Returns NULL only if the key does not fit (caller plans inline) or if * SPI_prepare fails (caller falls through to the normal error path). A plan * is inserted only after both SPI_prepare and SPI_keepplan succeed, so an * error never leaves a half-built entry. Must run with SPI connected. */ static SPIPlanPtr spi_cached_plan(const char *sql, int nargs, Oid *argtypes) { char key[NAMEDATALEN * 4]; PlanCacheEntry *entry; bool found; SPIPlanPtr plan; if (!plan_cache_key(key, sizeof key, sql, nargs, argtypes)) return NULL; /* too long to key; plan inline */ if (plan_cache == NULL) { HASHCTL ctl; memset(&ctl, 0, sizeof ctl); ctl.keysize = sizeof ((PlanCacheEntry *) 0)->key; ctl.entrysize = sizeof(PlanCacheEntry); ctl.hcxt = TopMemoryContext; plan_cache = hash_create("pg_pure SPI plans", 32, &ctl, HASH_ELEM | HASH_STRINGS | HASH_CONTEXT); } entry = hash_search(plan_cache, key, HASH_FIND, &found); if (found) { entry->last_used = ++plan_cache_clock; return entry->plan; } /* Miss: plan it. A failure here leaves the cache untouched. */ plan = SPI_prepare(sql, nargs, argtypes); if (plan == NULL) return NULL; if (SPI_keepplan(plan) != 0) return NULL; /* could not save; plan not cached */ /* Evict the least-recently-used entry if the cache is full. */ if (hash_get_num_entries(plan_cache) >= PG_PURE_PLAN_CACHE_MAX) { HASH_SEQ_STATUS seq; PlanCacheEntry *e; PlanCacheEntry *victim = NULL; hash_seq_init(&seq, plan_cache); while ((e = hash_seq_search(&seq)) != NULL) if (victim == NULL || e->last_used < victim->last_used) victim = e; if (victim) { SPIPlanPtr vp = victim->plan; char vkey[NAMEDATALEN * 4]; memcpy(vkey, victim->key, sizeof vkey); hash_search(plan_cache, vkey, HASH_REMOVE, NULL); SPI_freeplan(vp); } } entry = hash_search(plan_cache, key, HASH_ENTER, &found); entry->plan = plan; entry->last_used = ++plan_cache_clock; return plan; } /* * Convert the current SPI_tuptable's first n rows to a Pure list: a one-column * row is the bare value, a multi-column row a tuple. Shared by sql::query * (whole result) and sql::stream (one fetched batch). */ static pure_expr * spi_tuptable_to_list(uint64 n) { pure_expr **rows = palloc(sizeof(pure_expr *) * (n ? n : 1)); TupleDesc td = SPI_tuptable ? SPI_tuptable->tupdesc : NULL; pure_expr *result; for (uint64 i = 0; i < n; i++) { int nc = td->natts; pure_expr **cols = palloc(sizeof(pure_expr *) * nc); for (int c = 0; c < nc; c++) { bool isnull; Datum dv = SPI_getbinval(SPI_tuptable->vals[i], td, c + 1, &isnull); cols[c] = datum_to_pure(dv, isnull, TupleDescAttr(td, c)->atttypid); } rows[i] = nc == 1 ? cols[0] : pure_tuplev(nc, cols); pfree(cols); } result = pure_listv(n, rows); pfree(rows); return result; } /* * Build the raw hashpair row vector for a heap tuple: one "colname"=>value * per non-dropped attribute. A NULL column becomes sql::null. datum_to_pure * copies by-reference values into Pure's heap, so the result does not alias * the tuple. The caller (the trigger wrapper, in a Pure frame) turns this into * a canonical record with the Pure record function. */ static pure_expr * tuple_to_pure_record(HeapTuple tuple, TupleDesc tupdesc) { int natts = tupdesc->natts; Datum *values = palloc(sizeof(Datum) * natts); bool *nulls = palloc(sizeof(bool) * natts); pure_expr **pairs = palloc(sizeof(pure_expr *) * (natts ? natts : 1)); int np = 0; pure_expr *vec; heap_deform_tuple(tuple, tupdesc, values, nulls); for (int i = 0; i < natts; i++) { Form_pg_attribute att = TupleDescAttr(tupdesc, i); pure_expr *kv[2]; if (att->attisdropped) continue; kv[0] = pure_cstring_dup(NameStr(att->attname)); kv[1] = datum_to_pure(values[i], nulls[i], att->atttypid); pairs[np++] = pure_tuplev(2, kv); } pfree(values); pfree(nulls); /* * Return a frame-free list of (key, value) tuples. The compiled trigger * wrapper turns it into a canonical record (via __pg_pure_mkrec) inside * its own Pure evaluation frame; building a record here with pure_app * would assert, because this C code runs before any Pure call is active. */ vec = pure_listv((size_t) np, pairs); pfree(pairs); if (vec == NULL) throw_sql_error("XX000", "pg_pure: could not build a row record"); return vec; } /* * Build the heap tuple a BEFORE-row trigger returns, from the record the body * returned. Starts from the original tuple (otup) and overrides only the * columns the record names, as PL/Python does: a column the record omits * keeps its original value, so returning a record with one changed key does * not null the rest. An unknown column, a system or generated column, or a * value that does not fit the column's type is a clean error, never a silent * wrong row. Returns a tuple allocated in the current (upper) memory context, * so call this after SPI_finish. */ static HeapTuple pure_record_to_tuple(pure_expr *rec, TupleDesc tupdesc, HeapTuple otup) { int natts = tupdesc->natts; Datum *modvalues = palloc0(sizeof(Datum) * natts); bool *modnulls = palloc0(sizeof(bool) * natts); bool *modrepls = palloc0(sizeof(bool) * natts); pure_expr **elems; size_t np; bool any = false; /* rec is already a list of "key"=>value pairs (the wrapper's __pg_pure_tro * packed the returned record into one, so no Pure call is needed here). * This runs after the Pure call returned, so errors go through ereport, * not pure_throw (there is no evaluation frame to catch a Pure exception). */ if (!pure_is_listv(rec, &np, &elems)) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("a BEFORE row trigger must return a record or sql::null"))); for (size_t i = 0; i < np; i++) { pure_expr *f1, *arrowsym, *key, *val; const char *colname; int attn; Form_pg_attribute att; bool isnull, overflow; /* each pair is (=>) key value */ if (!pure_is_app(elems[i], &f1, &val) || !pure_is_app(f1, &arrowsym, &key) || !pure_is_string(key, &colname)) { if (elems) free(elems); ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("a trigger record has a non-string key"))); } attn = SPI_fnumber(tupdesc, colname); if (attn == SPI_ERROR_NOATTRIBUTE) { if (elems) free(elems); ereport(ERROR, (errcode(ERRCODE_UNDEFINED_COLUMN), errmsg("pg_pure: the trigger record has no column \"%s\" in the row", colname))); } if (attn <= 0) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("pg_pure: cannot set system column \"%s\" from a trigger", colname))); att = TupleDescAttr(tupdesc, attn - 1); if (att->attgenerated != '\0') ereport(ERROR, (errcode(ERRCODE_GENERATED_ALWAYS), errmsg("pg_pure: cannot set generated column \"%s\" from a trigger", colname))); if (!pure_to_datum(val, att->atttypid, &modvalues[attn - 1], &isnull, &overflow)) { ereport(ERROR, (errcode(overflow ? ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE : ERRCODE_DATATYPE_MISMATCH), errmsg("pg_pure: trigger column \"%s\" value does not fit type %s", colname, format_type_be(att->atttypid)))); } modnulls[attn - 1] = isnull; modrepls[attn - 1] = true; any = true; } if (elems) free(elems); /* No column overridden: the row is unchanged; keep the original tuple. */ if (!any) return otup; return heap_modify_tuple(otup, tupdesc, modvalues, modnulls, modrepls); } static pure_expr * spi_run(const char *sql, bool want_rows, pure_expr *params) { pure_expr *volatile result = NULL; MemoryContext oldcxt = CurrentMemoryContext; ResourceOwner oldowner = CurrentResourceOwner; char *volatile sqlstate_copy = NULL; char *volatile errmsg_copy = NULL; BeginInternalSubTransaction(NULL); MemoryContextSwitchTo(oldcxt); PG_TRY(); { int rc; size_t np = 0; pure_expr **pe = NULL; if (params && !pure_is_listv(params, &np, &pe)) ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("pg_pure query parameters must be a list"))); if (np == 0) rc = SPI_execute(sql, false, 0); else { Oid *argtypes = palloc(sizeof(Oid) * np); Datum *values = palloc(sizeof(Datum) * np); char *nulls = palloc(np); SPIPlanPtr plan; for (size_t i = 0; i < np; i++) pure_param_to_datum(pe[i], &argtypes[i], &values[i], &nulls[i]); /* Reuse a saved plan when the text and parameter types repeat. */ plan = spi_cached_plan(sql, (int) np, argtypes); if (plan) rc = SPI_execute_plan(plan, values, nulls, false, 0); else rc = SPI_execute_with_args(sql, (int) np, argtypes, values, nulls, false, 0); } if (pe) free(pe); if (rc < 0) elog(ERROR, "SPI_execute failed: %s", SPI_result_code_string(rc)); if (!want_rows) result = pure_int64((int64_t) SPI_processed); else result = spi_tuptable_to_list(SPI_processed); ReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldcxt); CurrentResourceOwner = oldowner; } PG_CATCH(); { ErrorData *edata; /* * Copy the error in a context that outlives the subtransaction we are * about to roll back, then flush. CopyErrorData requires we are not in * ErrorContext, so switch to TopMemoryContext first. */ MemoryContextSwitchTo(TopMemoryContext); edata = CopyErrorData(); FlushErrorState(); RollbackAndReleaseCurrentSubTransaction(); MemoryContextSwitchTo(oldcxt); CurrentResourceOwner = oldowner; if (pending_pg_error) FreeErrorData(pending_pg_error); pending_pg_error = edata; sqlstate_copy = pstrdup(unpack_sql_state(edata->sqlerrcode)); errmsg_copy = pstrdup(edata->message ? edata->message : ""); if (result) pure_freenew(result); result = NULL; } PG_END_TRY(); if (!result) { /* * Throw sql::error "SQLSTATE" "message". This unwinds the Pure frames, * not PostgreSQL's. If Pure catches it the transaction continues; if * not, report_pure_failure re-raises pending_pg_error unchanged. */ pure_expr *e = pure_symbol(sym_sql_error); e = pure_app(e, pure_cstring_dup(sqlstate_copy ? sqlstate_copy : "XX000")); e = pure_app(e, pure_cstring_dup(errmsg_copy ? errmsg_copy : "")); pure_throw(e); } return result; } PGDLLEXPORT pure_expr *pg_pure_spi_query(const char *sql); PGDLLEXPORT pure_expr *pg_pure_spi_exec(const char *sql); PGDLLEXPORT pure_expr *pg_pure_spi_query_p(const char *sql, pure_expr *params); PGDLLEXPORT pure_expr *pg_pure_spi_exec_p(const char *sql, pure_expr *params); PGDLLEXPORT void pg_pure_notice(const char *msg); PGDLLEXPORT void pg_pure_warning(const char *msg); PGDLLEXPORT pure_expr *pg_pure_spi_stream_open(const char *sql, pure_expr *params); PGDLLEXPORT pure_expr *pg_pure_spi_stream_fetch(int32_t handle); PGDLLEXPORT pure_expr *pg_pure_trig_new(int32_t ignore); PGDLLEXPORT pure_expr *pg_pure_trig_old(int32_t ignore); PGDLLEXPORT pure_expr *pg_pure_trig_tg(int32_t ignore); static pure_expr *trigger_info_record(TriggerData *td); pure_expr * pg_pure_spi_query(const char *sql) { return spi_run(sql, true, NULL); } pure_expr * pg_pure_spi_exec(const char *sql) { return spi_run(sql, false, NULL); } pure_expr * pg_pure_spi_query_p(const char *sql, pure_expr *params) { return spi_run(sql, true, params); } pure_expr * pg_pure_spi_exec_p(const char *sql, pure_expr *params) { return spi_run(sql, false, params); } void pg_pure_notice(const char *msg) { ereport(NOTICE, (errmsg_internal("%s", msg ? msg : ""))); } void pg_pure_warning(const char *msg) { ereport(WARNING, (errmsg_internal("%s", msg ? msg : ""))); } /* * Mark the start of a function call's SPI session. Streams opened during the * call are valid only until spi_call_end bumps the epoch. */ static void spi_call_begin(void) { spi_active = true; } /* * End a function call's SPI session: close any cursors it opened and bump the * epoch so an outstanding stream handle forced later fails its epoch check and * throws rather than touching a dropped portal. Call immediately before * SPI_finish, while SPI is still connected (SPI_cursor_close needs it). */ static void spi_call_end(void) { for (int i = 0; i < PG_PURE_MAX_STREAMS; i++) { if (streams[i].in_use) { Portal p = SPI_cursor_find(streams[i].portal); if (p != NULL && PortalIsValid(p)) SPI_cursor_close(p); streams[i].in_use = false; } } spi_active = false; spi_epoch++; } /* * Throw a Pure sql::error exception directly (no ereport, nothing to unwind on * the PostgreSQL side). Used by the stream fetch when its cursor is no longer * valid: this unwinds Pure frames, it does not longjmp through them. Does not * return. */ static void throw_sql_error(const char *sqlstate, const char *msg) { pure_expr *e = pure_symbol(sym_sql_error); e = pure_app(e, pure_cstring_dup(sqlstate)); e = pure_app(e, pure_cstring_dup(msg)); pure_throw(e); pg_unreachable(); } /* * sql::stream opens a cursor and hands back a small integer handle into the * per-call stream registry. The lazy Pure wrapper (see the interpreter setup) * drives it with pg_pure_spi_stream_fetch. The cursor is valid only for this * function call: call_function closes it and bumps spi_epoch before * SPI_finish, so a handle forced after the call returned fails the epoch check * in fetch and throws. Returns the handle as a Pure int. */ pure_expr * pg_pure_spi_stream_open(const char *sql, pure_expr *params) { int slot; size_t np = 0; pure_expr **pe = NULL; SPIPlanPtr plan; Oid *argtypes = NULL; Datum *values = NULL; char *nulls = NULL; Portal portal; if (params && !pure_is_listv(params, &np, &pe)) throw_sql_error("42804", "pg_pure stream parameters must be a list"); for (slot = 0; slot < PG_PURE_MAX_STREAMS; slot++) if (!streams[slot].in_use) break; if (slot == PG_PURE_MAX_STREAMS) { if (pe) free(pe); throw_sql_error("53400", "too many open pg_pure streams"); } if (np > 0) { argtypes = palloc(sizeof(Oid) * np); values = palloc(sizeof(Datum) * np); nulls = palloc(np); for (size_t i = 0; i < np; i++) pure_param_to_datum(pe[i], &argtypes[i], &values[i], &nulls[i]); } if (pe) free(pe); /* * Open the cursor at the SPI-connection level (not inside a per-query * subtransaction), so it lives for the whole function call. A saved plan * from the cache backs it. SPI rejects a non-SELECT as a cursor. */ plan = spi_cached_plan(sql, (int) np, argtypes); if (plan == NULL) { plan = SPI_prepare(sql, (int) np, argtypes); if (plan == NULL) throw_sql_error("42601", psprintf("pg_pure stream: %s", SPI_result_code_string(SPI_result))); } snprintf(streams[slot].portal, sizeof streams[slot].portal, "pgpure_stream_%d_%d", MyProcPid, slot); portal = SPI_cursor_open(streams[slot].portal, plan, values, nulls, false); if (portal == NULL) throw_sql_error("34000", "pg_pure stream: could not open the cursor"); streams[slot].in_use = true; streams[slot].epoch = spi_epoch; streams[slot].done = false; return pure_int(slot); } /* * Fetch the next batch of a stream and return it as a Pure list, or [] at the * end. The safety checks run first and throw a Pure sql::error if the cursor * is no longer usable (the call that opened it has returned, so the portal was * dropped): the portal is found fresh by name, never from a stored pointer, so * a force after the call cannot touch freed memory. */ pure_expr * pg_pure_spi_stream_fetch(int32_t handle) { StreamState *s; Portal portal; pure_expr *rows; if (handle < 0 || handle >= PG_PURE_MAX_STREAMS || !streams[handle].in_use) throw_sql_error("34000", "pg_pure stream: invalid handle"); s = &streams[handle]; /* The call that opened the cursor has ended: the portal is gone. */ if (s->epoch != spi_epoch || !spi_active) throw_sql_error("55000", "pg_pure stream used after its function returned"); if (s->done) return pure_listv(0, NULL); /* Find the portal fresh by name; never dereference a stored pointer. */ portal = SPI_cursor_find(s->portal); if (portal == NULL || !PortalIsValid(portal)) throw_sql_error("34000", "pg_pure stream: the cursor is no longer open"); SPI_cursor_fetch(portal, true, PG_PURE_STREAM_BATCH); if (SPI_processed == 0) { s->done = true; return pure_listv(0, NULL); } rows = spi_tuptable_to_list(SPI_processed); return rows; } /* * Trigger row/info externs. The compiled trigger wrapper calls these to bind * new, old and tg, so the compound values they return are built inside the * body's Pure evaluation frame (building a list or tuple needs an active * frame). new and old return a list of (key, value) tuples, or sql::null when * the event has no such row; tg always returns its list of fields. The * wrapper canonicalizes each into a record. */ pure_expr * pg_pure_trig_new(int32_t ignore) { TriggerData *td = current_trigdata; HeapTuple tup = NULL; (void) ignore; if (td && TRIGGER_FIRED_FOR_ROW(td->tg_event)) { if (TRIGGER_FIRED_BY_INSERT(td->tg_event)) tup = td->tg_trigtuple; else if (TRIGGER_FIRED_BY_UPDATE(td->tg_event)) tup = td->tg_newtuple; } if (!tup) return pure_symbol(sym_sql_null); return tuple_to_pure_record(tup, td->tg_relation->rd_att); } pure_expr * pg_pure_trig_old(int32_t ignore) { TriggerData *td = current_trigdata; HeapTuple tup = NULL; (void) ignore; if (td && TRIGGER_FIRED_FOR_ROW(td->tg_event)) { if (TRIGGER_FIRED_BY_UPDATE(td->tg_event) || TRIGGER_FIRED_BY_DELETE(td->tg_event)) tup = td->tg_trigtuple; } if (!tup) return pure_symbol(sym_sql_null); return tuple_to_pure_record(tup, td->tg_relation->rd_att); } pure_expr * pg_pure_trig_tg(int32_t ignore) { (void) ignore; if (!current_trigdata) return pure_symbol(sym_sql_null); return trigger_info_record(current_trigdata); } /* --- type mapping ------------------------------------------------------ */ static bool type_supported(Oid t) { /* A domain is supported exactly when its base type is. */ t = getBaseType(t); switch (t) { case INT2OID: case INT4OID: case INT8OID: case FLOAT4OID: case FLOAT8OID: case BOOLOID: case TEXTOID: case VARCHAROID: case NUMERICOID: case FLOAT8ARRAYOID: case BYTEAOID: return true; default: return false; } } /* * numeric -> Pure. An integral numeric becomes a Pure bigint (exact); a * fractional one becomes an exact rational num % den (needs the math module). * NaN and +/-Infinity have no rational form and become doubles. Nothing is * rounded. Built as text handed to pure_eval so we need no GMP headers here. */ static pure_expr * numeric_to_pure(Datum d) { Numeric n = DatumGetNumeric(d); char *s; pure_expr *x; StringInfoData buf; if (numeric_is_nan(n) || numeric_is_inf(n)) return pure_double(DatumGetFloat8(DirectFunctionCall1(numeric_float8, d))); s = DatumGetCString(DirectFunctionCall1(numeric_out, d)); initStringInfo(&buf); if (strchr(s, '.') == NULL && strchr(s, 'e') == NULL && strchr(s, 'E') == NULL) /* Integral: a bigint literal, e.g. 42L. */ appendStringInfo(&buf, "%sL", s); else { /* * Fractional: rational (mantissa * 10^-scale), e.g. 12.5 becomes * 125L%10L, which math normalizes to 25L%2L. Build it from the digits * so no double is involved. */ char *dot = strchr(s, '.'); int scale = dot ? (int) strlen(dot + 1) : 0; char *digits = palloc(strlen(s) + 1); char *w = digits; bool neg = (*s == '-'); char *m; for (char *r = s; *r; r++) if (*r != '.' && *r != '-' && *r != '+') *w++ = *r; *w = '\0'; /* * Strip leading zeros from the mantissa: Pure reads a literal with a * leading zero (0333) as octal, so 0.333 would become 219%1000, and a * mantissa with an 8 or 9 digit (0.123...) fails to parse at all. Keep * at least one digit. */ m = digits; while (m[0] == '0' && m[1] != '\0') m++; /* scale is bounded by numeric's digit count, so 10^scale as a literal is fine. */ appendStringInfo(&buf, "%s%sL%%1", neg ? "-" : "", m); for (int i = 0; i < scale; i++) appendStringInfoChar(&buf, '0'); appendStringInfoString(&buf, "L"); } x = pure_eval(buf.data); pfree(buf.data); pfree(s); if (!x) ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("pg_pure: cannot represent numeric value as a Pure number"), errhint("A rational result needs the math module; it is loaded by default via pg_pure.using."))); return x; } /* * float8[] -> Pure double matrix. A 1-D SQL array of n elements becomes a * 1-by-n Pure matrix (a row vector); a 2-D n-by-m array becomes an n-by-m * matrix. Higher dimensions and arrays containing NULL are rejected: a Pure * double matrix is a dense rectangle of doubles with no null slot. The SQL * array's own element order is row-major, which is what matrix_from_double_array * expects. */ static pure_expr * float8array_to_pure(Datum d) { ArrayType *a = DatumGetArrayTypeP(d); int ndim = ARR_NDIM(a); int *dims = ARR_DIMS(a); uint32_t n, m; Datum *elems; bool *nulls; int nelems; double *buf; pure_expr *x; if (ARR_ELEMTYPE(a) != FLOAT8OID) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("pg_pure: only float8[] arrays are supported"))); if (ndim == 0) return matrix_from_double_array(0, 0, NULL); /* empty matrix */ if (ndim > 2) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("pg_pure: float8[] with more than 2 dimensions is not supported"))); deconstruct_array(a, FLOAT8OID, sizeof(float8), FLOAT8PASSBYVAL, 'd', &elems, &nulls, &nelems); for (int i = 0; i < nelems; i++) if (nulls[i]) ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("pg_pure: a float8[] passed to Pure must not contain NULL elements"))); if (ndim == 1) { n = 1; m = (uint32_t) dims[0]; } else { n = (uint32_t) dims[0]; m = (uint32_t) dims[1]; } buf = palloc(sizeof(double) * (nelems ? nelems : 1)); for (int i = 0; i < nelems; i++) buf[i] = DatumGetFloat8(elems[i]); x = matrix_from_double_array(n, m, buf); /* copies buf */ pfree(buf); pfree(elems); pfree(nulls); if (!x) ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("pg_pure: could not build a Pure matrix from the float8[]"))); return x; } /* * bytea -> Pure. The bytes become a 1-by-n Pure int matrix, each element one * byte value (0..255). An int matrix holds any byte, including NUL, which a * Pure string cannot, so this round-trips arbitrary binary data. An empty * bytea becomes an empty matrix. */ static pure_expr * bytea_to_pure(Datum d) { bytea *b = DatumGetByteaPP(d); uint32_t n = (uint32_t) VARSIZE_ANY_EXHDR(b); unsigned char *p = (unsigned char *) VARDATA_ANY(b); int *ints; pure_expr *x; if (n == 0) return matrix_from_int_array(0, 0, NULL); ints = palloc(sizeof(int) * n); for (uint32_t i = 0; i < n; i++) ints[i] = p[i]; x = matrix_from_int_array(1, n, ints); /* copies ints */ pfree(ints); if (!x) ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("pg_pure: could not build a Pure matrix from the bytea"))); return x; } /* * Pure -> bytea. The value must be a Pure int matrix (or int vector); each * element is one byte and must be in 0..255, else the value does not fit a * byte and it is an error (never a silent truncation). Returns false on a * type mismatch so the caller reports it; sets *overflow for an out-of-range * element. */ static bool pure_to_bytea(pure_expr *x, Datum *d, bool *overflow) { void *mp; uint32_t sz; int *ints; bytea *b; unsigned char *w; if (!pure_is_int_matrix(x, &mp)) return false; sz = matrix_size(x); b = (bytea *) palloc(VARHDRSZ + (sz ? sz : 0)); SET_VARSIZE(b, VARHDRSZ + sz); if (sz == 0) { *d = PointerGetDatum(b); return true; } ints = palloc(sizeof(int) * sz); matrix_to_int_array(ints, x); /* respects stride */ w = (unsigned char *) VARDATA(b); for (uint32_t i = 0; i < sz; i++) { if (ints[i] < 0 || ints[i] > 255) { pfree(ints); pfree(b); *overflow = true; return false; } w[i] = (unsigned char) ints[i]; } pfree(ints); *d = PointerGetDatum(b); return true; } static pure_expr * datum_to_pure(Datum d, bool isnull, Oid type) { if (isnull) return pure_symbol(sym_sql_null); type = getBaseType(type); /* a domain converts as its base type */ switch (type) { case INT2OID: return pure_int(DatumGetInt16(d)); case INT4OID: return pure_int(DatumGetInt32(d)); case INT8OID: return pure_int64(DatumGetInt64(d)); case FLOAT4OID: return pure_double(DatumGetFloat4(d)); case FLOAT8OID: return pure_double(DatumGetFloat8(d)); case BOOLOID: return pure_int(DatumGetBool(d) ? 1 : 0); case NUMERICOID: return numeric_to_pure(d); case FLOAT8ARRAYOID: return float8array_to_pure(d); case BYTEAOID: return bytea_to_pure(d); default: { /* text, varchar, and (via SPI) any other type: its text form */ Oid out; bool isvarlena; char *s; pure_expr *x; getTypeOutputInfo(type, &out, &isvarlena); s = OidOutputFunctionCall(out, d); x = pure_string_dup(s); pfree(s); return x; } } } /* * Extract a 64-bit integer from a Pure int or bigint. Returns false if x is * neither, or if a bigint does not fit in int64. */ static bool pure_to_int64(pure_expr *x, int64 *out) { int32_t i; char *s; ErrorSaveContext escontext = {T_ErrorSaveContext}; Datum v; if (pure_is_int(x, &i)) { *out = i; return true; } if (!pure_is_mpz(x, NULL)) return false; /* * A bigint: parse its printed form (e.g. "123L") with int8in, which * range-checks into int64. Strip the trailing 'L'. pure_get_int64 * truncates silently, so it is not used here. */ s = str(x); if (s == NULL) return false; for (char *q = s; *q; q++) if (*q == 'L') { *q = '\0'; break; } if (!DirectInputFunctionCallSafe(int8in, s, InvalidOid, -1, (Node *) &escontext, &v)) { free(s); return false; } free(s); if (escontext.error_occurred) return false; *out = DatumGetInt64(v); return true; } /* * Clean one part (numerator or denominator) of a Pure rational's printed form * in place: drop the L bigint markers and the parentheses Pure puts around a * negative numerator ((-15432L) -> -15432). Returns the first kept character, * since a leading '(' is skipped rather than shifted. */ static char * clean_rational_part(char *s) { char *w = s; char *start = s; bool seen = false; for (char *r = s; *r; r++) { if (*r == 'L' || *r == '(' || *r == ')' || *r == ' ') continue; if (!seen) { start = w; seen = true; } *w++ = *r; } *w = '\0'; return start; } /* * The exact number of fractional digits a rational num/den needs, when den is * a positive integer: den must divide 10^k for some k, and the smallest such * k is max(v2, v5) where v2 and v5 are how many times 2 and 5 divide den. * Returns that k, or -1 if den has any other prime factor (the fraction does * not terminate in decimal, so no finite scale is exact). * * den arrives as a numeric Datum because a normalized remat like 15432%125 * (from 123.456) no longer has a power-of-ten denominator; the old * digit-count heuristic rounded such values. This factors den directly. */ static int terminating_scale(Datum den) { Datum zero = DirectFunctionCall1(int4_numeric, Int32GetDatum(0)); Datum two = DirectFunctionCall1(int4_numeric, Int32GetDatum(2)); Datum five = DirectFunctionCall1(int4_numeric, Int32GetDatum(5)); Datum one = DirectFunctionCall1(int4_numeric, Int32GetDatum(1)); Datum v = den; int v2 = 0, v5 = 0; /* Divide out all factors of 2, then all factors of 5. */ for (;;) { Datum r = DirectFunctionCall2(numeric_mod, v, two); if (DatumGetBool(DirectFunctionCall2(numeric_ne, r, zero))) break; v = DirectFunctionCall2(numeric_div_trunc, v, two); v2++; } for (;;) { Datum r = DirectFunctionCall2(numeric_mod, v, five); if (DatumGetBool(DirectFunctionCall2(numeric_ne, r, zero))) break; v = DirectFunctionCall2(numeric_div_trunc, v, five); v5++; } /* What remains must be 1 for the fraction to terminate. */ if (DatumGetBool(DirectFunctionCall2(numeric_ne, v, one))) return -1; return v2 > v5 ? v2 : v5; } /* * Pure -> Datum, range-checked. Returns false if x has no representation in * type (the caller reports a type mismatch) and sets *overflow when x is the * right kind of number but out of the type's range (the caller raises * numeric_value_out_of_range). */ static bool pure_to_datum(pure_expr *x, Oid type, Datum *d, bool *isnull, bool *overflow) { int32_t i; double f; const char *s; int32_t sym; int64 n64; *isnull = false; *overflow = false; /* A domain converts as its base type; the caller runs the constraint. */ type = getBaseType(type); if (pure_is_symbol(x, &sym) && sym == sym_sql_null) { *isnull = true; return true; } switch (type) { case INT2OID: if (!pure_to_int64(x, &n64)) return false; if (n64 < PG_INT16_MIN || n64 > PG_INT16_MAX) return (*overflow = true), false; *d = Int16GetDatum((int16) n64); return true; case INT4OID: if (!pure_to_int64(x, &n64)) return false; if (n64 < PG_INT32_MIN || n64 > PG_INT32_MAX) return (*overflow = true), false; *d = Int32GetDatum((int32) n64); return true; case BOOLOID: if (!pure_is_int(x, &i)) return false; *d = BoolGetDatum(i != 0); return true; case INT8OID: if (!pure_to_int64(x, &n64)) return false; *d = Int64GetDatum(n64); return true; case FLOAT4OID: case FLOAT8OID: if (pure_is_double(x, &f)) ; else if (pure_to_int64(x, &n64)) f = (double) n64; else return false; *d = type == FLOAT4OID ? Float4GetDatum((float4) f) : Float8GetDatum(f); return true; case NUMERICOID: { /* * Exact where Pure is exact. A double goes through * float8_numeric. An int or bigint prints as "123L" and a * rational as "25L%2L"; parse those into numerics with no * double in between. */ char *t; char *pct; if (pure_is_double(x, &f)) { *d = DirectFunctionCall1(float8_numeric, Float8GetDatum(f)); return true; } if (!pure_is_mpz(x, NULL) && !pure_is_int(x, &i)) { /* Could still be a rational application %\ x y. */ pure_expr *f1, *a1; if (!pure_is_app(x, &f1, &a1)) return false; } t = str(x); if (t == NULL) return false; pct = strchr(t, '%'); if (pct == NULL) { /* integral bigint/int: "123L" -> numeric */ char *num = pstrdup(t); for (char *p = num; *p; p++) if (*p == 'L') *p = '\0'; *d = DirectFunctionCall3(numeric_in, CStringGetDatum(num), ObjectIdGetDatum(InvalidOid), Int32GetDatum(-1)); pfree(num); } else { /* * Rational "NUM L % DEN L". numeric_div picks a result scale * from the operand magnitudes, which for large operands * rounds the fraction away. Force a scale wide enough: for a * numeric_to_pure builds mantissa % 10^k, but the math module * returns the rational in lowest terms, so the denominator is no * longer a power of ten (123.456 comes back as 15432 % 125). The * exact number of fractional digits is therefore derived from the * denominator's factors of 2 and 5, not its digit count. A * non-terminating rational (1 % 3) has no finite exact scale and is * rounded to a display scale, as numeric division always is. */ char *num = pstrdup(t); char *den; int scale; Datum nn, dd, q; den = strchr(num, '%'); *den++ = '\0'; /* * Pure prints a rational as NUM L % DEN L, and wraps a negative * numerator in parentheses: (-15432L)%125L. Strip the L markers * and the parentheses, in place, from both parts. */ num = clean_rational_part(num); den = clean_rational_part(den); nn = DirectFunctionCall3(numeric_in, CStringGetDatum(num), ObjectIdGetDatum(InvalidOid), Int32GetDatum(-1)); dd = DirectFunctionCall3(numeric_in, CStringGetDatum(den), ObjectIdGetDatum(InvalidOid), Int32GetDatum(-1)); /* * The exact fractional-digit count if the fraction terminates; * otherwise a display scale so a repeating fraction still returns * a sensible rounded value. */ scale = terminating_scale(dd); if (scale < 0) scale = NUMERIC_MAX_DISPLAY_SCALE; else if (scale > NUMERIC_MAX_DISPLAY_SCALE) scale = NUMERIC_MAX_DISPLAY_SCALE; /* * numeric_div chooses its result scale from the operand * magnitudes, which for a large numerator drops the last * fractional digits. Give the dividend that many fractional * digits up front (append a point and scale zeros) so the * quotient carries them, then round to the exact scale. */ { StringInfoData nbuf; initStringInfo(&nbuf); appendStringInfoString(&nbuf, num); appendStringInfoChar(&nbuf, '.'); for (int z = 0; z < scale; z++) appendStringInfoChar(&nbuf, '0'); nn = DirectFunctionCall3(numeric_in, CStringGetDatum(nbuf.data), ObjectIdGetDatum(InvalidOid), Int32GetDatum(-1)); pfree(nbuf.data); } q = DirectFunctionCall2(numeric_div, nn, dd); *d = DirectFunctionCall2(numeric_round, q, Int32GetDatum(scale)); pfree(num); } free(t); return true; } case TEXTOID: case VARCHAROID: /* * A text result must be a Pure string. An application that no rule * matched is a normal form (not a string), and turning it into * text with str would hide a type error as wrong text. */ if (pure_is_string(x, &s)) { *d = type == TEXTOID ? CStringGetTextDatum(s) : DirectFunctionCall3(varcharin, CStringGetDatum(s), ObjectIdGetDatum(InvalidOid), Int32GetDatum(-1)); return true; } return false; case FLOAT8ARRAYOID: { /* * A Pure double matrix becomes a float8[]: a 1-row matrix a * 1-D array, any other shape a 2-D n-by-m array (row-major, * which matrix_to_double_array produces). Anything that is not * a double matrix (a symbolic or int matrix, a scalar, an * unmatched application) is a type mismatch. */ void *mp; pure_expr *dimx; int32_t nrows, ncols; uint32_t sz; double *buf; Datum *elems; ArrayType *arr; if (!pure_is_double_matrix(x, &mp)) return false; /* matrix_dim returns the pair (rows, cols). */ dimx = matrix_dim(x); if (!dimx) return false; { size_t ndims; pure_expr **de; if (!pure_is_tuplev(dimx, &ndims, &de) || ndims != 2 || !pure_is_int(de[0], &nrows) || !pure_is_int(de[1], &ncols)) { if (ndims && de) free(de); pure_freenew(dimx); return false; } free(de); pure_freenew(dimx); } sz = matrix_size(x); buf = palloc(sizeof(double) * (sz ? sz : 1)); matrix_to_double_array(buf, x); /* respects stride */ elems = palloc(sizeof(Datum) * (sz ? sz : 1)); for (uint32_t i = 0; i < sz; i++) elems[i] = Float8GetDatum(buf[i]); if (nrows <= 1) arr = construct_array(elems, (int) sz, FLOAT8OID, sizeof(float8), FLOAT8PASSBYVAL, 'd'); else { int dims[2] = {nrows, ncols}; int lbs[2] = {1, 1}; arr = construct_md_array(elems, NULL, 2, dims, lbs, FLOAT8OID, sizeof(float8), FLOAT8PASSBYVAL, 'd'); } pfree(buf); pfree(elems); *d = PointerGetDatum(arr); return true; } case BYTEAOID: return pure_to_bytea(x, d, overflow); } return false; } /* --- interpreter and function cache ------------------------------------ */ /* * Return the backend's interpreter for the given language trust, creating it * on first use. The untrusted interpreter is unrestricted; the trusted one is * created with --safe, set up with the SPI bridge and the allowlisted modules * while still trusted, then armed so user code cannot escape the language. */ static pure_interp * ensure_interp(bool trusted) { char *argv_u[] = {"pg_pure", NULL}; char *argv_s[] = {"pg_pure", "--safe", NULL}; pure_interp **slot = trusted ? &interp_trusted : &interp_untrusted; pure_interp *ip; pure_expr *x; int32_t two = 0; const char *problem = NULL; StringInfoData setup; if (*slot) return *slot; ip = trusted ? pure_create_interp(2, argv_s) : pure_create_interp(1, argv_u); if (!ip) ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("pg_pure: cannot create the Pure interpreter"))); pure_switch_interp(ip); /* * Declare the sql namespace (sql::null and sql::error must be constant * symbols, or they would be variables in patterns) and bind the SPI/notice * externs. In the trusted interpreter this must happen before arming, * because arming refuses all externs; these are pg_pure's own C functions * and are safe. */ initStringInfo(&setup); appendStringInfoString(&setup, "namespace sql;\n" "nonfix null;\n" "public error query exec;\n" "extern expr* pg_pure_spi_query(char*) = query_;\n" "extern expr* pg_pure_spi_exec(char*) = exec_;\n" "extern expr* pg_pure_spi_query_p(char*, expr*) = query_p;\n" "extern expr* pg_pure_spi_exec_p(char*, expr*) = exec_p;\n" "query (q::string, ps::list) = query_p q ps;\n" "query q::string = query_ q;\n" "exec (q::string, ps::list) = exec_p q ps;\n" "exec q::string = exec_ q;\n" "extern expr* pg_pure_spi_stream_open(char*, expr*) = stream_open_;\n" "extern expr* pg_pure_spi_stream_fetch(int) = stream_fetch_;\n" "stream (q::string, ps::list) = stream_go (stream_open_ q ps);\n" "stream q::string = stream_go (stream_open_ q []);\n" "stream_go h = stream_rows (stream_fetch_ h) h;\n" "stream_rows [] h = [];\n" "stream_rows [r] h = r : stream_go h &;\n" "stream_rows (r:rs) h = r : stream_rows rs h &;\n" "extern void pg_pure_notice(char*) = notice;\n" "extern void pg_pure_warning(char*) = warning;\n" "namespace;\n" /* Trigger helpers and externs (top level). The externs * build new/old/tg inside the body's evaluation frame, * where building a list or record is legal; they take a * dummy int because a nullary C extern is awkward in * Pure. mkrec turns a (key, value) list into a record * (sql::null passes through); tro packs a record result * into a list of pairs the C side reads without a Pure * call. */ "extern expr* pg_pure_trig_new(int) = __pg_pure_tnew;\n" "extern expr* pg_pure_trig_old(int) = __pg_pure_told;\n" "extern expr* pg_pure_trig_tg(int) = __pg_pure_ttg;\n" "__pg_pure_mkrec sql::null = sql::null;\n" "__pg_pure_mkrec lst = record {k=>v | (k,v) = lst};\n" "__pg_pure_tro sql::null = sql::null;\n" "__pg_pure_tro v = list v if recordp v;\n" "__pg_pure_tro v = v otherwise;\n"); x = pure_eval(setup.data); pfree(setup.data); if (!x && *lasterr()) problem = pstrdup(lasterr()); /* * Load the configured modules. In the trusted interpreter, load each one * while still trusted and then allow it, so armed user code may say * "using ;" for a vetted module. A module that itself declares * externs (math declares log, pure_rational, ...) must be loaded here. */ if (!problem && pg_pure_using && *pg_pure_using) { char *list = pstrdup(pg_pure_using); char *tok; for (tok = strtok(list, " ,\t"); tok && !problem; tok = strtok(NULL, " ,\t")) { StringInfoData u; initStringInfo(&u); appendStringInfo(&u, "using %s;", tok); clear_lasterr(); x = pure_eval(u.data); pfree(u.data); if (!x && *lasterr()) { problem = psprintf("cannot load module \"%s\": %s", tok, lasterr()); break; } if (trusted) pure_safe_allow_using(tok); } pfree(list); } if (!problem) { clear_lasterr(); x = pure_eval("1+1"); if (!x || !pure_is_int(x, &two) || two != 2) problem = "the Pure prelude did not load; set PURELIB in the " "server's environment to the directory holding prelude.pure"; if (x) pure_freenew(x); } if (problem) { pure_delete_interp(ip); ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("pg_pure: cannot set up the %s interpreter: %s", trusted ? "trusted" : "untrusted", problem))); } /* Turn on sandbox enforcement last, after all trusted setup is done. */ if (trusted) pure_safe_arm(); sym_sql_null = pure_sym("sql::null"); sym_sql_error = pure_sym("sql::error"); pure_set_interrupt_hook(interrupt_hook); if (!IsUnderPostmaster) return ip; /* preloading: the postmaster keeps it for fork */ if (!interp_untrusted && !interp_trusted) on_proc_exit(pg_pure_exit, 0); *slot = ip; return ip; } static void set_stack_limit(void) { char here; /* Give Pure half of what is left of max_stack_depth from this frame. */ pure_set_stack_limit(&here, (size_t) max_stack_depth * 1024L / 2); } /* * Reject a function body that is not a single Pure expression. A body is * compiled as `__pg_pure_ args = (body);`, so the only way a body can * introduce a top-level definition (leaking a global rule or binding that * another function in the same backend would see) is to first close the * wrapping parenthesis with an unmatched ')'. A single balanced expression * never drives the bracket depth below zero and ends at depth zero. Scan the * body counting () [] {} depth, skipping string literals and comments so a * ')' inside text or a comment does not count. Return NULL if it is a single * expression, else a short reason. * * This is a correctness boundary for the trusted language, not a nicety: it * is what keeps one trusted function's interpreter state private from the * next. (The same check applies to pg_pureu; there the trust domain is a * single superuser, but the guarantee is cheap and uniform.) */ static const char * body_escapes_expression(const char *body) { int depth = 0; const char *p = body; while (*p) { if (p[0] == '/' && p[1] == '/') { while (*p && *p != '\n') p++; continue; } if (p[0] == '/' && p[1] == '*') { p += 2; while (*p && !(p[0] == '*' && p[1] == '/')) p++; if (*p) p += 2; continue; } if (*p == '"') { p++; while (*p && *p != '"') p += (*p == '\\' && p[1]) ? 2 : 1; if (*p) p++; continue; } if (*p == '(' || *p == '[' || *p == '{') depth++; else if (*p == ')' || *p == ']' || *p == '}') { if (--depth < 0) return "the body closes a bracket it did not open"; } p++; } if (depth != 0) return "the body leaves a bracket open"; return NULL; } static CachedFunc * compile_function(const char *lang, pure_interp *ip, Oid fn_oid, bool istrigger) { HeapTuple tup; Form_pg_proc proc; Datum src; char *body; char **argnames; Oid *argtypes; char *argmodes; int nargs; StringInfoData def; CachedFunc *cf; pure_expr *fun; char fname[64]; tup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid)); if (!HeapTupleIsValid(tup)) elog(ERROR, "cache lookup failed for function %u", fn_oid); proc = (Form_pg_proc) GETSTRUCT(tup); for (cf = func_cache; cf; cf = cf->next) if (cf->fn_oid == fn_oid && cf->ip == ip) { if (cf->fn_xmin == HeapTupleHeaderGetRawXmin(tup->t_data) && ItemPointerEquals(&cf->fn_tid, &tup->t_self)) { ReleaseSysCache(tup); return cf; } break; /* stale: recompile below, reuse the entry */ } nargs = get_func_arg_info(tup, &argtypes, &argnames, &argmodes); if (argmodes) for (int i = 0; i < nargs; i++) if (argmodes[i] != PROARGMODE_IN) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("%s functions support only IN arguments", lang))); if (!istrigger && !type_supported(proc->prorettype)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("%s functions cannot return type %s", lang, format_type_be(proc->prorettype)))); /* * RETURNS SETOF is supported for a supported element type; the * body yields a Pure list (or lazy stream) and each element is a row. * RETURNS TABLE(...) / SETOF (a RECORD result) is not yet * supported -- that needs multi-column tuple construction. */ if (proc->proretset && (proc->prorettype == RECORDOID || type_is_rowtype(proc->prorettype))) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("%s set-returning functions support only SETOF of a scalar or array type yet", lang), errdetail("RETURNS TABLE(...) and SETOF composite are not yet supported."))); for (int i = 0; !istrigger && i < nargs; i++) { if (!type_supported(argtypes[i])) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("%s functions cannot take type %s", lang, format_type_be(argtypes[i])))); if (!argnames || !argnames[i] || !*argnames[i]) ereport(ERROR, (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION), errmsg("%s function arguments must be named", lang))); } src = SysCacheGetAttrNotNull(PROCOID, tup, Anum_pg_proc_prosrc); body = TextDatumGetCString(src); snprintf(fname, sizeof fname, "__pg_pure_%u", fn_oid); initStringInfo(&def); /* * Leading "using MODULE;" statements load modules into the interpreter, * so they must sit at top level, not inside the function body. Peel them * off the front of the body and emit them before the definition. The rest * of the body is one expression. */ while (1) { char *p = body; char *semi; while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r') p++; if (strncmp(p, "using", 5) != 0 || (p[5] != ' ' && p[5] != '\t' && p[5] != '\n')) break; semi = strchr(p, ';'); if (!semi) break; appendBinaryStringInfo(&def, p, semi - p + 1); appendStringInfoChar(&def, '\n'); body = semi + 1; } appendStringInfoString(&def, fname); if (istrigger) appendStringInfoString(&def, " ()"); /* a nullary closure; rows come via externs */ else { for (int i = 0; i < nargs; i++) appendStringInfo(&def, " %s", argnames[i]); if (nargs == 0) appendStringInfoString(&def, " ()"); /* a zero-arg call takes () */ } /* * The body must be a single expression. Rejecting one that escapes its * parentheses is what stops a body from defining a top-level rule that a * later function in the same backend would inherit. */ { const char *bad = body_escapes_expression(body); if (bad) { pfree(def.data); ReleaseSysCache(tup); ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("%s function body must be a single expression", lang), errdetail("%s.", bad))); } } /* Parenthesize the body so a stray ';' cannot define a global rule. */ if (istrigger) /* * Canonicalize the raw row vectors into records (new/old, or * sql::null) and the tg vector into a record, bind them as the body's * new/old/tg, then pack a record result into a list of pairs for the C * side. All of this runs inside the body's Pure evaluation frame. */ appendStringInfo(&def, " = __pg_pure_tro ((%s) when new = __pg_pure_mkrec (__pg_pure_tnew 0); " "old = __pg_pure_mkrec (__pg_pure_told 0); tg = __pg_pure_mkrec (__pg_pure_ttg 0) end);\n%s;", body, fname); else appendStringInfo(&def, " = (%s);\n%s;", body, fname); set_stack_limit(); pure_switch_interp(ip); if (cf) { /* CREATE OR REPLACE: drop old rules, which Pure appends to otherwise. */ char clr[80]; char *out; snprintf(clr, sizeof clr, "clear %s\n", fname); out = pure_evalcmd(clr); free(out); } clear_lasterr(); fun = pure_eval(def.data); if (!fun || *lasterr()) { char *e = pstrdup(*lasterr() ? lasterr() : "no value"); if (fun) pure_freenew(fun); ReleaseSysCache(tup); ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("%s: cannot compile function \"%s\"", lang, NameStr(proc->proname)), errdetail("%s", e))); } if (!cf) { cf = MemoryContextAllocZero(TopMemoryContext, sizeof(CachedFunc)); cf->next = func_cache; func_cache = cf; } else if (cf->fun) pure_free(cf->fun); cf->fn_oid = fn_oid; cf->ip = ip; cf->fn_xmin = HeapTupleHeaderGetRawXmin(tup->t_data); cf->fn_tid = tup->t_self; cf->fun = pure_new(fun); cf->nargs = istrigger ? 3 : nargs; if (!istrigger) memcpy(cf->argtypes, argtypes, sizeof(Oid) * nargs); cf->rettype = proc->prorettype; cf->istrigger = istrigger; cf->retset = proc->proretset; /* Reset the domain-constraint cache: the return type may have changed. */ cf->domain_extra = NULL; cf->domain_cxt = TopMemoryContext; ReleaseSysCache(tup); return cf; } /* --- entry points ------------------------------------------------------ */ /* * A set-returning pg_pure function: the body yields a Pure list (or a lazy * stream), and each element becomes one row of a single-column result. The * rows are collected into a tuplestore (materialize mode). The list spine is * walked one cons cell at a time with pure_force, so a lazy stream is * realized incrementally and a CHECK_FOR_INTERRUPTS() between rows bounds an * over-long or infinite stream by cancel / statement_timeout. res is consumed * (freed) here. */ static Datum return_set(const char *lang, FunctionCallInfo fcinfo, CachedFunc *cf, pure_expr *res) { ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo; TupleDesc tupdesc; Tuplestorestate *tupstore; MemoryContext per_query; MemoryContext oldcxt; int32_t nil = pure_sym("[]"); pure_expr *cur; uint64 nrows = 0; /* * Materialize mode collects every row before the executor applies any * LIMIT, so it cannot stop an unbounded stream early. Cap the row count * so a body that yields an infinite stream fails with a clear error * instead of filling memory forever; a CHECK_FOR_INTERRUPTS() per row * also lets cancel / statement_timeout stop it. A caller that wants only * the first rows of a lazy stream should take them in Pure (take n ...). */ #define PG_PURE_MAX_SET_ROWS UINT64CONST(100000000) if (!rsinfo || !IsA(rsinfo, ReturnSetInfo) || !(rsinfo->allowedModes & SFRM_Materialize)) { pure_freenew(res); ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("%s set-returning function called in a context that cannot accept a set", lang))); } /* One result column, of the SETOF element type. */ per_query = rsinfo->econtext->ecxt_per_query_memory; oldcxt = MemoryContextSwitchTo(per_query); tupdesc = CreateTemplateTupleDesc(1); TupleDescInitEntry(tupdesc, 1, "value", cf->rettype, -1, 0); tupstore = tuplestore_begin_heap(true, false, work_mem); rsinfo->returnMode = SFRM_Materialize; rsinfo->setResult = tupstore; rsinfo->setDesc = tupdesc; MemoryContextSwitchTo(oldcxt); /* * Walk the list. A Pure list is either [] (the nil symbol) or an * application (:) head tail. pure_force realizes a thunk tail of a lazy * stream. Each head is converted with pure_to_datum, like a scalar * result, so the same range checks and type rules apply. */ cur = pure_force(res); for (;;) { pure_expr *f1, *head, *consf, *tail; int32_t sym; Datum d; bool isnull, overflow; CHECK_FOR_INTERRUPTS(); if (pure_is_symbol(cur, &sym) && sym == nil) break; /* end of list */ if (nrows >= PG_PURE_MAX_SET_ROWS) { pure_freenew(res); ereport(ERROR, (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), errmsg("%s set-returning function produced more than %llu rows", lang, (unsigned long long) PG_PURE_MAX_SET_ROWS), errhint("A lazy or infinite Pure stream must be bounded in the body, e.g. take n stream."))); } /* Expect (:) head tail: peel two applications. */ if (!pure_is_app(cur, &f1, &tail) || !pure_is_app(f1, &consf, &head)) { char *s = str(cur); char *msg = pstrdup(s ? s : "?"); free(s); pure_freenew(res); ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("%s set-returning function must yield a list, got %s", lang, msg))); } if (!pure_to_datum(head, cf->rettype, &d, &isnull, &overflow)) { char *s = str(head); char *msg = pstrdup(s ? s : "?"); free(s); pure_freenew(res); ereport(ERROR, (errcode(overflow ? ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE : ERRCODE_DATATYPE_MISMATCH), errmsg("%s: row value %s cannot be converted to %s", lang, msg, format_type_be(cf->rettype)))); } oldcxt = MemoryContextSwitchTo(per_query); { Datum vals[1]; bool nulls[1]; vals[0] = d; nulls[0] = isnull; tuplestore_putvalues(tupstore, tupdesc, vals, nulls); } MemoryContextSwitchTo(oldcxt); nrows++; cur = pure_force(tail); } pure_freenew(res); fcinfo->isnull = true; return (Datum) 0; } /* * Build the tg record describing the firing trigger: name, when, level, op, * table_name, table_schema, and args (a list of the trigger's static text * arguments). The field names match DESIGN section 2.5. */ static pure_expr * trigger_info_record(TriggerData *td) { Trigger *tg = td->tg_trigger; pure_expr *pairs[7]; pure_expr *argl; pure_expr *vec; const char *when, *level, *op; if (TRIGGER_FIRED_BEFORE(td->tg_event)) when = "BEFORE"; else if (TRIGGER_FIRED_AFTER(td->tg_event)) when = "AFTER"; else when = "INSTEAD OF"; level = TRIGGER_FIRED_FOR_ROW(td->tg_event) ? "ROW" : "STATEMENT"; if (TRIGGER_FIRED_BY_INSERT(td->tg_event)) op = "INSERT"; else if (TRIGGER_FIRED_BY_UPDATE(td->tg_event)) op = "UPDATE"; else if (TRIGGER_FIRED_BY_DELETE(td->tg_event)) op = "DELETE"; else op = "TRUNCATE"; /* args: a Pure list of the trigger's static text arguments. */ { pure_expr **av = palloc(sizeof(pure_expr *) * (tg->tgnargs ? tg->tgnargs : 1)); for (int i = 0; i < tg->tgnargs; i++) av[i] = pure_cstring_dup(tg->tgargs[i]); argl = pure_listv(tg->tgnargs, av); pfree(av); } /* Each field is a (key, value) 2-tuple; the wrapper records them. */ #define TG_PAIR(i, k, v) \ do { \ pure_expr *kv[2]; \ kv[0] = pure_cstring_dup(k); \ kv[1] = (v); \ pairs[i] = pure_tuplev(2, kv); \ } while (0) TG_PAIR(0, "name", pure_cstring_dup(tg->tgname)); TG_PAIR(1, "when", pure_cstring_dup(when)); TG_PAIR(2, "level", pure_cstring_dup(level)); TG_PAIR(3, "op", pure_cstring_dup(op)); TG_PAIR(4, "table_name", pure_cstring_dup(RelationGetRelationName(td->tg_relation))); TG_PAIR(5, "table_schema", pure_cstring_dup(get_namespace_name(RelationGetNamespace(td->tg_relation)))); TG_PAIR(6, "args", argl); #undef TG_PAIR vec = pure_listv(7, pairs); if (vec == NULL) throw_sql_error("XX000", "pg_pure: could not build the trigger record"); return vec; } /* * Run a trigger function. The body sees new, old and tg (see DESIGN 2.5): * new/old are the row records or sql::null, tg describes the event. For a * BEFORE-row trigger the return value becomes the stored row: a record (built * from the original row plus the record's overrides), or sql::null to skip the * operation. AFTER and statement triggers ignore the return. The returned * tuple is built after SPI_finish, in the upper memory context, so it survives * for the executor to store. */ static Datum call_trigger(const char *lang, bool trusted, FunctionCallInfo fcinfo) { TriggerData *td = (TriggerData *) fcinfo->context; TupleDesc tupdesc = td->tg_relation->rd_att; bool is_row = TRIGGER_FIRED_FOR_ROW(td->tg_event); bool is_before = TRIGGER_FIRED_BEFORE(td->tg_event); TriggerData *saved_td = current_trigdata; pure_interp *ip; CachedFunc *cf; pure_expr *args[1]; pure_expr *res, *exc = NULL; HeapTuple newtup = NULL; int rc; int32_t sym; bool ret_isnull; HeapTuple result; /* The row a BEFORE-row override is applied to (the op's new row). */ if (is_row) { if (TRIGGER_FIRED_BY_INSERT(td->tg_event)) newtup = td->tg_trigtuple; else if (TRIGGER_FIRED_BY_UPDATE(td->tg_event)) newtup = td->tg_newtuple; } ip = ensure_interp(trusted); pure_switch_interp(ip); cf = compile_function(lang, ip, fcinfo->flinfo->fn_oid, true); if ((rc = SPI_connect()) != SPI_OK_CONNECT) elog(ERROR, "SPI_connect failed: %s", SPI_result_code_string(rc)); SPI_register_trigger_data(td); spi_call_begin(); set_stack_limit(); pending_pg_error = NULL; /* * Publish this trigger's data for the pg_pure_trig_* externs, which the * wrapper calls (inside the evaluation frame below) to build new/old/tg. * The closure takes () as its single argument. Restore current_trigdata * even if an extern raises a PG error that longjmps out of the call. */ current_trigdata = td; args[0] = pure_tuplel(0); PG_TRY(); { res = pure_appxv(cf->fun, 1, args, &exc); } PG_FINALLY(); { current_trigdata = saved_td; } PG_END_TRY(); if (!res) { spi_call_end(); SPI_finish(); report_pure_failure(lang, "uncaught exception", exc); } /* * AFTER and statement triggers ignore the return value. Return a NULL * tuple pointer (not an SQL NULL): the executor reads the Datum as a * HeapTuple*, and isnull must stay false or it raises "returned null * value". A NULL pointer means "proceed with the row unchanged". */ if (!is_row || !is_before) { pure_freenew(res); spi_call_end(); SPI_finish(); fcinfo->isnull = false; return PointerGetDatum(NULL); } /* A BEFORE-row trigger: sql::null means skip the operation (NULL tuple). */ ret_isnull = pure_is_symbol(res, &sym) && sym == sym_sql_null; if (ret_isnull) { pure_freenew(res); spi_call_end(); SPI_finish(); fcinfo->isnull = false; return PointerGetDatum(NULL); } /* * Build the stored row after SPI_finish, in the upper memory context, so * it outlives SPI's context. The override is applied to the row the op * started with (the new row for INSERT/UPDATE). pure_record_to_tuple * errors cleanly if the body returned neither a record nor sql::null. */ spi_call_end(); SPI_finish(); result = pure_record_to_tuple(res, tupdesc, newtup); pure_freenew(res); fcinfo->isnull = false; return PointerGetDatum(result); } static Datum call_function(const char *lang, bool trusted, FunctionCallInfo fcinfo) { pure_interp *ip; CachedFunc *cf; pure_expr *args[FUNC_MAX_ARGS]; pure_expr *res, *exc = NULL; Datum d = (Datum) 0; bool isnull, overflow; int rc; if (CALLED_AS_TRIGGER(fcinfo)) return call_trigger(lang, trusted, fcinfo); if (CALLED_AS_EVENT_TRIGGER(fcinfo)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("%s does not support event triggers yet", lang))); ip = ensure_interp(trusted); pure_switch_interp(ip); cf = compile_function(lang, ip, fcinfo->flinfo->fn_oid, false); /* Convert arguments outside of any Pure call: they may ereport. */ for (int i = 0; i < cf->nargs; i++) args[i] = datum_to_pure(fcinfo->args[i].value, fcinfo->args[i].isnull, cf->argtypes[i]); if (cf->nargs == 0) args[0] = pure_tuplel(0); if ((rc = SPI_connect()) != SPI_OK_CONNECT) elog(ERROR, "SPI_connect failed: %s", SPI_result_code_string(rc)); spi_call_begin(); set_stack_limit(); pending_pg_error = NULL; res = pure_appxv(cf->fun, cf->nargs ? cf->nargs : 1, args, &exc); if (!res) { spi_call_end(); SPI_finish(); report_pure_failure(lang, "uncaught exception", exc); } if (cf->retset) { /* Collect the list into a tuplestore, then disconnect SPI. */ Datum set = return_set(lang, fcinfo, cf, res); spi_call_end(); SPI_finish(); return set; } if (!pure_to_datum(res, cf->rettype, &d, &isnull, &overflow)) { char *s = str(res); char *msg = pstrdup(s ? s : "?"); free(s); pure_freenew(res); spi_call_end(); SPI_finish(); if (overflow) ereport(ERROR, (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE), errmsg("%s: result %s is out of range for %s", lang, msg, format_type_be(cf->rettype)))); ereport(ERROR, (errcode(ERRCODE_DATATYPE_MISMATCH), errmsg("%s: result %s cannot be converted to %s", lang, msg, format_type_be(cf->rettype)), errhint("Check the argument types your rules expect; an " "unmatched application stays unevaluated in Pure."))); } pure_freenew(res); /* If the declared return type is a domain, enforce its constraints. */ if (cf->rettype != getBaseType(cf->rettype)) domain_check(d, isnull, cf->rettype, &cf->domain_extra, cf->domain_cxt); /* Copy a by-reference result out of SPI's memory before SPI_finish. */ if (!isnull && !get_typbyval(cf->rettype)) d = SPI_datumTransfer(d, false, get_typlen(cf->rettype)); spi_call_end(); SPI_finish(); fcinfo->isnull = isnull; return d; } static void validate_function(const char *lang, bool trusted, Oid fn_oid, FunctionCallInfo fcinfo) { pure_interp *ip; HeapTuple tup; bool istrigger; if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, fn_oid)) return; if (!check_function_bodies) return; tup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid)); if (!HeapTupleIsValid(tup)) elog(ERROR, "cache lookup failed for function %u", fn_oid); istrigger = ((Form_pg_proc) GETSTRUCT(tup))->prorettype == TRIGGEROID; ReleaseSysCache(tup); ip = ensure_interp(trusted); pure_switch_interp(ip); (void) compile_function(lang, ip, fn_oid, istrigger); } Datum pg_pure_call_handler(PG_FUNCTION_ARGS) { return call_function("pg_pure", true, fcinfo); } Datum pg_pure_inline_handler(PG_FUNCTION_ARGS) { return inline_block("pg_pure", true, fcinfo); } Datum pg_pure_validator(PG_FUNCTION_ARGS) { validate_function("pg_pure", true, PG_GETARG_OID(0), fcinfo); PG_RETURN_VOID(); } Datum pg_pureu_call_handler(PG_FUNCTION_ARGS) { return call_function("pg_pureu", false, fcinfo); } static Datum inline_block(const char *lang, bool trusted, FunctionCallInfo fcinfo) { InlineCodeBlock *codeblock = (InlineCodeBlock *) DatumGetPointer(PG_GETARG_DATUM(0)); pure_interp *ip; pure_expr *res, *exc = NULL; StringInfoData def; char *out; int rc; ip = ensure_interp(trusted); pure_switch_interp(ip); set_stack_limit(); /* The block, like a function body, must be a single expression. */ { const char *bad = body_escapes_expression(codeblock->source_text); if (bad) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("%s DO block must be a single expression", lang), errdetail("%s.", bad))); } /* Compile the block as a temporary niladic function, call, then clear. */ initStringInfo(&def); appendStringInfo(&def, "__pg_pure_do () = (%s);\n", codeblock->source_text); clear_lasterr(); res = pure_eval(def.data); if (res) pure_freenew(res); if (*lasterr()) { char *e = pstrdup(lasterr()); pfree(def.data); ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("%s: cannot compile DO block", lang), errdetail("%s", e))); } pfree(def.data); if ((rc = SPI_connect()) != SPI_OK_CONNECT) elog(ERROR, "SPI_connect failed: %s", SPI_result_code_string(rc)); spi_call_begin(); pending_pg_error = NULL; { pure_expr *f = pure_symbol(pure_sym("__pg_pure_do")); pure_expr *arg = pure_tuplel(0); res = pure_appxv(f, 1, &arg, &exc); } out = pure_evalcmd("clear __pg_pure_do\n"); free(out); if (!res) { spi_call_end(); SPI_finish(); report_pure_failure(lang, "uncaught exception in DO block", exc); } pure_freenew(res); spi_call_end(); SPI_finish(); PG_RETURN_VOID(); } Datum pg_pureu_inline_handler(PG_FUNCTION_ARGS) { return inline_block("pg_pureu", false, fcinfo); } Datum pg_pureu_validator(PG_FUNCTION_ARGS) { validate_function("pg_pureu", false, PG_GETARG_OID(0), fcinfo); PG_RETURN_VOID(); } void _PG_init(void) { if (IsBinaryUpgrade) return; DefineCustomStringVariable("pg_pure.using", "Pure modules every interpreter loads.", "A space- or comma-separated list passed to a " "Pure \"using\" declaration when the interpreter " "is created. The default, math, provides exact " "rationals.", &pg_pure_using, "math", PGC_SIGHUP, GUC_SUPERUSER_ONLY, NULL, NULL, NULL); MarkGUCPrefixReserved("pg_pure"); /* * When preloaded, build and warm both interpreters in the postmaster so * every backend inherits them through fork. The first warm call pays the * one-time LLVM codegen cost once, not per backend. DESIGN.md section 3. */ if (process_shared_preload_libraries_in_progress) { for (int t = 0; t < 2; t++) { pure_interp *ip = ensure_interp(t == 1); pure_expr *w; char *out; pure_switch_interp(ip); w = pure_eval("__pg_pure_warm x y = (x*y+1); __pg_pure_warm 6 7;"); if (w) pure_freenew(w); out = pure_evalcmd("clear __pg_pure_warm\n"); free(out); } } }