ProvSQL C/C++ API
Adding support for provenance and uncertainty management to PostgreSQL databases
Loading...
Searching...
No Matches
provsql_utils.c
Go to the documentation of this file.
1/**
2 * @file provsql_utils.c
3 * @brief OID lookup, constants cache, and utility functions for ProvSQL.
4 *
5 * Implements the functions declared in @c provsql_utils.h:
6 * - @c get_constants(): retrieves and caches per-database OIDs for all
7 * ProvSQL types, functions, and operators.
8 * - @c find_equality_operator(): looks up the @c = operator OID for a
9 * given pair of types.
10 *
11 * The constants cache is a sorted, dynamically-grown array of
12 * @c database_constants_t records (one per PostgreSQL database OID)
13 * stored in process-local memory and searched with binary search.
14 * The @c reset_constants_cache() SQL function forces a cache invalidation
15 * for the current database, which is needed after @c ALTER EXTENSION.
16 *
17 * Several helper functions (@c get_func_oid, @c get_provsql_func_oid,
18 * @c OperatorGet, @c get_enum_oid, @c binary_oper_exact) are adapted
19 * from PostgreSQL source code that is not exported as a public API.
20 */
21#include "postgres.h"
22#include "access/htup_details.h"
23#if PG_VERSION_NUM >= 120000
24#include "access/table.h" /* table_open / table_close */
25#else
26#include "access/heapam.h" /* heap_open / heap_close (PG <12) */
27#define table_open(r, l) heap_open((r), (l))
28#define table_close(r, l) heap_close((r), (l))
29#endif
30#include "access/genam.h"
31#include "miscadmin.h"
32#include "catalog/indexing.h" /* ConstraintRelidTypidNameIndexId */
33#include "catalog/namespace.h"
34#include "catalog/pg_attribute.h"
35#include "catalog/pg_constraint.h"
36#include "catalog/pg_index.h"
37#include "catalog/pg_type.h"
38#include "catalog/pg_enum.h"
39#include "catalog/pg_namespace.h"
40#include "catalog/pg_operator.h"
41#include "catalog/pg_type.h"
42#include "compatibility.h"
43#include "fmgr.h"
44#include "nodes/value.h"
45#include "parser/parse_func.h"
46#include "utils/fmgroids.h"
47#include "utils/syscache.h"
48#include "utils/lsyscache.h"
49#include "utils/inval.h"
50
51#include <string.h>
52
53#include "provsql_utils.h"
54
55const char *gate_type_name[] = {
56 "input",
57 "plus",
58 "times",
59 "monus",
60 "project",
61 "zero",
62 "one",
63 "eq",
64 "agg",
65 "semimod",
66 "cmp",
67 "delta",
68 "value",
69 "mulinput",
70 "update",
71 "rv",
72 "arith",
73 "mixture",
74 "assumed",
75 "annotation",
76 "conditioned",
77 "mobius",
78 "case",
79 "observe",
80 "fixvar",
81 "fixsystem",
82 "fixpoint",
83 "invalid"
84};
85
86/**
87 * @brief Look up an exactly matching binary operator OID.
88 *
89 * Copied and adapted from @c parse_oper.c (PostgreSQL internals, not
90 * exported). Returns @c InvalidOid if no exact match exists.
91 *
92 * @param opname Qualified operator name (a @c List of @c String nodes).
93 * @param arg1 OID of the left operand type.
94 * @param arg2 OID of the right operand type.
95 * @return OID of the matching operator, or @c InvalidOid.
96 */
97static Oid
98binary_oper_exact(List *opname, Oid arg1, Oid arg2)
99{
100 Oid result;
101 bool was_unknown = false;
102
103 /* Unspecified type for one of the arguments? then use the other */
104 if ((arg1 == UNKNOWNOID) && (arg2 != InvalidOid))
105 {
106 arg1 = arg2;
107 was_unknown = true;
108 }
109 else if ((arg2 == UNKNOWNOID) && (arg1 != InvalidOid))
110 {
111 arg2 = arg1;
112 was_unknown = true;
113 }
114
115 result = OpernameGetOprid(opname, arg1, arg2);
116 if (OidIsValid(result))
117 return result;
118
119 if (was_unknown)
120 {
121 /* arg1 and arg2 are the same here, need only look at arg1 */
122 Oid basetype = getBaseType(arg1);
123
124 if (basetype != arg1)
125 {
126 result = OpernameGetOprid(opname, basetype, basetype);
127 if (OidIsValid(result))
128 return result;
129 }
130 }
131
132 return InvalidOid;
133}
134
135/* Adapted from PostgreSQL code that is not exported (see parse_oper.c
136 * and the static function oper_select_candidate therein).
137 */
138Oid find_equality_operator(Oid ltypeId, Oid rtypeId)
139{
140 List * const equals=list_make1(makeString("="));
141
142 FuncCandidateList clist;
143 Oid inputOids[2] = {ltypeId,rtypeId};
144 int ncandidates;
145
146 Oid result = binary_oper_exact(equals, ltypeId, rtypeId);
147
148 if(result!=InvalidOid)
149 return result;
150
151 clist = OpernameGetCandidatesCompat(equals, 'b', false);
152
153 ncandidates = func_match_argtypes(2, inputOids,
154 clist, &clist);
155
156 if (ncandidates == 0)
157 return InvalidOid;
158 else if (ncandidates == 1)
159 return clist->oid;
160
161 clist = func_select_candidate(2, inputOids, clist);
162
163 if(clist)
164 return clist->oid;
165 else
166 return InvalidOid;
167}
168
169/**
170 * @brief Return the OID of a globally qualified function named @p s.
171 *
172 * Looks up the function in the default search path. Returns 0 if no
173 * matching function is found.
174 *
175 * @param s Function name (unqualified).
176 * @return OID of the function, or 0 if not found.
177 */
178static Oid get_func_oid(char *s)
179{
180 FuncCandidateList fcl=FuncnameGetCandidatesCompat(
181 list_make1(makeString(s)),
182 -1,
183 NIL,
184 false,
185 false,
186 false,
187 false);
188 if(fcl)
189 return fcl->oid;
190 else
191 return 0;
192}
193
194/**
195 * @brief Return the OID of a @c provsql-schema function named @p s.
196 *
197 * Looks up the function in the @c provsql schema. Returns 0 if not found.
198 *
199 * @param s Function name (without schema prefix).
200 * @return OID of the function, or 0 if not found.
201 */
202static Oid get_provsql_func_oid(char *s)
203{
204 FuncCandidateList fcl=FuncnameGetCandidatesCompat(
205 list_make2(makeString("provsql"),makeString(s)),
206 -1,
207 NIL,
208 false,
209 false,
210 false,
211 false);
212 if(fcl)
213 return fcl->oid;
214 else
215 return 0;
216}
217
218/**
219 * @brief Return the OID of a @c provsql-schema function named @p s with a
220 * specific argument-type signature.
221 *
222 * Unlike @c get_provsql_func_oid (which returns an arbitrary overload), this
223 * disambiguates overloaded functions by exact argument types. Needed for the
224 * @c probability / @c probability_evaluate families, which now carry both a
225 * @c uuid and a @c boolean first-argument overload. Returns 0 if not found.
226 */
227static Oid get_provsql_func_oid_args(char *s, int nargs, Oid *argtypes)
228{
229 return LookupFuncName(list_make2(makeString("provsql"), makeString(s)),
230 nargs, argtypes, true /* missing_ok */);
231}
232
233/**
234 * @brief Retrieve operator and function OIDs for a named operator.
235 *
236 * Copied and adapted from @c pg_operator.c (PostgreSQL internals, not
237 * exported). Looks up the operator by name, namespace, and operand types
238 * in the system cache.
239 *
240 * @param operatorName Operator symbol string (e.g. @c "<>").
241 * @param operatorNamespace OID of the schema containing the operator.
242 * @param leftObjectId OID of the left operand type.
243 * @param rightObjectId OID of the right operand type.
244 * @param operatorObjectId Output: OID of the operator, or 0 if not found.
245 * @param functionObjectId Output: OID of the underlying function, or 0.
246 */
247static void OperatorGet(
248 const char *operatorName,
249 Oid operatorNamespace,
250 Oid leftObjectId,
251 Oid rightObjectId,
252 Oid *operatorObjectId,
253 Oid *functionObjectId)
254{
255 HeapTuple tup;
256 bool defined;
257
258 tup = SearchSysCache4(OPERNAMENSP,
259 PointerGetDatum(operatorName),
260 ObjectIdGetDatum(leftObjectId),
261 ObjectIdGetDatum(rightObjectId),
262 ObjectIdGetDatum(operatorNamespace));
263 if (HeapTupleIsValid(tup))
264 {
265 Form_pg_operator oprform = (Form_pg_operator) GETSTRUCT(tup);
266#if PG_VERSION_NUM >= 120000
267 *operatorObjectId = oprform->oid;
268#else
269 *operatorObjectId = HeapTupleGetOid(tup);
270#endif
271 *functionObjectId = oprform->oprcode;
272 defined = RegProcedureIsValid(oprform->oprcode);
273 ReleaseSysCache(tup);
274 }
275 else
276 {
277 defined = false;
278 }
279
280 if(!defined) {
281 *operatorObjectId = 0;
282 *functionObjectId = 0;
283 }
284}
285
286/**
287 * @brief Return the OID of a specific enum label within an enum type.
288 *
289 * @param enumtypoid OID of the enum type (e.g. @c provenance_gate).
290 * @param label C-string label of the enum value to look up.
291 * @return OID of the enum label's @c pg_enum row, or
292 * @c InvalidOid if the label is not present.
293 */
294static Oid get_enum_oid(Oid enumtypoid, const char *label)
295{
296 HeapTuple tup;
297 Oid ret;
298
299 tup = SearchSysCache2(ENUMTYPOIDNAME,
300 ObjectIdGetDatum(enumtypoid),
301 CStringGetDatum(label));
302 if (!HeapTupleIsValid(tup))
303 return InvalidOid;
304
305#if PG_VERSION_NUM >= 120000
306 ret = ((Form_pg_enum) GETSTRUCT(tup))->oid;
307#else
308 ret = HeapTupleGetOid(tup);
309#endif
310
311 ReleaseSysCache(tup);
312
313 return ret;
314}
315
316/**
317 * @brief Query the system catalogs to populate a fresh @c constants_t.
318 *
319 * Performs all OID lookups required by ProvSQL in a single pass through
320 * the system caches. The @c CheckOid() macro aborts (or returns early,
321 * depending on @p failure_if_not_possible) if any OID resolves to
322 * @c InvalidOid.
323 *
324 * @param failure_if_not_possible If @c true, raise a @c provsql_error when
325 * any OID cannot be resolved. If @c false, return a @c constants_t
326 * with @c ok==false instead.
327 * @return Fully populated @c constants_t on success, or @c ok==false on
328 * failure when @p failure_if_not_possible is @c false.
329 */
330static constants_t initialize_constants(bool failure_if_not_possible)
331{
332 constants_t constants;
333 constants.ok = false;
334
335 /** @brief Abort or return early if OID field @p o of @p constants is invalid. */
336 #define CheckOid(o) if(constants.o==InvalidOid) { \
337 if(failure_if_not_possible) \
338 provsql_error("Could not initialize provsql constants"); \
339 else \
340 return constants; }
341
342 constants.OID_SCHEMA_PROVSQL = get_namespace_oid("provsql", true);
343 CheckOid(OID_SCHEMA_PROVSQL);
344
345 constants.OID_TYPE_UUID = TypenameGetTypid("uuid");
346 CheckOid(OID_TYPE_UUID);
347
348 constants.OID_TYPE_GATE_TYPE = GetSysCacheOid2(
349 TYPENAMENSP,
350#if PG_VERSION_NUM >= 120000
351 Anum_pg_type_oid,
352#endif
353 CStringGetDatum("provenance_gate"),
354 ObjectIdGetDatum(constants.OID_SCHEMA_PROVSQL)
355 );
356 CheckOid(OID_TYPE_GATE_TYPE);
357
358 constants.OID_TYPE_AGG_TOKEN = GetSysCacheOid2(
359 TYPENAMENSP,
360#if PG_VERSION_NUM >= 120000
361 Anum_pg_type_oid,
362#endif
363 CStringGetDatum("agg_token"),
364 ObjectIdGetDatum(constants.OID_SCHEMA_PROVSQL)
365 );
366 CheckOid(OID_TYPE_AGG_TOKEN);
367
368 constants.OID_TYPE_UUID = TypenameGetTypid("uuid");
369 CheckOid(OID_TYPE_UUID);
370
371 constants.OID_TYPE_UUID_ARRAY = TypenameGetTypid("_uuid");
372 CheckOid(OID_TYPE_UUID_ARRAY);
373
374 constants.OID_TYPE_INT = TypenameGetTypid("int4");
375 CheckOid(OID_TYPE_INT);
376
377 constants.OID_TYPE_BOOL = TypenameGetTypid("bool");
378 CheckOid(OID_TYPE_BOOL);
379
380 constants.OID_TYPE_FLOAT = TypenameGetTypid("float8");
381 CheckOid(OID_TYPE_FLOAT);
382
383 constants.OID_TYPE_INT_ARRAY = TypenameGetTypid("_int4");
384 CheckOid(OID_TYPE_INT_ARRAY);
385
386 constants.OID_TYPE_VARCHAR = TypenameGetTypid("varchar");
387 CheckOid(OID_TYPE_VARCHAR);
388
389#if PG_VERSION_NUM >= 140000
390 constants.OID_TYPE_TSTZMULTIRANGE = TypenameGetTypid("tstzmultirange");
391 CheckOid(OID_TYPE_TSTZMULTIRANGE);
392 constants.OID_TYPE_NUMMULTIRANGE = TypenameGetTypid("nummultirange");
393 CheckOid(OID_TYPE_NUMMULTIRANGE);
394 constants.OID_TYPE_INT4MULTIRANGE = TypenameGetTypid("int4multirange");
395 CheckOid(OID_TYPE_INT4MULTIRANGE);
396#else
397 constants.OID_TYPE_TSTZMULTIRANGE = InvalidOid;
398 constants.OID_TYPE_NUMMULTIRANGE = InvalidOid;
399 constants.OID_TYPE_INT4MULTIRANGE = InvalidOid;
400#endif
401
402 constants.OID_FUNCTION_ARRAY_AGG = get_func_oid("array_agg");
403 CheckOid(OID_FUNCTION_ARRAY_AGG);
404
405 constants.OID_FUNCTION_PROVENANCE_PLUS = get_provsql_func_oid("provenance_plus");
406 CheckOid(OID_FUNCTION_PROVENANCE_PLUS);
407
408 constants.OID_FUNCTION_PROVENANCE_TIMES = get_provsql_func_oid("provenance_times");
409 CheckOid(OID_FUNCTION_PROVENANCE_TIMES);
410
411 constants.OID_FUNCTION_PROVENANCE_MONUS = get_provsql_func_oid("provenance_monus");
412 CheckOid(OID_FUNCTION_PROVENANCE_MONUS);
413
414 constants.OID_FUNCTION_PROVENANCE_PROJECT = get_provsql_func_oid("provenance_project");
415 CheckOid(OID_FUNCTION_PROVENANCE_PROJECT);
416
417 constants.OID_FUNCTION_PROVENANCE_EQ = get_provsql_func_oid("provenance_eq");
418 CheckOid(OID_FUNCTION_PROVENANCE_EQ);
419
420 constants.OID_FUNCTION_PROVENANCE = get_provsql_func_oid("provenance");
421 CheckOid(OID_FUNCTION_PROVENANCE);
422
423 constants.OID_FUNCTION_PROVENANCE_DELTA = get_provsql_func_oid("provenance_delta");
424 CheckOid(OID_FUNCTION_PROVENANCE_DELTA);
425
426 constants.OID_FUNCTION_PROVENANCE_AGGREGATE = get_provsql_func_oid("provenance_aggregate");
427 CheckOid(OID_FUNCTION_PROVENANCE_AGGREGATE);
428
429 constants.OID_FUNCTION_PROVENANCE_SEMIMOD = get_provsql_func_oid("provenance_semimod");
430 CheckOid(OID_FUNCTION_PROVENANCE_SEMIMOD);
431 /* Optional: absent from schemas older than 1.13.0. */
433 get_provsql_func_oid("provenance_semimod_nullable");
434 /* Optional: absent from schemas older than 1.13.0. */
436 get_provsql_func_oid("row_number_as_rank");
437 /* Optional: absent from schemas older than 1.13.0. */
439 get_provsql_func_oid("order_determined");
440 constants.OID_FUNCTION_ORDER_CHECKED = get_provsql_func_oid("order_checked");
441 /* Optional: absent from schemas older than 1.13.0. */
443 get_provsql_func_oid("ntile_as_rank");
444 /* Optional: absent from schemas older than 1.13.0. */
446 get_provsql_func_oid("agg_token_null_event");
448 get_provsql_func_oid("agg_count_can_be_zero");
450 get_provsql_func_oid("window_distinct_tokens");
451 constants.OID_FUNCTION_PLAIN = get_provsql_func_oid("plain");
452 constants.OID_FUNCTION_PLAIN_TRUTH = get_provsql_func_oid("plain_truth");
454 get_provsql_func_oid("agg_token_plain_text");
456 get_provsql_func_oid("agg_token_frozen_value");
458 get_provsql_func_oid("agg_token_explode_children");
459 /* Optional: absent from schemas older than 1.13.0. */
461 get_provsql_func_oid("agg_possible_values");
463 get_provsql_func_oid("agg_guard_holds");
465 get_provsql_func_oid("provenance_semimod_flat");
467 get_provsql_func_oid("provenance_semimod_nested");
469 get_provsql_func_oid("provenance_contributions_cat");
470 constants.OID_FUNCTION_GATE_NULL = get_provsql_func_oid("gate_null");
471
472 constants.OID_FUNCTION_GATE_ZERO = get_provsql_func_oid("gate_zero");
473 CheckOid(OID_FUNCTION_GATE_ZERO);
474
475 constants.OID_FUNCTION_GATE_ONE = get_provsql_func_oid("gate_one");
476 CheckOid(OID_FUNCTION_GATE_ONE);
477
478 constants.OID_FUNCTION_PROVENANCE_CMP = get_provsql_func_oid("provenance_cmp");
479 CheckOid(OID_FUNCTION_PROVENANCE_CMP);
480
481 constants.OID_FUNCTION_AGG_TOKEN_UUID = get_provsql_func_oid("agg_token_uuid");
482 CheckOid(OID_FUNCTION_AGG_TOKEN_UUID);
483
484 /* Used by the aggregate-carrier CASE lowering (build_agg_case) to lift a
485 * numeric constant branch (e.g. `ELSE 0`) into a value gate. */
486 constants.OID_FUNCTION_AGG_VALUE_GATE = get_provsql_func_oid("agg_value_gate");
487
488 /* The next two are used by the agg_token JOIN query rewriting. */
489 constants.OID_FUNCTION_GET_CHILDREN = get_provsql_func_oid("get_children");
490 CheckOid(OID_FUNCTION_GET_CHILDREN);
491
492 constants.OID_FUNCTION_GET_EXTRA = get_provsql_func_oid("get_extra");
493 CheckOid(OID_FUNCTION_GET_EXTRA);
494
495 /* Pick the unnest(anyarray) overload explicitly; PG 14+ also has
496 * unnest(anymultirange), which get_func_oid would pick up first on
497 * some versions. */
498 {
499 Oid argtypes[1] = { ANYARRAYOID };
500 constants.OID_UNNEST = LookupFuncName(list_make1(makeString("unnest")),
501 1, argtypes, true);
502 }
503 CheckOid(OID_UNNEST);
504
505 /* random_variable type and its operator procedures will ship in
506 * 1.5.0. Older schemas (notably the 1.0.0 baseline used by
507 * extension_upgrade) do not have them. Treat each lookup as
508 * optional -- if the catalog lacks the symbol, the OID stays
509 * InvalidOid and downstream code (rv_cmp_index, the planner-hook
510 * walker) silently no-ops on such schemas because real OpExpr
511 * funcoids never equal InvalidOid. Mirrors the
512 * GET_GATE_TYPE_OID_OPTIONAL pattern above. */
513 constants.OID_TYPE_RANDOM_VARIABLE = GetSysCacheOid2(
514 TYPENAMENSP,
515#if PG_VERSION_NUM >= 120000
516 Anum_pg_type_oid,
517#endif
518 CStringGetDatum("random_variable"),
519 ObjectIdGetDatum(constants.OID_SCHEMA_PROVSQL)
520 );
522 OidIsValid(constants.OID_TYPE_RANDOM_VARIABLE)
523 ? get_array_type(constants.OID_TYPE_RANDOM_VARIABLE)
524 : InvalidOid;
525
526 /* provsql.greatest / provsql.least (VARIADIC random_variable[]): the
527 * order-statistic constructors the planner lifts a builtin GREATEST / LEAST
528 * over random_variable arguments into. Optional (InvalidOid on older
529 * schemas disables the lift; the qualified provsql.greatest(...) still
530 * works). */
531 constants.OID_FUNCTION_RV_GREATEST = get_provsql_func_oid("greatest");
532 constants.OID_FUNCTION_RV_LEAST = get_provsql_func_oid("least");
533
534 /* rv_aggregate_semimod helper used by the RV-returning aggregate
535 * rewrite (sum, avg, and any future aggregate whose result type is
536 * random_variable). The planner-hook routes on aggtype instead of a
537 * per-aggregate OID, so no individual aggregate OID needs to be
538 * cached here; an InvalidOid for this helper just leaves the rewrite
539 * disabled on older schemas that lack the continuous-distribution
540 * surface (1.0.0 baseline used by extension_upgrade). */
541 /* Disambiguate by signature: rv_aggregate_semimod is now overloaded
542 * (2-arg identity-0 wrap and 3-arg identity-parameterised wrap), so a
543 * bare-name lookup could return either. Pin the 2-arg overload used for
544 * sum and the avg numerator. */
545 {
546 Oid semimod2[2] = { constants.OID_TYPE_UUID,
547 constants.OID_TYPE_RANDOM_VARIABLE };
549 get_provsql_func_oid_args("rv_aggregate_semimod", 2, semimod2);
550 }
551
552 /* Per-aggregate identity dispatch for the RV-aggregate rewrite: the
553 * 3-arg identity-parameterised wrap (product / max / min bake their
554 * identity element into the mixture), the avg denominator indicator, the
555 * RV division for avg's sum/sum rewrite, and the five RV-returning
556 * aggregate OIDs the rewrite keys on. The `constants' struct is not
557 * zero-initialised, so every field is set unconditionally; the arg-typed
558 * lookups reference the random_variable type and are skipped (left
559 * InvalidOid) on a schema predating the continuous-distribution surface,
560 * which disables only the identity/avg refinements. */
561 constants.OID_FUNCTION_RV_AGGREGATE_SEMIMOD_ID = InvalidOid;
562 constants.OID_FUNCTION_RV_AGGREGATE_INDICATOR = InvalidOid;
563 constants.OID_FUNCTION_RV_AGGREGATE_INDICATOR_VALUED = InvalidOid;
564 constants.OID_FUNCTION_RV_DIV = InvalidOid;
565 constants.OID_AGG_SUM_RV = InvalidOid;
566 constants.OID_AGG_PRODUCT_RV = InvalidOid;
567 constants.OID_AGG_AVG_RV = InvalidOid;
568 constants.OID_AGG_MAX_RV = InvalidOid;
569 constants.OID_AGG_MIN_RV = InvalidOid;
570 constants.OID_AGG_RV_SUM_OR_NULL = InvalidOid;
571 constants.OID_AGG_COVAR_POP_RV = InvalidOid;
572 constants.OID_AGG_COVAR_SAMP_RV = InvalidOid;
573 constants.OID_AGG_CORR_RV = InvalidOid;
574 constants.OID_AGG_STDDEV_POP_RV = InvalidOid;
575 constants.OID_AGG_STDDEV_SAMP_RV = InvalidOid;
576 constants.OID_AGG_PERCENTILE_CONT_RV = InvalidOid;
577 constants.OID_AGG_RV_COVAR_POP_IMPL = InvalidOid;
578 constants.OID_AGG_RV_COVAR_SAMP_IMPL = InvalidOid;
579 constants.OID_AGG_RV_CORR_IMPL = InvalidOid;
580 constants.OID_AGG_RV_STDDEV_POP_IMPL = InvalidOid;
581 constants.OID_AGG_RV_STDDEV_SAMP_IMPL = InvalidOid;
582 constants.OID_AGG_RV_PERCENTILE_IMPL = InvalidOid;
583 if (OidIsValid(constants.OID_TYPE_RANDOM_VARIABLE)) {
584 Oid rvarg[1] = { constants.OID_TYPE_RANDOM_VARIABLE };
585 Oid rvarg2[2] = { constants.OID_TYPE_RANDOM_VARIABLE,
586 constants.OID_TYPE_RANDOM_VARIABLE };
587 Oid rvarg3[3] = { constants.OID_TYPE_RANDOM_VARIABLE,
588 constants.OID_TYPE_RANDOM_VARIABLE,
589 constants.OID_TYPE_RANDOM_VARIABLE };
590 Oid pctarg[2] = { FLOAT8OID, constants.OID_TYPE_RANDOM_VARIABLE };
591 Oid pctimplarg[3] = { FLOAT8OID, constants.OID_TYPE_RANDOM_VARIABLE,
592 constants.OID_TYPE_RANDOM_VARIABLE };
593 Oid semimod3[3] = { constants.OID_TYPE_UUID,
594 constants.OID_TYPE_RANDOM_VARIABLE, FLOAT8OID };
596 get_provsql_func_oid_args("rv_aggregate_semimod", 3, semimod3);
597 {
598 /* rv_aggregate_indicator is overloaded: resolve each signature
599 * explicitly (the by-name lookup returns an arbitrary overload). */
600 Oid indarg1[1] = { constants.OID_TYPE_UUID };
601 Oid indarg2[2] = { constants.OID_TYPE_UUID,
602 constants.OID_TYPE_RANDOM_VARIABLE };
604 get_provsql_func_oid_args("rv_aggregate_indicator", 1, indarg1);
606 get_provsql_func_oid_args("rv_aggregate_indicator", 2, indarg2);
607 }
608 constants.OID_FUNCTION_RV_DIV =
609 get_provsql_func_oid("random_variable_div");
610 constants.OID_AGG_SUM_RV = get_provsql_func_oid_args("sum", 1, rvarg);
611 constants.OID_AGG_PRODUCT_RV = get_provsql_func_oid_args("product", 1, rvarg);
612 constants.OID_AGG_AVG_RV = get_provsql_func_oid_args("avg", 1, rvarg);
613 constants.OID_AGG_MAX_RV = get_provsql_func_oid_args("max", 1, rvarg);
614 constants.OID_AGG_MIN_RV = get_provsql_func_oid_args("min", 1, rvarg);
615 constants.OID_AGG_RV_SUM_OR_NULL =
616 get_provsql_func_oid_args("rv_sum_or_null", 1, rvarg);
617 /* SQL-standard statistic aggregates over RV rows (public forms) and
618 * the indicator-carrying _impl rewrite targets. Optional lookups:
619 * absent on schemas predating them, which leaves the public forms
620 * unrecognised so they run their own certain-row fold. */
621 constants.OID_AGG_COVAR_POP_RV =
622 get_provsql_func_oid_args("covar_pop", 2, rvarg2);
623 constants.OID_AGG_COVAR_SAMP_RV =
624 get_provsql_func_oid_args("covar_samp", 2, rvarg2);
625 constants.OID_AGG_CORR_RV =
626 get_provsql_func_oid_args("corr", 2, rvarg2);
627 constants.OID_AGG_STDDEV_POP_RV =
628 get_provsql_func_oid_args("stddev_pop", 1, rvarg);
629 constants.OID_AGG_STDDEV_SAMP_RV =
630 get_provsql_func_oid_args("stddev_samp", 1, rvarg);
632 get_provsql_func_oid_args("percentile_cont", 2, pctarg);
633 constants.OID_AGG_RV_COVAR_POP_IMPL =
634 get_provsql_func_oid_args("rv_covar_pop_impl", 3, rvarg3);
636 get_provsql_func_oid_args("rv_covar_samp_impl", 3, rvarg3);
637 constants.OID_AGG_RV_CORR_IMPL =
638 get_provsql_func_oid_args("rv_corr_impl", 3, rvarg3);
640 get_provsql_func_oid_args("rv_stddev_pop_impl", 2, rvarg2);
642 get_provsql_func_oid_args("rv_stddev_samp_impl", 2, rvarg2);
644 get_provsql_func_oid_args("rv_percentile_impl", 3, pctimplarg);
645 }
646
647 /* choose(anyelement): keeps the first non-NULL value of a group. Used by
648 * the scalar-subquery decorrelation to pick the single matched value.
649 * Optional lookup (0 on schemas predating it). */
650 constants.OID_FUNCTION_CHOOSE = get_provsql_func_oid("choose");
651
652 /* array_collect(anynonarray): array_agg, but {} over no rows. Optional
653 * lookup (0 on schemas predating it, where array_agg is used instead). */
654 constants.OID_FUNCTION_ARRAY_COLLECT = get_provsql_func_oid("array_collect");
655
656 /* assume_boolean is installed by the 1.6.0 upgrade script. Treat
657 * its absence as a soft signal: on older schemas the safe-query
658 * rewriter (gated behind the 'boolean' provenance class) refuses to
659 * fire because it cannot mark the per-row root with a
660 * gate_assumed for downstream semiring-compatibility
661 * enforcement. Optional lookup matches the pattern used above for
662 * rv_aggregate_semimod. */
664 get_provsql_func_oid("assume_boolean");
665
666 /* annotate(uuid,text) -- transparent annotation wrapper carrying the
667 * inversion-free certificate / order keys. Optional like the helpers
668 * above: InvalidOid on an older schema simply disables the carrier. */
669 constants.OID_FUNCTION_ANNOTATE =
670 get_provsql_func_oid("annotate");
671
672 /* inversion_free_key(text,text,int) -- builds the per-input order-key string
673 * for the inversion-free path. Optional: InvalidOid on an older schema
674 * disables per-input markers (the path then declines and falls back). */
676 get_provsql_func_oid("inversion_free_key");
677
678 /* cond(uuid,uuid) / given(uuid) -- the conditioning operator and its
679 * whole-tuple output marker. Optional: InvalidOid on a schema predating
680 * the conditioning feature disables the given() rewrite. */
681 /* Optional: absent from extension versions predating the structural
682 * supersede, whose constants must still initialise. */
684 get_provsql_func_oid("provenance_cmp_times");
685 constants.OID_FUNCTION_COND = get_provsql_func_oid("cond");
686 /* given is overloaded: given(uuid) is the evidence carrier / whole-tuple
687 * output marker; given(boolean) is the predicate placeholder the planner
688 * rewrites (both the function form and the prefix "| (predicate)"). */
689 {
690 Oid uuid_arg[1] = { constants.OID_TYPE_UUID };
691 constants.OID_FUNCTION_GIVEN = get_provsql_func_oid_args("given", 1, uuid_arg);
692 }
693
694 /* random_variable_cond(random_variable,uuid) and its Boolean-predicate
695 * placeholder random_variable_cond_predicate(random_variable,boolean): the
696 * planner rewrites "X | (predicate)" into the former over the gate built
697 * from the latter's Boolean operand. Optional (older schemas). */
698 constants.OID_FUNCTION_RV_COND =
699 get_provsql_func_oid("random_variable_cond");
700 constants.OID_FUNCTION_AGG_COND =
701 get_provsql_func_oid("agg_token_cond");
702 /* The "X | (predicate)" placeholders, one per carrier (and the prefix
703 * whole-tuple form). The planner rewrites each into the matching
704 * conditioning constructor over the gate built from the Boolean operand. */
706 get_provsql_func_oid("cond_predicate");
708 get_provsql_func_oid("random_variable_cond_predicate");
710 get_provsql_func_oid("agg_token_cond_predicate");
712 get_provsql_func_oid("predicate_cond_predicate");
713 {
714 Oid bool_arg[1] = { constants.OID_TYPE_BOOL };
716 get_provsql_func_oid_args("given", 1, bool_arg);
717 }
719 get_provsql_func_oid("regular_indicator");
720
721 /* probability(<predicate>) surface: the real probability_evaluate(uuid,
722 * text, text) is the rewrite target; probability(boolean, text, text) is
723 * the placeholder the planner lifts. Disambiguated by argument type since
724 * each name is overloaded. Optional (InvalidOid on schemas predating the
725 * boolean overload). */
726 {
727 Oid uuid_sig[3] = { constants.OID_TYPE_UUID, TEXTOID, TEXTOID };
728 Oid bool_sig[3] = { BOOLOID, TEXTOID, TEXTOID };
730 get_provsql_func_oid_args("probability_evaluate", 3, uuid_sig);
732 get_provsql_func_oid_args("probability", 3, bool_sig);
733 }
734
735 /* rv_case(uuid[]) -> random_variable: builds a gate_case from the planner's
736 * flattened guard/value wire list. Optional (InvalidOid disables the
737 * CASE-over-RV rewrite on schemas predating gate_case). */
738 constants.OID_FUNCTION_RV_CASE = get_provsql_func_oid("rv_case");
739
740 /* agg_case(uuid[]) -> agg_token: the aggregate-carrier analogue of rv_case.
741 * Optional (InvalidOid disables the CASE-over-aggregate rewrite). */
742 constants.OID_FUNCTION_AGG_CASE = get_provsql_func_oid("agg_case");
743
744 /* random_variable_{eq,ne,le,lt,ge,gt} -- order matches the
745 * ComparisonOperator enum in src/Aggregation.h (EQ=0, NE=1, LE=2,
746 * LT=3, GE=4, GT=5). */
747 constants.OID_FUNCTION_RV_CMP[0] = get_provsql_func_oid("random_variable_eq");
748 constants.OID_FUNCTION_RV_CMP[1] = get_provsql_func_oid("random_variable_ne");
749 constants.OID_FUNCTION_RV_CMP[2] = get_provsql_func_oid("random_variable_le");
750 constants.OID_FUNCTION_RV_CMP[3] = get_provsql_func_oid("random_variable_lt");
751 constants.OID_FUNCTION_RV_CMP[4] = get_provsql_func_oid("random_variable_ge");
752 constants.OID_FUNCTION_RV_CMP[5] = get_provsql_func_oid("random_variable_gt");
753
754 OperatorGet("<>", PG_CATALOG_NAMESPACE, constants.OID_TYPE_UUID, constants.OID_TYPE_UUID, &constants.OID_OPERATOR_NOT_EQUAL_UUID, &constants.OID_FUNCTION_NOT_EQUAL_UUID);
755 CheckOid(OID_OPERATOR_NOT_EQUAL_UUID);
756 CheckOid(OID_FUNCTION_NOT_EQUAL_UUID);
757
758 /** @brief Look up the OID of provenance_gate enum value @p x and store it in constants. */
759 #define GET_GATE_TYPE_OID(x) { \
760 constants.GATE_TYPE_TO_OID[gate_ ## x] = get_enum_oid( \
761 constants.OID_TYPE_GATE_TYPE, \
762 #x); \
763 if(constants.GATE_TYPE_TO_OID[gate_ ## x]==InvalidOid) \
764 provsql_error("Could not initialize provsql gate type " #x); }
765
766 /** @brief Like @c GET_GATE_TYPE_OID but tolerates a missing enum value.
767 *
768 * Used for gate types added in releases newer than the oldest schema
769 * the @c extension_upgrade test exercises (currently 1.0.0). An
770 * intermediate state where a 1.0.0 database has been bound to a newer
771 * shared library is possible (e.g. between @c CREATE @c EXTENSION
772 * @c VERSION and @c ALTER @c EXTENSION @c UPDATE) and must not abort
773 * @c get_constants -- the missing OID stays @c InvalidOid and any
774 * attempt to actually create such a gate fails later in
775 * @c create_gate's "Invalid gate type" branch. When the upgrade
776 * scripts catch up, the lookup succeeds and the gate becomes usable
777 * normally. No state for @c InvalidOid is stored, so the field
778 * keeps its zero-init value (which is @c InvalidOid).
779 */
780 #define GET_GATE_TYPE_OID_OPTIONAL(x) { \
781 constants.GATE_TYPE_TO_OID[gate_ ## x] = get_enum_oid( \
782 constants.OID_TYPE_GATE_TYPE, \
783 #x); }
784
785 GET_GATE_TYPE_OID(input);
786 GET_GATE_TYPE_OID(plus);
787 GET_GATE_TYPE_OID(times);
788 GET_GATE_TYPE_OID(monus);
789 GET_GATE_TYPE_OID(project);
790 GET_GATE_TYPE_OID(zero);
794 GET_GATE_TYPE_OID(semimod);
796 GET_GATE_TYPE_OID(delta);
797 GET_GATE_TYPE_OID(value);
798 GET_GATE_TYPE_OID(mulinput);
799 GET_GATE_TYPE_OID(update);
804 /* The 'assumed' label was 'assumed_boolean' before 1.10.0; ALTER TYPE
805 * ... RENAME VALUE keeps the enum value's OID, so accepting the
806 * former label is equivalent -- and necessary when this cache is
807 * built in a session that later runs the upgrade chain across the
808 * rename (the extension-upgrade test does exactly that). */
809 if(constants.GATE_TYPE_TO_OID[gate_assumed] == InvalidOid)
810 constants.GATE_TYPE_TO_OID[gate_assumed] =
811 get_enum_oid(constants.OID_TYPE_GATE_TYPE, "assumed_boolean");
812 GET_GATE_TYPE_OID_OPTIONAL(annotation);
813 GET_GATE_TYPE_OID_OPTIONAL(conditioned);
820
821 constants.ok=true;
822
823 return constants;
824}
825
826static database_constants_t *constants_cache; ///< Per-database OID constants cache (sorted by database OID)
827static unsigned constants_cache_len=0; ///< Number of valid entries in @c constants_cache
828
829constants_t get_constants(bool failure_if_not_possible)
830{
831 int start=0, end=constants_cache_len-1;
832 database_constants_t *constants_cache2;
833 constants_t constants;
834
835 while(end>=start) {
836 unsigned mid=(start+end)/2;
837 if(constants_cache[mid].database<MyDatabaseId)
838 start=mid+1;
839 else if(constants_cache[mid].database>MyDatabaseId)
840 end=mid-1;
841 else
842 return constants_cache[mid].constants;
843 }
844
845 constants=initialize_constants(failure_if_not_possible);
846
847 /* Only memoize successful lookups. A failed lookup (ok==false) means
848 * the provsql extension was not fully visible to this backend at this
849 * point -- e.g. the connection's first planned query ran before
850 * CREATE EXTENSION, or during a DROP/CREATE/ALTER EXTENSION ... UPDATE
851 * window. Caching that failure would permanently disable provenance
852 * tracking on the backend: a long-lived pooled connection would never
853 * recover, silently dropping the provsql column on every query until
854 * reset_constants_cache() is called by hand. Returning without
855 * caching lets the next call retry until the extension is available. */
856 if(!constants.ok)
857 return constants;
858
859 constants_cache2=calloc(constants_cache_len+1, sizeof(database_constants_t));
860 for(unsigned i=0; i<start; ++i)
861 constants_cache2[i]=constants_cache[i];
862
863 constants_cache2[start].database=MyDatabaseId;
864 constants_cache2[start].constants=constants;
865
866 for(unsigned i=start; i<constants_cache_len; ++i)
867 constants_cache2[i+1]=constants_cache[i];
868 free(constants_cache);
869 constants_cache=constants_cache2;
871
872 return constants_cache[start].constants;
873}
874
875/* -------------------------------------------------------------------------
876 * Per-backend table-info cache
877 *
878 * Sorted array of @c table_info_cache_entry, binary-searched on @c relid.
879 * Used by @c provsql_lookup_table_info to amortise IPC across repeated
880 * lookups during query planning. Entries are invalidated by
881 * @c invalidate_table_info_cache_callback, which is hooked into
882 * PostgreSQL's relcache invalidation channel and so reacts to local
883 * DDL, cross-backend invalidations broadcast via
884 * @c CacheInvalidateRelcacheByRelid, and explicit "invalidate all"
885 * (relid == InvalidOid) events.
886 * ------------------------------------------------------------------------- */
887
889 Oid relid; ///< pg_class OID (sort key)
890 bool valid; ///< false => refresh on next access
891 bool present; ///< when valid: was a record found at the worker?
892 uint8 kind; ///< when present: provsql_table_kind value
893 uint16 block_key_n; ///< when present: number of block-key columns
894 AttrNumber block_key[PROVSQL_TABLE_INFO_MAX_BLOCK_KEY]; ///< when present: block-key column numbers
896
897static table_info_cache_entry *table_info_cache = NULL; ///< Sorted by @c relid
898static unsigned table_info_cache_len = 0;
900
901/** Find @p relid in the cache. Returns the index on hit; otherwise
902 * @c -1 and writes the insertion point to @p *insert_at. */
903static int table_info_cache_find(Oid relid, int *insert_at)
904{
905 int start = 0, end = (int)table_info_cache_len - 1;
906 while(end >= start) {
907 int mid = (start + end) / 2;
908 if(table_info_cache[mid].relid < relid)
909 start = mid + 1;
910 else if(table_info_cache[mid].relid > relid)
911 end = mid - 1;
912 else
913 return mid;
914 }
915 if(insert_at) *insert_at = start;
916 return -1;
917}
918
919/** Insert a fresh entry at @p pos (which must be the value returned by
920 * the most recent @c table_info_cache_find that reported a miss). */
921static void table_info_cache_insert(int pos, Oid relid, bool present,
922 const ProvenanceTableInfo *info)
923{
924 table_info_cache_entry *new_buf = calloc(table_info_cache_len + 1,
925 sizeof(table_info_cache_entry));
926 for(int i = 0; i < pos; ++i)
927 new_buf[i] = table_info_cache[i];
928 new_buf[pos].relid = relid;
929 new_buf[pos].valid = true;
930 new_buf[pos].present = present;
931 if(present) {
932 new_buf[pos].kind = info->kind;
933 new_buf[pos].block_key_n = info->block_key_n;
934 memcpy(new_buf[pos].block_key, info->block_key,
935 info->block_key_n * sizeof(AttrNumber));
936 }
937 for(unsigned i = (unsigned)pos; i < table_info_cache_len; ++i)
938 new_buf[i + 1] = table_info_cache[i];
939 free(table_info_cache);
940 table_info_cache = new_buf;
942}
943
944/** Relcache callback: PostgreSQL fires this whenever a relation's
945 * relcache entry is invalidated (locally or via shared invalidation
946 * from another backend). @p relid == @c InvalidOid means
947 * "invalidate everything." */
948static void invalidate_table_info_cache_callback(Datum arg, Oid relid)
949{
950 int pos;
951 (void) arg;
952 if(relid == InvalidOid) {
953 for(unsigned i = 0; i < table_info_cache_len; ++i)
954 table_info_cache[i].valid = false;
955 return;
956 }
957 pos = table_info_cache_find(relid, NULL);
958 if(pos >= 0)
959 table_info_cache[pos].valid = false;
960}
961
963{
964 int insert_at = 0;
965 int pos;
967 bool present;
968
970 CacheRegisterRelcacheCallback(invalidate_table_info_cache_callback,
971 (Datum) 0);
973 }
974
975 pos = table_info_cache_find(relid, &insert_at);
976
977 if(pos >= 0 && table_info_cache[pos].valid) {
979 if(!e->present)
980 return false;
981 out->relid = relid;
982 out->kind = e->kind;
983 out->block_key_n = e->block_key_n;
984 memcpy(out->block_key, e->block_key,
985 e->block_key_n * sizeof(AttrNumber));
986 return true;
987 }
988
989 present = provsql_fetch_table_info(relid, &info);
990
991 if(pos >= 0) {
992 /* Refresh an existing, now-stale slot in place. */
994 e->valid = true;
995 e->present = present;
996 if(present) {
997 e->kind = info.kind;
998 e->block_key_n = info.block_key_n;
999 memcpy(e->block_key, info.block_key,
1000 info.block_key_n * sizeof(AttrNumber));
1001 }
1002 } else {
1003 table_info_cache_insert(insert_at, relid, present, &info);
1004 }
1005
1006 if(present) {
1007 *out = info;
1008 return true;
1009 }
1010 return false;
1011}
1012
1013/* -------------------------------------------------------------------------
1014 * Per-backend ancestry cache
1015 *
1016 * Structurally identical to the table-info cache above but keyed on
1017 * just the ancestor half of the on-disk record. The two halves share
1018 * the storage (one @c ProvenanceTableInfo per relation) but are
1019 * cached separately so a hot-path safe-query lookup that only needs
1020 * the kind doesn't pull the ancestor array, and vice versa. The
1021 * relcache callback below reuses the channel of the kind cache so
1022 * any @c set_ancestors / @c add_provenance / @c repair_key DDL
1023 * broadcast invalidates both caches in lock-step.
1024 * ------------------------------------------------------------------------- */
1025
1026typedef struct ancestry_cache_entry {
1027 Oid relid; ///< pg_class OID (sort key)
1028 bool valid; ///< false => refresh on next access
1029 bool present; ///< when valid: did the worker return any ancestors?
1030 uint16 ancestor_n; ///< when present: count
1031 Oid ancestors[PROVSQL_TABLE_INFO_MAX_ANCESTORS]; ///< when present: ancestor OIDs
1033
1035static unsigned ancestry_cache_len = 0;
1037
1038static int ancestry_cache_find(Oid relid, int *insert_at)
1039{
1040 int start = 0, end = (int)ancestry_cache_len - 1;
1041 while(end >= start) {
1042 int mid = (start + end) / 2;
1043 if(ancestry_cache[mid].relid < relid)
1044 start = mid + 1;
1045 else if(ancestry_cache[mid].relid > relid)
1046 end = mid - 1;
1047 else
1048 return mid;
1049 }
1050 if(insert_at) *insert_at = start;
1051 return -1;
1052}
1053
1054static void ancestry_cache_insert(int pos, Oid relid, bool present,
1055 uint16 ancestor_n, const Oid *ancestors)
1056{
1057 ancestry_cache_entry *new_buf = calloc(ancestry_cache_len + 1,
1058 sizeof(ancestry_cache_entry));
1059 for(int i = 0; i < pos; ++i)
1060 new_buf[i] = ancestry_cache[i];
1061 new_buf[pos].relid = relid;
1062 new_buf[pos].valid = true;
1063 new_buf[pos].present = present;
1064 if(present) {
1065 new_buf[pos].ancestor_n = ancestor_n;
1066 memcpy(new_buf[pos].ancestors, ancestors,
1067 ancestor_n * sizeof(Oid));
1068 }
1069 for(unsigned i = (unsigned)pos; i < ancestry_cache_len; ++i)
1070 new_buf[i + 1] = ancestry_cache[i];
1071 free(ancestry_cache);
1072 ancestry_cache = new_buf;
1074}
1075
1076static void invalidate_ancestry_cache_callback(Datum arg, Oid relid)
1077{
1078 int pos;
1079 (void) arg;
1080 if(relid == InvalidOid) {
1081 for(unsigned i = 0; i < ancestry_cache_len; ++i)
1082 ancestry_cache[i].valid = false;
1083 return;
1084 }
1085 pos = ancestry_cache_find(relid, NULL);
1086 if(pos >= 0)
1087 ancestry_cache[pos].valid = false;
1088}
1089
1090bool provsql_lookup_ancestry(Oid relid, uint16 *ancestor_n_out,
1091 Oid *ancestors_out)
1092{
1093 int insert_at = 0;
1094 int pos;
1095 uint16 n = 0;
1096 Oid ancestors[PROVSQL_TABLE_INFO_MAX_ANCESTORS];
1097 bool present;
1098
1100 CacheRegisterRelcacheCallback(invalidate_ancestry_cache_callback,
1101 (Datum) 0);
1103 }
1104
1105 pos = ancestry_cache_find(relid, &insert_at);
1106
1107 if(pos >= 0 && ancestry_cache[pos].valid) {
1109 if(!e->present)
1110 return false;
1111 *ancestor_n_out = e->ancestor_n;
1112 memcpy(ancestors_out, e->ancestors,
1113 e->ancestor_n * sizeof(Oid));
1114 return true;
1115 }
1116
1117 present = provsql_fetch_ancestry(relid, &n, ancestors);
1118
1119 if(pos >= 0) {
1121 e->valid = true;
1122 e->present = present;
1123 if(present) {
1124 e->ancestor_n = n;
1125 memcpy(e->ancestors, ancestors, n * sizeof(Oid));
1126 }
1127 } else {
1128 ancestry_cache_insert(insert_at, relid, present, n, ancestors);
1129 }
1130
1131 if(present) {
1132 *ancestor_n_out = n;
1133 memcpy(ancestors_out, ancestors, n * sizeof(Oid));
1134 return true;
1135 }
1136 return false;
1137}
1138
1139/* -------------------------------------------------------------------------
1140 * Per-backend relation-keys cache (§2 PK-FD support)
1141 *
1142 * Sibling of the @c table_info_cache above; structurally identical
1143 * (sorted-by-relid array, binary search, relcache-invalidated) but
1144 * keyed on @c pg_class OIDs of @em arbitrary relations -- not just
1145 * provenance-tracked ones -- because the §2 / §3 / §5 detector
1146 * passes also need to reason about PRIMARY KEY constraints on
1147 * deterministic dimension tables and self-joined relations.
1148 *
1149 * Each cached entry holds up to @c PROVSQL_KEY_CACHE_MAX_KEYS keys
1150 * (PRIMARY KEY plus NOT-NULL UNIQUE constraints from
1151 * @c pg_constraint, filtered by @c contype @c IN @c ('p','u')).
1152 * The relcache callback uses a separate static flag from the
1153 * table-info cache's, so a DROP CONSTRAINT / DROP TABLE invalidates
1154 * both caches independently.
1155 * ------------------------------------------------------------------------- */
1156
1164
1166static unsigned key_cache_len = 0;
1168
1169static int key_cache_find(Oid relid, int *insert_at)
1170{
1171 int start = 0, end = (int) key_cache_len - 1;
1172 while(end >= start) {
1173 int mid = (start + end) / 2;
1174 if(key_cache[mid].relid < relid)
1175 start = mid + 1;
1176 else if(key_cache[mid].relid > relid)
1177 end = mid - 1;
1178 else
1179 return mid;
1180 }
1181 if(insert_at) *insert_at = start;
1182 return -1;
1183}
1184
1185static void key_cache_insert(int pos, Oid relid,
1186 const ProvenanceRelationKeys *keys)
1187{
1188 key_cache_entry *new_buf = calloc(key_cache_len + 1,
1189 sizeof(key_cache_entry));
1190 for(int i = 0; i < pos; ++i)
1191 new_buf[i] = key_cache[i];
1192 new_buf[pos].relid = relid;
1193 new_buf[pos].valid = true;
1194 new_buf[pos].has_keys = keys->key_n > 0;
1195 new_buf[pos].key_n = keys->key_n;
1196 if(keys->key_n > 0)
1197 memcpy(new_buf[pos].keys, keys->keys,
1198 keys->key_n * sizeof(ProvenanceRelationKey));
1199 for(unsigned i = (unsigned)pos; i < key_cache_len; ++i)
1200 new_buf[i + 1] = key_cache[i];
1201 free(key_cache);
1202 key_cache = new_buf;
1203 ++key_cache_len;
1204}
1205
1206static void invalidate_key_cache_callback(Datum arg, Oid relid)
1207{
1208 int pos;
1209 (void) arg;
1210 if(relid == InvalidOid) {
1211 for(unsigned i = 0; i < key_cache_len; ++i)
1212 key_cache[i].valid = false;
1213 return;
1214 }
1215 pos = key_cache_find(relid, NULL);
1216 if(pos >= 0)
1217 key_cache[pos].valid = false;
1218}
1219
1220/**
1221 * @brief Read the PRIMARY-KEY and NOT-NULL-UNIQUE keys of @p relid
1222 * from the system catalogs.
1223 *
1224 * Scans @c pg_constraint for entries with @c conrelid @c = @p relid
1225 * and @c contype @c IN @c ('p','u'), then resolves each constraint's
1226 * column list via @c pg_index.indkey (the constraint's index is
1227 * recorded in @c pg_constraint.conindid). For UNIQUE constraints,
1228 * verifies every constituent column has @c pg_attribute.attnotnull
1229 * @c = @c true; UNIQUE-with-NULLABLE constraints are rejected
1230 * (UNIQUE allows multiple rows with NULL in PostgreSQL, so the
1231 * @c ∅ @c → @c attr FD does not hold without NOT NULL).
1232 *
1233 * Stores up to @c PROVSQL_KEY_CACHE_MAX_KEYS keys; subsequent keys
1234 * are silently dropped. Skips constraints whose column count
1235 * exceeds @c PROVSQL_KEY_CACHE_MAX_KEY_COLS. Both elisions are
1236 * conservatively safe (the §2 detector simply does not see the
1237 * dropped FDs).
1238 */
1240{
1241 Relation conrel;
1242 SysScanDesc scan;
1243 ScanKeyData skey;
1244 HeapTuple htup;
1245
1246 out->relid = relid;
1247 out->key_n = 0;
1248
1249 conrel = table_open(ConstraintRelationId, AccessShareLock);
1250 ScanKeyInit(&skey,
1251 Anum_pg_constraint_conrelid,
1252 BTEqualStrategyNumber, F_OIDEQ,
1253 ObjectIdGetDatum(relid));
1254 scan = systable_beginscan(conrel,
1255 ConstraintRelidTypidNameIndexId,
1256 true, NULL, 1, &skey);
1257
1258 while(HeapTupleIsValid(htup = systable_getnext(scan))) {
1259 Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(htup);
1260 HeapTuple idxtup;
1261 Form_pg_index idx;
1262 Oid indexrelid;
1263 int k;
1265 bool ok_not_null = true;
1266
1267 if(con->contype != CONSTRAINT_PRIMARY && con->contype != CONSTRAINT_UNIQUE)
1268 continue;
1270 break;
1271
1272 indexrelid = con->conindid;
1273 if(!OidIsValid(indexrelid))
1274 continue;
1275 idxtup = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(indexrelid));
1276 if(!HeapTupleIsValid(idxtup))
1277 continue;
1278 idx = (Form_pg_index) GETSTRUCT(idxtup);
1279
1280 if(idx->indnatts <= 0 || idx->indnatts > PROVSQL_KEY_CACHE_MAX_KEY_COLS) {
1281 ReleaseSysCache(idxtup);
1282 continue;
1283 }
1284
1285 key = &out->keys[out->key_n];
1286 key->col_n = (uint16) idx->indnatts;
1287 for(k = 0; k < idx->indnatts; ++k) {
1288 AttrNumber attno = idx->indkey.values[k];
1289 key->cols[k] = attno;
1290
1291 if(con->contype == CONSTRAINT_UNIQUE) {
1292 HeapTuple atttup =
1293 SearchSysCache2(ATTNUM,
1294 ObjectIdGetDatum(relid),
1295 Int16GetDatum(attno));
1296 if(!HeapTupleIsValid(atttup)) {
1297 ok_not_null = false;
1298 break;
1299 } else {
1300 Form_pg_attribute attform = (Form_pg_attribute) GETSTRUCT(atttup);
1301 if(!attform->attnotnull)
1302 ok_not_null = false;
1303 ReleaseSysCache(atttup);
1304 if(!ok_not_null)
1305 break;
1306 }
1307 }
1308 }
1309 ReleaseSysCache(idxtup);
1310
1311 if(!ok_not_null)
1312 continue; /* nullable UNIQUE -- skip */
1313
1314 ++out->key_n;
1315 }
1316
1317 systable_endscan(scan);
1318 table_close(conrel, AccessShareLock);
1319
1320 return out->key_n > 0;
1321}
1322
1324{
1325 int insert_at = 0;
1326 int pos;
1328 bool has_keys;
1329
1331 CacheRegisterRelcacheCallback(invalidate_key_cache_callback, (Datum) 0);
1333 }
1334
1335 pos = key_cache_find(relid, &insert_at);
1336 if(pos >= 0 && key_cache[pos].valid) {
1337 key_cache_entry *e = &key_cache[pos];
1338 out->relid = relid;
1339 out->key_n = e->key_n;
1340 if(e->key_n > 0)
1341 memcpy(out->keys, e->keys, e->key_n * sizeof(ProvenanceRelationKey));
1342 return e->has_keys;
1343 }
1344
1345 has_keys = fetch_relation_keys(relid, &fresh);
1346
1347 if(pos >= 0) {
1348 key_cache_entry *e = &key_cache[pos];
1349 e->valid = true;
1350 e->has_keys = has_keys;
1351 e->key_n = fresh.key_n;
1352 if(fresh.key_n > 0)
1353 memcpy(e->keys, fresh.keys, fresh.key_n * sizeof(ProvenanceRelationKey));
1354 } else {
1355 key_cache_insert(insert_at, relid, &fresh);
1356 }
1357
1358 *out = fresh;
1359 return has_keys;
1360}
1361
1362PG_FUNCTION_INFO_V1(reset_constants_cache);
1363/**
1364 * @brief SQL function to invalidate the OID constants cache.
1365 *
1366 * Forces a fresh OID lookup for the current database on the next call to
1367 * @c get_constants(). Must be called after @c ALTER EXTENSION provsql
1368 * UPDATE to ensure cached OIDs are refreshed.
1369 * @return Void datum.
1370 */
1371Datum reset_constants_cache(PG_FUNCTION_ARGS)
1372{
1373 int start=0, end=constants_cache_len-1;
1374
1375 while(end>=start) {
1376 unsigned mid=(start+end)/2;
1377 if(constants_cache[mid].database<MyDatabaseId)
1378 start=mid+1;
1379 else if(constants_cache[mid].database>MyDatabaseId)
1380 end=mid-1;
1381 else {
1382 constants_cache[mid].constants = initialize_constants(true);
1383 break;
1384 }
1385 }
1386
1387 PG_RETURN_VOID();
1388}
#define PROVSQL_TABLE_INFO_MAX_BLOCK_KEY
Cap on the number of block-key columns recorded per relation.
#define PROVSQL_TABLE_INFO_MAX_ANCESTORS
Cap on the number of base ancestors recorded per relation.
PostgreSQL cross-version compatibility shims for ProvSQL.
static FuncCandidateList OpernameGetCandidatesCompat(List *names, char oprkind, bool missing_schema_ok)
Version-agnostic wrapper around OpernameGetCandidates().
static FuncCandidateList FuncnameGetCandidatesCompat(List *names, int nargs, List *argnames, bool expand_variadic, bool expand_defaults, bool include_out_arguments, bool missing_ok)
Version-agnostic wrapper around FuncnameGetCandidates().
static bool key_cache_callback_registered
static unsigned table_info_cache_len
static bool table_info_callback_registered
const char * gate_type_name[]
Names of gate types.
static Oid get_enum_oid(Oid enumtypoid, const char *label)
Return the OID of a specific enum label within an enum type.
static int key_cache_find(Oid relid, int *insert_at)
static void invalidate_ancestry_cache_callback(Datum arg, Oid relid)
static void OperatorGet(const char *operatorName, Oid operatorNamespace, Oid leftObjectId, Oid rightObjectId, Oid *operatorObjectId, Oid *functionObjectId)
Retrieve operator and function OIDs for a named operator.
Datum reset_constants_cache(PG_FUNCTION_ARGS)
SQL function to invalidate the OID constants cache.
Oid find_equality_operator(Oid ltypeId, Oid rtypeId)
Find the equality operator OID for two given types.
static void ancestry_cache_insert(int pos, Oid relid, bool present, uint16 ancestor_n, const Oid *ancestors)
#define GET_GATE_TYPE_OID_OPTIONAL(x)
bool provsql_lookup_ancestry(Oid relid, uint16 *ancestor_n_out, Oid *ancestors_out)
Look up the base-ancestor set of a tracked relation.
static Oid get_provsql_func_oid(char *s)
Return the OID of a provsql-schema function named s.
static database_constants_t * constants_cache
Per-database OID constants cache (sorted by database OID).
static void invalidate_table_info_cache_callback(Datum arg, Oid relid)
Relcache callback: PostgreSQL fires this whenever a relation's relcache entry is invalidated (locally...
bool provsql_lookup_table_info(Oid relid, ProvenanceTableInfo *out)
Look up per-table provenance metadata with a backend-local cache.
static Oid get_provsql_func_oid_args(char *s, int nargs, Oid *argtypes)
Return the OID of a provsql-schema function named s with a specific argument-type signature.
static bool ancestry_callback_registered
static void table_info_cache_insert(int pos, Oid relid, bool present, const ProvenanceTableInfo *info)
Insert a fresh entry at pos (which must be the value returned by the most recent table_info_cache_fin...
static table_info_cache_entry * table_info_cache
Sorted by relid.
constants_t get_constants(bool failure_if_not_possible)
Retrieve the cached OID constants for the current database.
static unsigned constants_cache_len
Number of valid entries in constants_cache.
static int table_info_cache_find(Oid relid, int *insert_at)
Find relid in the cache.
static int ancestry_cache_find(Oid relid, int *insert_at)
static void invalidate_key_cache_callback(Datum arg, Oid relid)
bool provsql_lookup_relation_keys(Oid relid, ProvenanceRelationKeys *out)
Look up the PRIMARY-KEY and NOT-NULL-UNIQUE keys of a relation with a backend-local cache.
static unsigned ancestry_cache_len
static bool fetch_relation_keys(Oid relid, ProvenanceRelationKeys *out)
Read the PRIMARY-KEY and NOT-NULL-UNIQUE keys of relid from the system catalogs.
static Oid get_func_oid(char *s)
Return the OID of a globally qualified function named s.
static unsigned key_cache_len
static Oid binary_oper_exact(List *opname, Oid arg1, Oid arg2)
Look up an exactly matching binary operator OID.
#define GET_GATE_TYPE_OID(x)
#define CheckOid(o)
static void key_cache_insert(int pos, Oid relid, const ProvenanceRelationKeys *keys)
static key_cache_entry * key_cache
static constants_t initialize_constants(bool failure_if_not_possible)
Query the system catalogs to populate a fresh constants_t.
static ancestry_cache_entry * ancestry_cache
Core types, constants, and utilities shared across ProvSQL.
#define PROVSQL_KEY_CACHE_MAX_KEY_COLS
@ gate_assumed
Structural marker over a single child whose sub-circuit was computed under a Boolean-provenance assum...
bool provsql_fetch_table_info(Oid relid, ProvenanceTableInfo *out)
Raw IPC fetch (no cache).
Definition table_info.c:175
bool provsql_fetch_ancestry(Oid relid, uint16 *ancestor_n_out, Oid *ancestors_out)
Raw IPC fetch for the ancestry half (no cache).
Definition table_info.c:180
#define PROVSQL_KEY_CACHE_MAX_KEYS
Upper bounds for the relation-key cache.
One PRIMARY-KEY or NOT-NULL-UNIQUE key on a relation.
AttrNumber cols[PROVSQL_KEY_CACHE_MAX_KEY_COLS]
Per-relation set of PRIMARY-KEY and NOT-NULL-UNIQUE keys.
ProvenanceRelationKey keys[PROVSQL_KEY_CACHE_MAX_KEYS]
Per-relation metadata for the safe-query optimisation.
Oid relid
pg_class OID of the relation (primary key)
AttrNumber block_key[PROVSQL_TABLE_INFO_MAX_BLOCK_KEY]
Block-key column numbers.
uint16_t block_key_n
Number of valid entries in block_key.
uint8_t kind
One of provsql_table_kind.
uint16 ancestor_n
when present: count
Oid ancestors[PROVSQL_TABLE_INFO_MAX_ANCESTORS]
when present: ancestor OIDs
Oid relid
pg_class OID (sort key)
bool present
when valid: did the worker return any ancestors?
bool valid
false => refresh on next access
Structure to store the value of various constants.
Oid OID_FUNCTION_REGULAR_INDICATOR
OID of provsql.regular_indicator(boolean): the deterministic gate_one/gate_zero indicator the planner...
Oid OID_FUNCTION_PROVENANCE_EQ
OID of the provenance_eq FUNCTION.
Oid OID_FUNCTION_PROVENANCE_AGGREGATE
OID of the provenance_aggregate FUNCTION.
Oid OID_FUNCTION_WINDOW_DISTINCT_TOKENS
OID of window_distinct_tokens, used for dense_rank(); InvalidOid on a schema that predates it.
Oid OID_FUNCTION_PROVENANCE_SEMIMOD
OID of the provenance_semimod FUNCTION.
Oid OID_FUNCTION_RV_DIV
OID of random_variable_div(rv, rv) -> rv: builds the avg num/denom division gate.
Oid OID_AGG_AVG_RV
provsql.avg(random_variable)
Oid OID_AGG_RV_CORR_IMPL
provsql.rv_corr_impl(ind rv, x rv, y rv)
Oid OID_AGG_RV_SUM_OR_NULL
provsql.rv_sum_or_null(random_variable): the avg-numerator sum, NULL on an empty group (so avg is NUL...
Oid OID_AGG_SUM_RV
OIDs of the RV-returning aggregates, keyed for the per-aggregate identity dispatch in make_rv_aggrega...
Oid OID_FUNCTION_CHOOSE
OID of the choose(anyelement) aggregate (keeps the first non-NULL value); used to decorrelate scalar ...
Oid OID_AGG_RV_STDDEV_SAMP_IMPL
provsql.rv_stddev_samp_impl(ind rv, x rv)
Oid OID_AGG_STDDEV_SAMP_RV
provsql.stddev_samp(rv)
Oid OID_FUNCTION_ANNOTATE
OID of provsql.annotate(uuid,text)->uuid.
Oid OID_FUNCTION_PROVENANCE
OID of the provenance FUNCTION.
Oid OID_FUNCTION_AGG_TOKEN_PLAIN_TEXT
OID of agg_token_plain_text(), the sort key of an ORDER BY on an aggregate result; InvalidOid on a sc...
Oid OID_FUNCTION_RV_LEAST
provsql.least(VARIADIC random_variable[])
Oid OID_FUNCTION_RV_CASE
OID of provsql.rv_case(uuid[])->random_variable.
Oid OID_FUNCTION_INVERSION_FREE_KEY
OID of provsql.inversion_free_key(text,text,int)->text.
Oid OID_FUNCTION_AGG_VALUE_GATE
agg_value_gate(numeric) -> uuid
Oid OID_FUNCTION_AGG_TOKEN_UUID
OID of the agg_token_uuid FUNCTION.
Oid OID_AGG_STDDEV_POP_RV
provsql.stddev_pop(rv)
Oid OID_FUNCTION_RV_AGGREGATE_SEMIMOD
OID of rv_aggregate_semimod(uuid, rv) -> rv: wraps a per-row argument as mixture(prov,...
Oid OID_TYPE_VARCHAR
OID of the VARCHAR TYPE.
Oid OID_FUNCTION_ORDER_CHECKED
OID of order_checked, which warns where that check fails; InvalidOid on a schema that predates it.
Oid OID_FUNCTION_GATE_ZERO
OID of the provenance_zero FUNCTION.
Oid OID_SCHEMA_PROVSQL
OID of the provsql SCHEMA.
Oid OID_FUNCTION_AGG_TOKEN_FROZEN_VALUE
OID of agg_token_frozen_value(), the value of an aggregate result that ProvSQL casts to a plain value...
Oid OID_TYPE_RANDOM_VARIABLE_ARRAY
OID of the random_variable[] TYPE.
Oid OID_AGG_PRODUCT_RV
provsql.product(random_variable)
Oid OID_FUNCTION_AGG_GUARD_HOLDS
OID of agg_guard_holds(), the truth of a comparison of aggregate results in the database as it is,...
Oid OID_FUNCTION_AGG_TOKEN_EXPLODE_CHILDREN
OID of agg_token_explode_children(), the children of the gate of a choose() result exploded into rows...
Oid OID_FUNCTION_COND
OID of provsql.cond(uuid,uuid)->uuid.
Oid OID_TYPE_GATE_TYPE
OID of the provenance_gate TYPE.
Oid OID_FUNCTION_PROVENANCE_PROJECT
OID of the provenance_project FUNCTION.
Oid OID_FUNCTION_PROVENANCE_CONTRIBUTIONS_CAT
OID of the provenance_contributions_cat aggregate, which collects them; InvalidOid on a schema that p...
Oid OID_FUNCTION_RV_AGGREGATE_INDICATOR
OID of rv_aggregate_indicator(uuid) -> rv: the avg denominator wrap mixture(prov, 1,...
Oid OID_FUNCTION_GET_CHILDREN
OID of the get_children FUNCTION.
Oid OID_FUNCTION_ROW_NUMBER_AS_RANK
OID of row_number_as_rank, which row_number() over tracked relations is rewritten into; InvalidOid on...
Oid OID_FUNCTION_RV_AGGREGATE_SEMIMOD_ID
OID of the 3-arg rv_aggregate_semimod(uuid, rv, float8): identity-parameterised wrap mixture(prov,...
Oid OID_UNNEST
OID of the unnest(anyarray) FUNCTION.
Oid OID_FUNCTION_COND_PREDICATE
cond_predicate(uuid,boolean)
Oid OID_AGG_MIN_RV
provsql.min(random_variable)
Oid OID_TYPE_FLOAT
OID of the FLOAT TYPE.
Oid OID_TYPE_AGG_TOKEN
OID of the agg_token TYPE.
Oid OID_FUNCTION_ARRAY_AGG
OID of the array_agg FUNCTION.
Oid OID_FUNCTION_AGG_TOKEN_NULL_EVENT
OID of agg_token_null_event, the IS [NOT] NULL of an aggregate column; InvalidOid on a schema that pr...
Oid OID_TYPE_INT
OID of the INT TYPE.
Oid GATE_TYPE_TO_OID[nb_gate_types]
Array of the OID of each provenance_gate ENUM value.
Oid OID_FUNCTION_PLAIN
OID of the marker plain(), which keeps a LIMIT a truncation of the actual result; InvalidOid on a sch...
Oid OID_FUNCTION_PROVENANCE_PLUS
OID of the provenance_plus FUNCTION.
Oid OID_OPERATOR_NOT_EQUAL_UUID
OID of the <> operator on UUIDs FUNCTION.
Oid OID_TYPE_UUID
OID of the uuid TYPE.
Oid OID_TYPE_TSTZMULTIRANGE
OID of the tstzmultirange TYPE (PG14+, InvalidOid otherwise).
bool ok
true if constants were loaded
Oid OID_TYPE_INT_ARRAY
OID of the INT[] TYPE.
Oid OID_AGG_RV_PERCENTILE_IMPL
provsql.rv_percentile_impl(fraction float8, ind rv, x rv)
Oid OID_FUNCTION_AGG_COUNT_CAN_BE_ZERO
OID of agg_count_can_be_zero; InvalidOid on a schema that predates it.
Oid OID_FUNCTION_PROVENANCE_DELTA
OID of the provenance_delta FUNCTION.
Oid OID_FUNCTION_ASSUME_BOOLEAN
OID of provsql.assume_boolean(uuid)->uuid.
Oid OID_FUNCTION_AGG_POSSIBLE_VALUES
OID of agg_possible_values(), the values an aggregate result takes over the possible worlds,...
Oid OID_FUNCTION_PROVENANCE_TIMES
OID of the provenance_times FUNCTION.
Oid OID_FUNCTION_PROVENANCE_MONUS
OID of the provenance_monus FUNCTION.
Oid OID_FUNCTION_AGG_COND_PREDICATE
agg_token_cond_predicate(agg_token,boolean)
Oid OID_FUNCTION_GIVEN_PREDICATE
given_predicate(boolean) – prefix whole-tuple
Oid OID_TYPE_BOOL
OID of the BOOL TYPE.
Oid OID_FUNCTION_NOT_EQUAL_UUID
OID of the = operator on UUIDs FUNCTION.
Oid OID_FUNCTION_ARRAY_COLLECT
OID of the array_collect(anynonarray) aggregate (array_agg with {} over no rows); the value of a deco...
Oid OID_FUNCTION_AGG_CASE
OID of agg_case(uuid[]), the agg_token constructor the planner hook lowers an aggregate-carrier CASE ...
Oid OID_AGG_CORR_RV
provsql.corr(rv, rv)
Oid OID_FUNCTION_GIVEN
OID of provsql.given(uuid)->uuid.
Oid OID_FUNCTION_PLAIN_TRUTH
OID of plain_truth(), whether a token holds in the database as it is; InvalidOid on a schema that pre...
Oid OID_FUNCTION_GATE_ONE
OID of the provenance_one FUNCTION.
Oid OID_FUNCTION_PROVENANCE_SEMIMOD_NESTED
OID of provenance_semimod_nested(), the contribution of an aggregate result aggregated by an aggregat...
Oid OID_AGG_COVAR_SAMP_RV
provsql.covar_samp(rv, rv)
Oid OID_TYPE_NUMMULTIRANGE
OID of the nummultirange TYPE (PG14+, InvalidOid otherwise).
Oid OID_FUNCTION_RV_AGGREGATE_INDICATOR_VALUED
OID of rv_aggregate_indicator(uuid, rv) -> rv: NULL when the row's value is NULL (SQL NULL-skip for a...
Oid OID_FUNCTION_PROVENANCE_SEMIMOD_FLAT
OID of provenance_semimod_flat(), the contributions of an aggregate result aggregated again; InvalidO...
Oid OID_FUNCTION_PROBABILITY_EVALUATE
OID of the real provsql.probability_evaluate(uuid,text,text).
Oid OID_FUNCTION_RV_COND
OID of provsql.random_variable_cond(random_variable,uuid).
Oid OID_FUNCTION_NTILE_AS_RANK
OID of ntile_as_rank, the tie check of a tracked ntile(); InvalidOid on a schema that predates it.
Oid OID_FUNCTION_RV_COND_PREDICATE
random_variable_cond_predicate(random_variable,boolean)
Oid OID_TYPE_UUID_ARRAY
OID of the uuid[] TYPE.
Oid OID_FUNCTION_PREDICATE_COND_PREDICATE
predicate_cond_predicate(boolean,boolean) – (A)|(B), both events
Oid OID_AGG_MAX_RV
provsql.max(random_variable)
Oid OID_FUNCTION_AGG_COND
OID of provsql.agg_token_cond(agg_token,uuid): the conditioning constructor for the agg_token carrier...
Oid OID_FUNCTION_PROBABILITY_PREDICATE
OID of the probability(boolean,text,text) placeholder.
Oid OID_FUNCTION_GATE_NULL
OID of gate_null(), the value gate of the NULL value (a NULL branch of a CASE over aggregates).
Oid OID_TYPE_RANDOM_VARIABLE
OID of the random_variable TYPE.
Oid OID_AGG_COVAR_POP_RV
SQL-standard statistic aggregates over random_variable rows and their internal indicator-carrying rew...
Oid OID_FUNCTION_PROVENANCE_CMP
OID of the provenance_cmp FUNCTION.
Oid OID_AGG_PERCENTILE_CONT_RV
provsql.percentile_cont(float8) WITHIN GROUP (ORDER BY rv)
Oid OID_FUNCTION_RV_GREATEST
provsql.greatest(VARIADIC random_variable[])
Oid OID_AGG_RV_COVAR_POP_IMPL
provsql.rv_covar_pop_impl(ind rv, x rv, y rv)
Oid OID_AGG_RV_STDDEV_POP_IMPL
provsql.rv_stddev_pop_impl(ind rv, x rv)
Oid OID_TYPE_INT4MULTIRANGE
OID of the int4multirange TYPE (PG14+, InvalidOid otherwise).
Oid OID_AGG_RV_COVAR_SAMP_IMPL
provsql.rv_covar_samp_impl(ind rv, x rv, y rv)
Oid OID_FUNCTION_PROVENANCE_SEMIMOD_NULLABLE
OID of provenance_semimod_nullable, the variant used for aggregates that see their NULL inputs (array...
Oid OID_FUNCTION_GET_EXTRA
OID of the get_extra FUNCTION.
Oid OID_FUNCTION_RV_CMP[6]
OIDs of the random_variable_{eq,ne,le,lt,ge,gt} comparison procedure functions, indexed by the Compar...
Oid OID_FUNCTION_PROVENANCE_CMP_TIMES
OID of the provenance_cmp_times FUNCTION.
Oid OID_FUNCTION_ORDER_DETERMINED
OID of the order_determined aggregate, the tie check of an order-dependent aggregate; InvalidOid on a...
Structure to store the value of various constants for a specific database.
Oid database
OID of the database these constants belong to.
constants_t constants
Cached OID constants for this database.
uint16 key_n
bool valid
Oid relid
bool has_keys
ProvenanceRelationKey keys[PROVSQL_KEY_CACHE_MAX_KEYS]
uint8 kind
when present: provsql_table_kind value
Oid relid
pg_class OID (sort key)
uint16 block_key_n
when present: number of block-key columns
AttrNumber block_key[PROVSQL_TABLE_INFO_MAX_BLOCK_KEY]
when present: block-key column numbers
bool present
when valid: was a record found at the worker?
bool valid
false => refresh on next access