ProvSQL C/C++ API
Adding support for provenance and uncertainty management to PostgreSQL databases
Loading...
Searching...
No Matches
to_prov.cpp
Go to the documentation of this file.
1/**
2 * @file to_prov.cpp
3 * @brief SQL function @c provsql.to_provxml() – XML/JSON circuit export.
4 *
5 * Implements @c provsql.to_provxml(), which serialises the provenance
6 * circuit rooted at a given UUID token to an XML string. The XML
7 * representation can be used for export, interchange, or display.
8 *
9 * The implementation retrieves the circuit from the mmap store via SPI,
10 * traverses it depth-first, and builds the XML document using string
11 * operations. Special XML characters in node labels are escaped by the
12 * local @c xmlEscape() helper.
13 */
14extern "C"
15{
16#include "postgres.h"
17#include "fmgr.h"
18#include "catalog/pg_type.h"
19#include "utils/uuid.h"
20#include "provsql_shmem.h"
21#include "provsql_utils.h"
22
23PG_FUNCTION_INFO_V1(to_provxml);
24}
25
26#include <set>
27#include <csignal>
28#include <utility>
29#include <sstream>
30#include <list>
31#include <algorithm>
32
34
35using namespace std;
36
37/**
38 * @brief Escape special XML characters in @p input.
39 * @param input String to escape.
40 * @return Escaped string suitable for embedding in XML.
41 */
42static string xmlEscape(const std::string& input) {
43 string output;
44 output.reserve(input.size());
45 for (char c : input) {
46 switch (c) {
47 case '&': output += "&amp;"; break;
48 case '<': output += "&lt;"; break;
49 default: output += c; break;
50 }
51 }
52 return output;
53}
54
55/* From provenance_evaluate_compiled.cpp */
56extern const char *drop_temp_table;
57bool join_with_temp_uuids(Oid table, const std::vector<std::string> &uuids);
58
59/**
60 * @brief Build an XML provenance representation for a circuit token.
61 * @param tokenDatum Datum containing the root provenance gate UUID.
62 * @param table Datum with the OID of the provenance mapping table.
63 * @return XML string describing the provenance circuit.
64 */
65static string to_provxml_internal(Datum tokenDatum, Datum table)
66{
67 pg_uuid_t token = *DatumGetUUIDP(tokenDatum);
68
69 stringstream ss;
70
71 ss << "<?xml version='1.0' encoding='UTF-8'?>\n";
72 ss << "<prov:document xmlns:prov='http://www.w3.org/ns/prov#' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:provsql='https://provsql.org/'>\n";
73
75 auto root = c.getGate(uuid2string(token));
76
77 std::unordered_map<gate_t, std::string> provenance_mapping;
78 if(table) {
79 bool drop_table = join_with_temp_uuids(table, c.getMappableUUIDs());
80 constants_t constants = get_constants(true);
81 initialize_provenance_mapping<std::string>(constants, c, provenance_mapping, [](const char *v) {
82 return std::string(v);
83 }, drop_table);
84 }
85
86 std::list<gate_t> to_process { root };
87 std::set<gate_t> seen;
88
89 while(!to_process.empty()) {
90 auto g = to_process.front();
91 to_process.pop_front();
92 auto uuid = c.getUUID(g);
93 gate_type type = c.getGateType(g);
94
95 ss << " <prov:entity prov:id='provsql:" + uuid + "'>\n";
96 ss << " <prov:type xsi:type='xsd:QName'>provsql:" + std::string(gate_type_name[type]) + "</prov:type>\n";
97 if ((type == gate_input || type == gate_mulinput) && table &&
98 provenance_mapping.find(g)!=provenance_mapping.end()) {
99 ss << " <prov:value>" + xmlEscape(provenance_mapping[g]) + "</prov:value>\n";
100 }
101 ss << " </prov:entity>\n";
102
103 bool first=true;
104 const auto &wires = c.getWires(g);
105 std::size_t pos = 0;
106 for(auto h: wires) {
107 ss << " <prov:wasDerivedFrom>\n";
108 ss << " <prov:generatedEntity prov:ref='provsql:" + uuid + "' />\n";
109 ss << " <prov:usedEntity prov:ref='provsql:" + c.getUUID(h) + "' />\n";
110 if(type == gate_monus) {
111 if(first)
112 ss << " <prov:label>left</prov:label>\n";
113 else
114 ss << " <prov:label>right</prov:label>\n";
115 } else if(type == gate_fixsystem) {
116 /* Unknown i is defined by equation i: the first half of the wires
117 * are the unknowns, the second their right-hand sides. */
118 const std::size_t n = wires.size() / 2;
119 if(pos < n)
120 ss << " <prov:label>unknown " + std::to_string(pos + 1) + "</prov:label>\n";
121 else
122 ss << " <prov:label>equation " + std::to_string(pos - n + 1) + "</prov:label>\n";
123 } else if(type == gate_fixpoint) {
124 ss << " <prov:label>component " + std::to_string(c.getInfos(g).first) + "</prov:label>\n";
125 }
126 ++pos;
127
128 ss << " </prov:wasDerivedFrom>\n";
129
130 if(seen.find(h) == seen.end()) {
131 to_process.push_back(h);
132 seen.insert(h);
133 }
134
135 first=false;
136 }
137 }
138
139 ss << "</prov:document>\n";
140
141 return ss.str();
142}
143
144/** @brief PostgreSQL-callable wrapper for to_provxml(). */
145Datum to_provxml(PG_FUNCTION_ARGS)
146{
147 try
148 {
149 Datum token = PG_GETARG_DATUM(0);
150 Datum table = PG_GETARG_DATUM(1);
151
152 std::string s = to_provxml_internal(token, table);
153
154 text *result = (text *) palloc(VARHDRSZ + s.size() + 1);
155 SET_VARSIZE(result, VARHDRSZ + s.size());
156
157 memcpy((void *) VARDATA(result),
158 s.c_str(),
159 s.size());
160 PG_RETURN_TEXT_P(result);
161 } catch(const exception &e) {
162 provsql_error("to_provxml: %s", e.what());
163 }
164 catch (...)
165 {
166 provsql_error("to_provxml: Unknown exception");
167 }
168
169 PG_RETURN_NULL();
170}
GenericCircuit getGenericCircuit(pg_uuid_t token)
Build a GenericCircuit from the mmap store rooted at token.
std::vector< gate_t > & getWires(gate_t g)
Return a mutable reference to the child-wire list of gate g.
Definition Circuit.h:311
gateType getGateType(gate_t g) const
Return the type of gate g.
Definition Circuit.h:301
uuid getUUID(gate_t g) const
Return the UUID string associated with gate g.
Definition Circuit.hpp:65
gate_t getGate(const uuid &u)
Return (or create) the gate associated with UUID u.
Definition Circuit.hpp:50
std::vector< std::string > getMappableUUIDs() const
The UUIDs a provenance mapping can label: those of the input gates, and of the mulinput gates,...
std::pair< unsigned, unsigned > getInfos(gate_t g) const
Return the integer annotation pair for gate g.
const char * drop_temp_table
DROP TABLE statement for the per-query temporary provenance mapping table.
Template helper for populating provenance mappings from SPI results.
void initialize_provenance_mapping(const constants_t &constants, GenericCircuit &c, std::unordered_map< gate_t, T > &provenance_mapping, const std::function< T(const char *)> &charp_to_value, bool drop_table)
Populate a provenance mapping from the current SPI result set.
#define provsql_error(fmt,...)
Report a fatal ProvSQL error and abort the current transaction.
Shared-memory segment and inter-process pipe management.
const char * gate_type_name[]
Names of gate types.
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.
@ gate_fixpoint
Component of the least solution of an equation system: one wire to a gate_fixsystem,...
@ gate_fixsystem
Linear equation system x_i = f_i(x) of a recursive query, one equation per derived tuple: wires [x_1,...
string uuid2string(pg_uuid_t uuid)
Format a pg_uuid_t as a std::string.
Structure to store the value of various constants.
bool join_with_temp_uuids(Oid table, const std::vector< std::string > &uuids)
Join a provenance mapping table with a set of UUIDs using SPI.
Datum to_provxml(PG_FUNCTION_ARGS)
PostgreSQL-callable wrapper for to_provxml().
Definition to_prov.cpp:145
static string to_provxml_internal(Datum tokenDatum, Datum table)
Build an XML provenance representation for a circuit token.
Definition to_prov.cpp:65
static string xmlEscape(const std::string &input)
Escape special XML characters in input.
Definition to_prov.cpp:42