-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathformula.sql
118 lines (105 loc) · 2.57 KB
/
formula.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
\set ECHO none
\pset format unaligned
SET search_path TO provsql_test,provsql;
/* The provenance formula m-semiring */
CREATE TYPE formula_state AS (
formula text,
nbargs int
);
CREATE FUNCTION formula_plus_state(state text[], value text)
RETURNS text[] AS
$$
BEGIN
IF state IS NULL OR array_length(state, 1)=0 THEN
RETURN ARRAY[value];
ELSE
RETURN array_append(state, value);
END IF;
END
$$ LANGUAGE plpgsql IMMUTABLE;
CREATE FUNCTION formula_times_state(state formula_state, value text)
RETURNS formula_state AS
$$
BEGIN
IF state IS NULL OR state.nbargs=0 THEN
RETURN (value,1);
ELSE
RETURN (concat(state.formula,' ⊗ ',value),state.nbargs+1);
END IF;
END
$$ LANGUAGE plpgsql IMMUTABLE;
CREATE FUNCTION formula_array2formula(state text[])
RETURNS text AS
$$
BEGIN
IF array_length(state,1) < 2 THEN
RETURN state;
ELSE
RETURN concat(
'(',
array_to_string(ARRAY(SELECT unnest(state) t ORDER BY t), ' ⊕ '),
')'
);
END IF;
END
$$ LANGUAGE plpgsql IMMUTABLE STRICT;
CREATE FUNCTION formula_state2formula(state formula_state)
RETURNS text AS
$$
BEGIN
IF state.nbargs<2 THEN
RETURN state.formula;
ELSE
RETURN concat('(',state.formula,')');
END IF;
END
$$ LANGUAGE plpgsql IMMUTABLE STRICT;
CREATE AGGREGATE formula_plus(text)
(
sfunc = formula_plus_state,
stype = text[],
initcond = '{}',
finalfunc = formula_array2formula
);
CREATE AGGREGATE formula_times(text)
(
sfunc = formula_times_state,
stype = formula_state,
initcond = '(𝟙,0)',
finalfunc = formula_state2formula
);
CREATE FUNCTION formula_delta(formula text) RETURNS text
LANGUAGE sql IMMUTABLE STRICT
AS $$
SELECT concat('δ(',formula,')')
$$;
CREATE FUNCTION formula_monus(formula1 text, formula2 text) RETURNS text AS
$$
SELECT concat('(',formula1,' ⊖ ',formula2,')')
$$ LANGUAGE SQL IMMUTABLE STRICT;
CREATE FUNCTION formula(token UUID, token2value regclass)
RETURNS text AS
$$
BEGIN
RETURN provenance_evaluate(
token,
token2value,
'𝟙'::text,
'formula_plus',
'formula_times',
'formula_monus',
'formula_delta');
END
$$ LANGUAGE plpgsql PARALLEL SAFE;
/* Example of provenance evaluation */
SELECT create_provenance_mapping('personnel_name', 'personnel', 'name');
CREATE TABLE result_formula AS SELECT
p1.city,
formula(provenance(), 'personnel_name')
FROM personnel p1, personnel p2
WHERE p1.city = p2.city AND p1.id < p2.id
GROUP BY p1.city
ORDER BY p1.city;
SELECT remove_provenance('result_formula');
SELECT * FROM result_formula;
DROP TABLE result_formula;