ProvSQL C/C++ API
Adding support for provenance and uncertainty management to PostgreSQL databases
Loading...
Searching...
No Matches
where_provenance.cpp
Go to the documentation of this file.
1/**
2 * @file where_provenance.cpp
3 * @brief SQL function @c provsql.where_provenance() – column-level provenance.
4 *
5 * Implements @c provsql.where_provenance(), which evaluates the
6 * where-provenance of a query result tuple. Where-provenance identifies
7 * the base-relation cells (table, row, column) from which each output
8 * value was copied.
9 *
10 * The function builds a @c WhereCircuit from the mmap-backed circuit store
11 * (using SPI to obtain gate information), evaluates it via
12 * @c WhereCircuit::evaluate(), and returns the result as a PostgreSQL
13 * text-array value containing @c "table.tid.position" locator strings.
14 */
15extern "C" {
16
17#include "postgres.h"
18#include "fmgr.h"
19#include "catalog/pg_type.h"
20#include "utils/uuid.h"
21#include "executor/spi.h"
22#include "utils/builtins.h"
23
24#include "provsql_shmem.h"
25#include "provsql_utils.h"
26
27PG_FUNCTION_INFO_V1(where_provenance);
28}
29
30#include <algorithm>
31#include <utility>
32#include <sstream>
33
34#include "WhereCircuit.h"
35#include "provsql_utils_cpp.h"
36
37using namespace std;
38
39/**
40 * @brief Parse a PostgreSQL text representation of an array of integer pairs.
41 * @param s String in the form @c {{a,b},{c,d},...}.
42 * @return Vector of (first, second) integer pairs.
43 */
44static vector<pair<int,int> > parse_array(string s)
45{
46 s=s.substr(1,s.size()-2); // Remove initial '{' and final '}'
47
48 vector<pair<int,int> > result;
49 istringstream iss(s);
50 string p;
51
52 while(getline(iss, p, '}'))
53 {
54 if(!p.empty() && p[0]==',')
55 p=p.substr(1);
56
57 int k=p.find(",",1);
58 string s1=p.substr(1,k-1);
59 string s2=p.substr(k+1,p.size()-k);
60 int i1 = (s1=="NULL") ? 0 : stoi(s1);
61 int i2 = (s2=="NULL") ? 0 : stoi(s2);
62 result.push_back(make_pair(i1,i2));
63 }
64
65 return result;
66}
67
68/**
69 * @brief Build a JSON where-provenance description for the circuit rooted at @p token.
70 * @param token Datum containing the root provenance gate UUID.
71 * @return JSON string describing the where-provenance.
72 */
74 (Datum token)
75{
76 Datum arguments[1]={token};
77 const constants_t constants = get_constants(true);
78 Oid argtypes[1]={constants.OID_TYPE_UUID};
79 char nulls[1] = {' '};
80
81 SPI_connect();
82
84
85 if(SPI_execute_with_args(
86 "SELECT * FROM provsql.sub_circuit_for_where($1)", 1, argtypes, arguments, nulls, true, 0)
87 == SPI_OK_SELECT) {
88 int proc = SPI_processed;
89 TupleDesc tupdesc = SPI_tuptable->tupdesc;
90 SPITupleTable *tuptable = SPI_tuptable;
91
92 for (int i = 0; i < proc; i++)
93 {
94 HeapTuple tuple = tuptable->vals[i];
95
96 string f = SPI_getvalue(tuple, tupdesc, 1);
97 string type = SPI_getvalue(tuple, tupdesc, 3);
98 if(type == "input") {
99 char *table = SPI_getvalue(tuple, tupdesc, 4);
100 if(table == nullptr)
102 "where_provenance: input gate %s could not be traced back to a "
103 "provenance-tracked relation (it may belong to a table that was "
104 "dropped, or to one outside the search_path)", f.c_str());
105 int nb_columns = stoi(SPI_getvalue(tuple, tupdesc, 5));
106
107 c.setGateInput(f, table, nb_columns);
108 } else if(type == "cmp") {
109 /* A comparison is a condition on whether the row is there (the
110 * rank cut of ORDER BY ... LIMIT, a comparison on an aggregate):
111 * where-provenance is about where values are copied from, which a
112 * condition does not change. sub_circuit_for_where stops at it, so
113 * it is a leaf here. */
115 } else {
116 auto id=c.getGate(f);
117
118 if(type == "times" || type == "assumed" || type == "annotation"
119 || type == "delta") {
120 /* assumed, annotation and delta are single-child wrappers; a
121 * single-wire TIMES is the identity in WhereCircuit semantics (the
122 * Locator-set union of one child is just that child's), so funnel
123 * them all through the same case. delta says that a group exists:
124 * its grouping columns are copied from the rows of the group, the
125 * PLUS below it. */
127 } else if(type == "plus") {
129 } else if(type == "project") {
130 vector<pair<int,int> > v = parse_array(SPI_getvalue(tuple, tupdesc, 7));
131 sort(v.begin(), v.end(), [](auto &left, auto &right) {
132 return left.second < right.second;
133 });
134 vector<int> infos;
135 for(auto p : v) {
136 infos.push_back(p.first);
137 }
138 c.setGateProjection(f, std::move(infos));
139 } else if(type == "eq") {
140 vector<pair<int,int> > v = parse_array(std::string("{")+SPI_getvalue(tuple, tupdesc, 6)+"}");
141 if(v.size()!=1)
142 provsql_error("Incorrect extra information on eq gate");
143 c.setGateEquality(f, v[0].first, v[0].second);
144 } else if(type == "monusr" || type == "monusl" || type == "monus") {
145 provsql_unsupported(PROVSQL_OUT_OF_SCOPE, "where-non-monotone", "Where-provenance of non-monotone query not supported");
146 } else if(type == "fixpoint" || type == "fixsystem" || type == "fixvar") {
147 provsql_unsupported(PROVSQL_OUT_OF_SCOPE, "where-recursive-cycle", "Where-provenance of a tuple derived through a cycle of a recursive query not supported");
148 } else {
149 provsql_error("Where-provenance does not support gates of type %s", type.c_str());
150 }
151 c.addWire(id, c.getGate(SPI_getvalue(tuple, tupdesc, 2)));
152 }
153 }
154 } else {
155 provsql_error("SPI_execute_with_args failed on provsql.sub_circuit_for_where");
156 }
157
158 SPI_finish();
159
160 auto gate = c.getGate(UUIDDatum2string(token));
161
162 vector<set<WhereCircuit::Locator> > v = c.evaluate(gate);
163
164 ostringstream os;
165 os << "{";
166 bool ofirst=true;
167 for(auto s : v) {
168 if(!ofirst)
169 os << ",";
170 os << "[";
171 bool ifirst=true;
172 for(auto l : s) {
173 if(!ifirst)
174 os << ";";
175 os << l.toString();
176 ifirst=false;
177 }
178 os << "]";
179 ofirst=false;
180 }
181 os << "}";
182
183 return os.str();
184}
185
186/** @brief PostgreSQL-callable wrapper for where_provenance(). */
187Datum where_provenance(PG_FUNCTION_ARGS)
188{
189 if (PG_ARGISNULL(0))
190 PG_RETURN_NULL();
191
192 try {
193 Datum token = PG_GETARG_DATUM(0);
194
195 PG_RETURN_TEXT_P(cstring_to_text(where_provenance_internal(token).c_str()));
196 } catch(const std::exception &e) {
197 provsql_error("where_provenance: %s", e.what());
198 } catch(...) {
199 provsql_error("where_provenance: Unknown exception");
200 }
201}
Where-provenance circuit tracking column-level data origin.
@ PLUS
Sum (disjunction) of child where-provenance sets.
@ CONDITION
A comparison beside the row it filters: no column, no value copied.
@ TIMES
Product (conjunction) of child where-provenance sets.
void addWire(gate_t f, gate_t t)
Add a directed wire from gate f (parent) to gate t (child).
Definition Circuit.hpp:195
gate_t getGate(const uuid &u)
Return (or create) the gate associated with UUID u.
Definition Circuit.hpp:50
Circuit encoding where-provenance (column-level data origin).
gate_t setGateInput(const uuid &u, std::string table, int nb_columns)
Create an input gate for a specific table row.
gate_t setGateEquality(const uuid &u, int pos1, int pos2)
Create an equality (equijoin) gate for two attribute positions.
gate_t setGate(const uuid &u, WhereGate type) override
Create or update the gate associated with UUID u.
gate_t setGateProjection(const uuid &u, std::vector< int > &&infos)
Create a projection gate with column mapping.
std::vector< std::set< Locator > > evaluate(gate_t g) const
Evaluate the where-provenance circuit at gate g.
#define PROVSQL_OUT_OF_SCOPE
#define provsql_error(fmt,...)
Report a fatal ProvSQL error and abort the current transaction.
#define provsql_unsupported(scope, tag, fmt,...)
Refuse a query ProvSQL cannot track, and abort the transaction.
Shared-memory segment and inter-process pipe management.
constants_t get_constants(bool failure_if_not_possible)
Retrieve the cached OID constants for the current database.
Core types, constants, and utilities shared across ProvSQL.
string UUIDDatum2string(Datum token)
Convert a PostgreSQL Datum holding a UUID to a std::string.
C++ utility functions for UUID manipulation.
Structure to store the value of various constants.
Oid OID_TYPE_UUID
OID of the uuid TYPE.
Datum where_provenance(PG_FUNCTION_ARGS)
PostgreSQL-callable wrapper for where_provenance().
static string where_provenance_internal(Datum token)
Build a JSON where-provenance description for the circuit rooted at token.
static vector< pair< int, int > > parse_array(string s)
Parse a PostgreSQL text representation of an array of integer pairs.