ProvSQL C/C++ API
Adding support for provenance and uncertainty management to PostgreSQL databases
Loading...
Searching...
No Matches
agg_token.c
Go to the documentation of this file.
1/**
2 * @file agg_token.c
3 * @brief PostgreSQL I/O functions and cast for the @c agg_token composite type.
4 *
5 * Implements the three SQL-callable C functions that back the
6 * @c agg_token type:
7 * - @c agg_token_in() – text → agg_token (input function)
8 * - @c agg_token_out() – agg_token → text (output function)
9 * - @c agg_token_cast() – agg_token → text (cast, extracts the UUID part)
10 *
11 * The on-wire text format is @c ( UUID , value ) where @c UUID is the
12 * 36-character hyphenated UUID of the provenance gate and @c value is
13 * the aggregate running value.
14 */
15#include "postgres.h"
16#include "fmgr.h"
17#include "catalog/pg_type.h"
18#include "catalog/pg_collation.h"
19#include "utils/uuid.h"
20#include "utils/numeric.h"
21#include "utils/fmgrprotos.h"
22#include "utils/builtins.h"
23#include "access/xact.h"
24#include "executor/spi.h"
25#include "access/htup_details.h"
26#include "utils/datum.h"
27#include "utils/typcache.h"
28#include "utils/lsyscache.h"
29
30#include "provsql_utils.h"
31#include "agg_token.h"
32
33/**
34 * @brief Set the value of @p aggtok to the @p len first bytes of @p val.
35 *
36 * A value too long for @c agg_token::val keeps its first
37 * @c AGG_TOKEN_PREFIX_LEN bytes, marked by @c AGG_TOKEN_TRUNCATED in the last
38 * byte; @p aggtok must be zeroed.
39 */
40void agg_token_set_value(agg_token *aggtok, const char *val, size_t len)
41{
42 if(len < sizeof(aggtok->val) - 1) {
43 memcpy(aggtok->val, val, len);
44 aggtok->val[len] = '\0';
45 } else {
46 memcpy(aggtok->val, val, AGG_TOKEN_PREFIX_LEN);
47 aggtok->val[AGG_TOKEN_PREFIX_LEN] = '\0';
48 aggtok->val[sizeof(aggtok->val) - 1] = AGG_TOKEN_TRUNCATED;
49 }
50}
51
52/**
53 * @brief The value of @p aggtok, as a C string.
54 *
55 * The value stored in the token, or, when it is only a prefix, the value of
56 * its gate, read with @c provsql.agg_token_value_text; the prefix is returned
57 * if the gate gives none that starts with it.
58 */
59const char *agg_token_value_cstring(const agg_token *aggtok)
60{
61 MemoryContext caller = CurrentMemoryContext;
62 Oid argtypes[1] = {TEXTOID};
63 Datum args[1];
64 char *full = NULL;
65
66 if(aggtok->val[sizeof(aggtok->val) - 1] != AGG_TOKEN_TRUNCATED ||
67 strlen(aggtok->val) != AGG_TOKEN_PREFIX_LEN)
68 return aggtok->val;
69
70 args[0] = CStringGetTextDatum(aggtok->tok);
71 if(SPI_connect() != SPI_OK_CONNECT)
72 return aggtok->val;
73 if(SPI_execute_with_args("SELECT provsql.agg_token_value_text($1::uuid)",
74 1, argtypes, args, NULL, true, 1) == SPI_OK_SELECT &&
75 SPI_processed == 1) {
76 char *v = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
77 size_t n;
78 /* agg_token_value_text gives the value followed by " (*)"; it is that
79 * of the token if it starts with the prefix the token holds. */
80 if(v != NULL && (n = strlen(v)) >= AGG_TOKEN_PREFIX_LEN + 4 &&
81 strcmp(v + n - 4, " (*)") == 0 &&
82 strncmp(v, aggtok->val, AGG_TOKEN_PREFIX_LEN) == 0) {
83 v[n - 4] = '\0';
84 full = MemoryContextStrdup(caller, v);
85 }
86 }
87 SPI_finish();
88 return full != NULL ? full : aggtok->val;
89}
90
91PG_FUNCTION_INFO_V1(agg_token_in);
92/**
93 * @brief Parse an @c agg_token value from its text representation.
94 *
95 * Expected format: @c "( UUID , value )" with a single space around the
96 * comma and at the outer parentheses. Raises @c ERROR on malformed input.
97 * @return Pointer to the newly allocated @c agg_token.
98 */
99Datum
100agg_token_in(PG_FUNCTION_ARGS)
101{
102 char *str = PG_GETARG_CSTRING(0);
103 agg_token* result;
104 const unsigned toklen=sizeof(result->tok)-1;
105 unsigned vallen;
106
107 result = (agg_token *)palloc0(sizeof(agg_token));
108
109 // str is ( UUID , string ) with UUID starting at 2 and with length
110 // 20 (2*UUID-LEN=16) plus 4 hashes; then three characters we can
111 // ignore (two spaces and comma) then the string then two ignored
112 // spaces at the end
113 if(strlen(str)<toklen+7 ||
114 str[0]!='(' || str[1]!=' ' || str[2+toklen] != ' ' || str[2+toklen+1] != ','
115 || str[2+toklen+2] != ' ' || str[strlen(str)-2] != ' '
116 || str[strlen(str)-1] != ')')
117 ereport(ERROR,
118 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
119 errmsg("invalid input syntax for agg_token: \"%s\"",
120 str)));
121
122 strncpy(result->tok, str+2, toklen);
123 result->tok[toklen]='\0';
124
125 vallen=strlen(str)-toklen-2-3-2;
126 agg_token_set_value(result, str+2+toklen+3, vallen);
127
128 PG_RETURN_POINTER(result);
129}
130
131PG_FUNCTION_INFO_V1(agg_token_out);
132/**
133 * @brief Produce a display string for an @c agg_token.
134 *
135 * Default: returns @c "value (*)" (the running value followed by
136 * @c " (*)"), matching @c EXPLAIN and direct @c CAST to text. Where the value
137 * is SQL NULL it is @c "(*)" alone: SQL writes nothing for a NULL, so writing
138 * @c "NULL" would put four characters where a reader expects none, and a text
139 * client would read them as data.
140 *
141 * When the @c provsql.aggtoken_text_as_uuid GUC is on, returns the
142 * underlying provenance UUID instead. This is the form ProvSQL
143 * Studio enables per session so agg_token cells in a result table
144 * expose the circuit root UUID for click-through; the user-facing
145 * @c "value (*)" string is recovered via the
146 * @c provsql.agg_token_value_text(uuid) helper.
147 *
148 * @return C-string representation of the agg_token.
149 */
150Datum
151agg_token_out(PG_FUNCTION_ARGS)
152{
153 agg_token *aggtok = (agg_token *) PG_GETARG_POINTER(0);
154 char *result;
155
157 result = psprintf("%s", aggtok->tok);
158 else if (strcmp(aggtok->val, "NULL") == 0)
159 /* The value is SQL NULL here -- an aggregate with no value, or one the
160 * arithmetic has none for (a division whose divisor reads zero, which
161 * ProvSQL answers rather than raising so that the other worlds stay
162 * answerable). SQL never writes the four characters NULL, so neither do
163 * we: the marker alone says the row is tracked and has no value here.
164 *
165 * Only that spelling, NOT the empty value string @c agg_token_val_is_null
166 * also accepts: an aggregate of the empty text has a value, and writing it
167 * as though it had none would lose the difference. The two are already
168 * indistinguishable in what the gate records, which is a separate matter
169 * from printing them alike. */
170 result = pstrdup("(*)");
171 else
172 result = psprintf("%s (*)", agg_token_value_cstring(aggtok));
173
174 PG_RETURN_CSTRING(result);
175}
176
177PG_FUNCTION_INFO_V1(agg_token_cast);
178/**
179 * @brief Cast an @c agg_token to @c text, returning only the UUID part.
180 *
181 * This is used when the caller needs the provenance circuit UUID
182 * stored in the token rather than the aggregate value.
183 * @return Text datum containing the UUID string of the token.
184 */
185Datum
186agg_token_cast(PG_FUNCTION_ARGS)
187{
188 agg_token *aggtok = (agg_token *) PG_GETARG_POINTER(0);
189 char *result;
190 text *txt_result;
191 int len;
192
193 result = psprintf("%s", aggtok->tok);
194 len = strlen(result);
195
196 txt_result = (text *) palloc(len + ((int32) sizeof(int32)));
197
198 SET_VARSIZE(txt_result, len + ((int32) sizeof(int32)));
199 memcpy(VARDATA(txt_result), result, len);
200
201 PG_RETURN_TEXT_P(txt_result);
202}
203
204/**
205 * @brief True when an @c agg_token value string cannot carry a number.
206 *
207 * An empty or literal @c "NULL" value string (an aggregate whose value is
208 * SQL NULL) must convert to SQL NULL rather than feed the type-input
209 * function a string it rejects.
210 */
211static bool
213{
214 return aggtok->val[0] == '\0' || strcmp(aggtok->val, "NULL") == 0;
215}
216
217/**
218 * @brief The "provenance information is lost" warning of a conversion, once
219 * for a statement and for each target type.
220 *
221 * A conversion runs for every row, and so did its warning: a query over a
222 * large relation wrote one line per row, which says nothing the first does not
223 * and which has filled a server log before. The statement is identified by
224 * @c provsql_stmt_serial, which the executor hook bumps for the user's
225 * outermost statement; a conversion outside any statement of the user (a
226 * direct call in a function the rewriting runs) warns once as well.
227 */
228static void warn_conversion_once(const char *target) {
229 /* One remembered serial per target type: the list is short and fixed. */
230 static const char *seen_target[8];
231 static unsigned seen_serial[8];
232 static int nseen = 0;
233 int i;
234
235 /* Tagged like a freezing, and scoped deliberate, although nothing is frozen
236 * here: this is the conversion of a token the RELATION holds -- reading
237 * "x::text" of a column an earlier statement wrote -- and the text of a
238 * token is the value on the data as it is, which no rewriting gives a
239 * provenance to. The tag is its own, not the freezing's
240 * (aggregate-read-as-plain-value), so that a survey counting causes does not
241 * take a read of stored data for a fragment ProvSQL failed to track. */
242 for (i = 0; i < nseen; ++i)
243 if (seen_target[i] == target) {
244 if (seen_serial[i] == provsql_stmt_serial)
245 return;
246 seen_serial[i] = provsql_stmt_serial;
247 provsql_warning_tagged(PROVSQL_DELIBERATE, "stored-agg-token-conversion", "converting agg_token to %s: provenance information is "
248 "lost", target);
249 return;
250 }
251 if (nseen < (int)(sizeof(seen_target) / sizeof(seen_target[0]))) {
252 seen_target[nseen] = target;
253 seen_serial[nseen] = provsql_stmt_serial;
254 ++nseen;
255 }
256 provsql_warning_tagged(PROVSQL_DELIBERATE, "stored-agg-token-conversion", "converting agg_token to %s: provenance information is lost",
257 target);
258}
259
260
261/** @brief The "sorted on the plain value" warning, once for a statement. */
262static void warn_ordering_once(void)
263{
264 static unsigned seen = (unsigned)-1;
265
266 if (seen == provsql_stmt_serial)
267 return;
268 seen = provsql_stmt_serial;
269 provsql_warning_tagged(PROVSQL_DELIBERATE, "agg-token-ordered-by-value",
270 "ordering or grouping an aggregate result reads "
271 "the value shown, not per world");
272}
273
274/** @brief Whether @p v is the text of a number, as @c numeric_in would read
275 * it: the check a comparison makes before parsing, since parsing what is not
276 * one would raise where a comparison must not. */
277static bool text_is_number(const char *v)
278{
279 const char *p = v;
280 bool digits = false;
281
282 if (p == NULL)
283 return false;
284 while (*p == ' ') ++p;
285 if (*p == '+' || *p == '-') ++p;
286 while (*p >= '0' && *p <= '9') { ++p; digits = true; }
287 if (*p == '.') {
288 ++p;
289 while (*p >= '0' && *p <= '9') { ++p; digits = true; }
290 }
291 if (digits && (*p == 'e' || *p == 'E')) {
292 ++p;
293 if (*p == '+' || *p == '-') ++p;
294 if (!(*p >= '0' && *p <= '9')) return false;
295 while (*p >= '0' && *p <= '9') ++p;
296 }
297 while (*p == ' ') ++p;
298 return digits && *p == '\0';
299}
300
301PG_FUNCTION_INFO_V1(agg_token_btree_cmp);
302/**
303 * @brief Order two @c agg_token values by the value each carries.
304 *
305 * An @c agg_token is a value and a provenance, and the value is the one the
306 * data as it is gives: ordering by it -- @c ORDER @c BY, @c DISTINCT, a
307 * @c GROUP @c BY that sorts -- is ordering by that one value, which another
308 * possible world need not agree with. The warning says so, once for the
309 * statement rather than once per comparison, since a sort makes n log n of
310 * them.
311 *
312 * A token with no value (an aggregate over no row) sorts first, as a @c NULL
313 * does under @c NULLS @c FIRST; two numbers are compared as numbers and
314 * anything else by its text, so that the order is total whatever the
315 * aggregate's own type.
316 */
317Datum
318agg_token_btree_cmp(PG_FUNCTION_ARGS)
319{
320 agg_token *a = (agg_token *) PG_GETARG_POINTER(0);
321 agg_token *b = (agg_token *) PG_GETARG_POINTER(1);
322 bool a_null = agg_token_val_is_null(a), b_null = agg_token_val_is_null(b);
323 const char *av, *bv;
324
326
327 if (a_null || b_null)
328 PG_RETURN_INT32(a_null && b_null ? 0 : (a_null ? -1 : 1));
331 if (text_is_number(av) && text_is_number(bv)) {
332 Datum na = DirectFunctionCall3(numeric_in, CStringGetDatum(av),
333 ObjectIdGetDatum(InvalidOid),
334 Int32GetDatum(-1));
335 Datum nb = DirectFunctionCall3(numeric_in, CStringGetDatum(bv),
336 ObjectIdGetDatum(InvalidOid),
337 Int32GetDatum(-1));
338 PG_RETURN_INT32(DatumGetInt32(DirectFunctionCall2(numeric_cmp, na, nb)));
339 }
340 {
341 int c = strcmp(av, bv);
342 PG_RETURN_INT32(c < 0 ? -1 : (c > 0 ? 1 : 0));
343 }
344}
345
346PG_FUNCTION_INFO_V1(agg_token_to_numeric);
347/**
348 * @brief Cast an @c agg_token to @c numeric, extracting only the value.
349 *
350 * Emits a WARNING that provenance information is lost during the conversion.
351 * @return Numeric datum parsed from the aggregate value string.
352 */
353Datum
354agg_token_to_numeric(PG_FUNCTION_ARGS)
355{
356 agg_token *aggtok = (agg_token *) PG_GETARG_POINTER(0);
357 Datum result;
358
359 warn_conversion_once("numeric");
360
361 if (agg_token_val_is_null(aggtok))
362 PG_RETURN_NULL();
363
364 result = DirectFunctionCall3(numeric_in,
365 CStringGetDatum(agg_token_value_cstring(aggtok)),
366 ObjectIdGetDatum(InvalidOid),
367 Int32GetDatum(-1));
368 PG_RETURN_DATUM(result);
369}
370
371PG_FUNCTION_INFO_V1(agg_token_value);
372/**
373 * @brief Extract the running value of an @c agg_token as @c numeric.
374 *
375 * Unlike @c agg_token_to_numeric, this does @b not emit the
376 * "provenance information is lost" warning: it is the internal accessor
377 * used by the provenance-preserving @c agg_token arithmetic operators
378 * (which keep the provenance in a @c gate_arith circuit), where no
379 * provenance is dropped.
380 * @return Numeric datum parsed from the aggregate value string.
381 */
382Datum
383agg_token_value(PG_FUNCTION_ARGS)
384{
385 agg_token *aggtok = (agg_token *) PG_GETARG_POINTER(0);
386 Datum result;
387
388 if (agg_token_val_is_null(aggtok))
389 PG_RETURN_NULL();
390
391 result = DirectFunctionCall3(numeric_in,
392 CStringGetDatum(agg_token_value_cstring(aggtok)),
393 ObjectIdGetDatum(InvalidOid),
394 Int32GetDatum(-1));
395 PG_RETURN_DATUM(result);
396}
397
398PG_FUNCTION_INFO_V1(agg_token_to_float8);
399/**
400 * @brief Cast an @c agg_token to @c double precision, extracting only the value.
401 *
402 * Emits a WARNING that provenance information is lost during the conversion.
403 * @return Float8 datum parsed from the aggregate value string.
404 */
405Datum
406agg_token_to_float8(PG_FUNCTION_ARGS)
407{
408 agg_token *aggtok = (agg_token *) PG_GETARG_POINTER(0);
409 Datum result;
410
411 warn_conversion_once("double precision");
412
413 if (agg_token_val_is_null(aggtok))
414 PG_RETURN_NULL();
415
416 result = DirectFunctionCall1(float8in,
417 CStringGetDatum(agg_token_value_cstring(aggtok)));
418 PG_RETURN_DATUM(result);
419}
420
421PG_FUNCTION_INFO_V1(agg_token_to_int4);
422/**
423 * @brief Cast an @c agg_token to @c integer, extracting only the value.
424 *
425 * Emits a WARNING that provenance information is lost during the conversion.
426 * @return Int32 datum parsed from the aggregate value string.
427 */
428Datum
429agg_token_to_int4(PG_FUNCTION_ARGS)
430{
431 agg_token *aggtok = (agg_token *) PG_GETARG_POINTER(0);
432 Datum result;
433
434 warn_conversion_once("integer");
435
436 if (agg_token_val_is_null(aggtok))
437 PG_RETURN_NULL();
438
439 result = DirectFunctionCall1(int4in,
440 CStringGetDatum(agg_token_value_cstring(aggtok)));
441 PG_RETURN_DATUM(result);
442}
443
444PG_FUNCTION_INFO_V1(agg_token_to_int8);
445/**
446 * @brief Cast an @c agg_token to @c bigint, extracting only the value.
447 *
448 * Emits a WARNING that provenance information is lost during the conversion.
449 * @return Int64 datum parsed from the aggregate value string.
450 */
451Datum
452agg_token_to_int8(PG_FUNCTION_ARGS)
453{
454 agg_token *aggtok = (agg_token *) PG_GETARG_POINTER(0);
455 Datum result;
456
457 warn_conversion_once("bigint");
458
459 if (agg_token_val_is_null(aggtok))
460 PG_RETURN_NULL();
461
462 result = DirectFunctionCall1(int8in,
463 CStringGetDatum(agg_token_value_cstring(aggtok)));
464 PG_RETURN_DATUM(result);
465}
466
467PG_FUNCTION_INFO_V1(agg_token_to_bool);
468/**
469 * @brief Cast an @c agg_token to @c boolean, extracting only the value.
470 *
471 * The value of a boolean aggregate (@c bool_or, @c bool_and, @c every).
472 * Emits a WARNING that provenance information is lost during the conversion.
473 * @return Boolean datum parsed from the aggregate value string.
474 */
475Datum
476agg_token_to_bool(PG_FUNCTION_ARGS)
477{
478 agg_token *aggtok = (agg_token *) PG_GETARG_POINTER(0);
479
480 warn_conversion_once("boolean");
481
482 if (agg_token_val_is_null(aggtok))
483 PG_RETURN_NULL();
484
485 return DirectFunctionCall1(boolin, CStringGetDatum(agg_token_value_cstring(aggtok)));
486}
487
488PG_FUNCTION_INFO_V1(agg_token_to_text);
489/**
490 * @brief Cast an @c agg_token to @c text, extracting only the value.
491 *
492 * Unlike @c agg_token_cast which returns the UUID part, this returns
493 * the aggregate value as text.
494 * Emits a WARNING that provenance information is lost during the conversion.
495 * @return Text datum containing the aggregate value string.
496 */
497Datum
498agg_token_to_text(PG_FUNCTION_ARGS)
499{
500 agg_token *aggtok = (agg_token *) PG_GETARG_POINTER(0);
501 text *txt_result;
502 const char *val;
503 int len;
504
505 warn_conversion_once("text");
506
507 val = agg_token_value_cstring(aggtok);
508 len = strlen(val);
509 txt_result = (text *) palloc(len + VARHDRSZ);
510 SET_VARSIZE(txt_result, len + VARHDRSZ);
511 memcpy(VARDATA(txt_result), val, len);
512
513 PG_RETURN_TEXT_P(txt_result);
514}
515
516PG_FUNCTION_INFO_V1(agg_token_plain_text);
517/**
518 * @brief The value of an @c agg_token as @c text, NULL for a NULL value,
519 * without the "provenance information is lost" warning.
520 *
521 * The internal accessor of the rewriter's sort keys: an @c ORDER @c BY on an
522 * aggregate result sorts on this value, read in the aggregate's type, while
523 * the column itself keeps its @c agg_token.
524 */
525Datum
526agg_token_plain_text(PG_FUNCTION_ARGS)
527{
528 agg_token *aggtok = (agg_token *) PG_GETARG_POINTER(0);
529
530 if (agg_token_val_is_null(aggtok))
531 PG_RETURN_NULL();
532 PG_RETURN_TEXT_P(cstring_to_text(agg_token_value_cstring(aggtok)));
533}
534
535PG_FUNCTION_INFO_V1(ntile_as_rank);
536/**
537 * @brief The @c agg_token of the bucket @c ntile() gives a row, read over
538 * its rank.
539 *
540 * Rows that tie on the @c ORDER @c BY of the window share the bucket of
541 * their rank, which is the reading of the semantics; SQL numbers them in
542 * some order and may split them between two buckets. Its SQL arguments
543 * are @c bucket, the @c agg_token of the tracked bucket, and @c sql_bucket,
544 * the bucket PostgreSQL gave the row; when the two differ, a warning says so,
545 * once per statement.
546 *
547 * @return @c bucket.
548 */
549Datum
550ntile_as_rank(PG_FUNCTION_ARGS)
551{
552 static TimestampTz warned = 0;
553 agg_token *bucket = (agg_token *) PG_GETARG_POINTER(0);
554 int64 sql_bucket = PG_GETARG_INT64(1);
555
556 if (!agg_token_val_is_null(bucket) &&
557 strtoll(bucket->val, NULL, 10) != sql_bucket &&
558 warned != GetCurrentStatementStartTimestamp()) {
559 warned = GetCurrentStatementStartTimestamp();
561 "ntile() gives rows that tie on the ORDER BY the "
562 "bucket of their rank, where SQL splits them "
563 "between buckets");
564 }
565 PG_RETURN_POINTER(bucket);
566}
567
568PG_FUNCTION_INFO_V1(row_number_as_rank);
569/**
570 * @brief The @c agg_token of @c rank() standing for @c row_number().
571 *
572 * The two are equal when the @c ORDER @c BY of the window leaves no ties;
573 * with ties, SQL itself does not determine which row gets which number.
574 * The rank is what is tracked. Its SQL arguments are @c rank, the
575 * @c agg_token of the rank of the row, and @c row_number, the row number of
576 * the row among those of the database as it is, or NULL for a row absent
577 * from it; when the two differ, or when @c tied says the row ties with a row
578 * of any world, a warning says so, once per statement.
579 *
580 * @return @c rank.
581 */
582Datum
583row_number_as_rank(PG_FUNCTION_ARGS)
584{
585 static TimestampTz warned = 0;
586 agg_token *rank;
587 int64 row_number;
588
589 if (PG_ARGISNULL(0))
590 PG_RETURN_NULL();
591 rank = (agg_token *) PG_GETARG_POINTER(0);
592 /* A tie with a row of any world, those absent from the database as it is
593 * included: the row number SQL would give is not determined there. */
594 if (PG_NARGS() > 2 && !PG_ARGISNULL(2) && PG_GETARG_BOOL(2) &&
595 warned != GetCurrentStatementStartTimestamp()) {
596 warned = GetCurrentStatementStartTimestamp();
597 provsql_warning_tagged(PROVSQL_DELIBERATE, "row-number-as-rank",
598 "row_number() / LIMIT / DISTINCT ON is tracked as "
599 "rank() (WITH TIES), which it differs from when "
600 "rows tie on the ORDER BY");
601 }
602 /* No row number: a row absent from the database as it is, which SQL does
603 * not number (see make_rank_expression). */
604 if (PG_ARGISNULL(1))
605 PG_RETURN_POINTER(rank);
606 row_number = PG_GETARG_INT64(1);
607
608 if (!agg_token_val_is_null(rank) &&
609 strtoll(rank->val, NULL, 10) != row_number &&
610 warned != GetCurrentStatementStartTimestamp()) {
611 warned = GetCurrentStatementStartTimestamp();
612 provsql_warning_tagged(PROVSQL_DELIBERATE, "row-number-as-rank",
613 "row_number() / LIMIT / DISTINCT ON is tracked as "
614 "rank() (WITH TIES), which it differs from when "
615 "rows tie on the ORDER BY");
616 }
617 PG_RETURN_POINTER(rank);
618}
619
620/** @brief Transition state of @c order_determined. */
622 int nvals; ///< Number of aggregated arguments
623 int nargs; ///< Aggregated arguments, then the sort keys
624 bool have_prev; ///< A row was read
625 bool determined; ///< No two peers so far with different values
626 Datum *prev; ///< The previous row's arguments
627 bool *prevnull; ///< Which of them are NULL
628 int16 *typlen; ///< Their type lengths
629 bool *typbyval; ///< Whether passed by value
630 FmgrInfo **keyeq; ///< Equality of each sort key (NULL for a value)
632
633/** @brief Whether two values of the same type are the same value, written the
634 * same way: equal bytes, after decompression for a varlena. */
635static bool
636same_value(Datum a, Datum b, int16 typlen, bool typbyval)
637{
638 if (typlen == -1) {
639 struct varlena *va = pg_detoast_datum_packed((struct varlena *) DatumGetPointer(a));
640 struct varlena *vb = pg_detoast_datum_packed((struct varlena *) DatumGetPointer(b));
641 Size la = VARSIZE_ANY_EXHDR(va), lb = VARSIZE_ANY_EXHDR(vb);
642
643 return la == lb && memcmp(VARDATA_ANY(va), VARDATA_ANY(vb), la) == 0;
644 }
645 return datumIsEqual(a, b, typbyval, typlen);
646}
647
648PG_FUNCTION_INFO_V1(order_determined_transfn);
649/**
650 * @brief Transition of @c order_determined(nvals, v_1, ..., v_nvals,
651 * k_1, ..., k_m): reads the rows of a group in the order of its sort
652 * keys @c k, and records whether two consecutive rows tie on the keys
653 * (are peers) with different values @c v.
654 *
655 * The aggregate it accompanies reads its rows in an order the query then
656 * does not determine. Without sort keys, every row is a peer of every
657 * other. Two NULLs are peers, as they sort together.
658 */
659Datum
661{
662 MemoryContext aggcxt, old;
664 int i;
665 bool peers = true, same = true;
666
667 if (!AggCheckCallContext(fcinfo, &aggcxt))
668 elog(ERROR, "order_determined_transfn called in non-aggregate context");
669
670 if (PG_ARGISNULL(0)) {
671 old = MemoryContextSwitchTo(aggcxt);
672 st = palloc0(sizeof(order_determined_state));
673 st->nvals = PG_GETARG_INT32(1);
674 st->nargs = PG_NARGS() - 2;
675 st->determined = true;
676 st->prev = palloc0(st->nargs * sizeof(Datum));
677 st->prevnull = palloc0(st->nargs * sizeof(bool));
678 st->typlen = palloc0(st->nargs * sizeof(int16));
679 st->typbyval = palloc0(st->nargs * sizeof(bool));
680 st->keyeq = palloc0(st->nargs * sizeof(FmgrInfo *));
681 for (i = 0; i < st->nargs; ++i) {
682 Oid t = get_fn_expr_argtype(fcinfo->flinfo, i + 2);
683 get_typlenbyval(t, &st->typlen[i], &st->typbyval[i]);
684 if (i >= st->nvals) {
685 TypeCacheEntry *tce = lookup_type_cache(t, TYPECACHE_EQ_OPR_FINFO);
686 if (OidIsValid(tce->eq_opr_finfo.fn_oid))
687 st->keyeq[i] = &tce->eq_opr_finfo;
688 }
689 }
690 MemoryContextSwitchTo(old);
691 } else
692 st = (order_determined_state *) PG_GETARG_POINTER(0);
693
694 if (!st->determined)
695 PG_RETURN_POINTER(st);
696
697 if (st->have_prev) {
698 for (i = st->nvals; i < st->nargs && peers; ++i) {
699 bool n = PG_ARGISNULL(i + 2);
700 if (n != st->prevnull[i])
701 peers = false;
702 else if (!n)
703 peers = st->keyeq[i] != NULL
704 ? DatumGetBool(FunctionCall2Coll(st->keyeq[i],
705 OidIsValid(PG_GET_COLLATION())
706 ? PG_GET_COLLATION()
707 : DEFAULT_COLLATION_OID,
708 st->prev[i], PG_GETARG_DATUM(i + 2)))
709 : same_value(st->prev[i], PG_GETARG_DATUM(i + 2), st->typlen[i],
710 st->typbyval[i]);
711 }
712 if (peers) {
713 for (i = 0; i < st->nvals && same; ++i) {
714 bool n = PG_ARGISNULL(i + 2);
715 if (n != st->prevnull[i])
716 same = false;
717 else if (!n)
718 same = same_value(st->prev[i], PG_GETARG_DATUM(i + 2),
719 st->typlen[i], st->typbyval[i]);
720 }
721 if (!same) {
722 st->determined = false;
723 PG_RETURN_POINTER(st);
724 }
725 }
726 }
727
728 old = MemoryContextSwitchTo(aggcxt);
729 for (i = 0; i < st->nargs; ++i) {
730 if (st->have_prev && !st->prevnull[i] && !st->typbyval[i])
731 pfree(DatumGetPointer(st->prev[i]));
732 st->prevnull[i] = PG_ARGISNULL(i + 2);
733 st->prev[i] = st->prevnull[i]
734 ? (Datum) 0
735 : datumCopy(PG_GETARG_DATUM(i + 2), st->typbyval[i], st->typlen[i]);
736 }
737 MemoryContextSwitchTo(old);
738 st->have_prev = true;
739 PG_RETURN_POINTER(st);
740}
741
742PG_FUNCTION_INFO_V1(order_determined_finalfn);
743/** @brief Final function of @c order_determined: whether no two peers have
744 * different values. */
745Datum
747{
748 if (PG_ARGISNULL(0))
749 PG_RETURN_BOOL(true);
750 PG_RETURN_BOOL(((order_determined_state *) PG_GETARG_POINTER(0))->determined);
751}
752
753PG_FUNCTION_INFO_V1(order_checked);
754/**
755 * @brief The value of an order-dependent aggregate, with a warning, once per
756 * statement, where @p determined says its order is not determined.
757 *
758 * The rows tie on its @c ORDER @c BY (or it has none) with different
759 * values: SQL leaves their order open, and the order of the database as it
760 * is is the one read in every world.
761 *
762 * @return its first argument.
763 */
764Datum
765order_checked(PG_FUNCTION_ARGS)
766{
767 static TimestampTz warned = 0;
768
769 if (!PG_ARGISNULL(1) && !PG_GETARG_BOOL(1) &&
770 warned != GetCurrentStatementStartTimestamp()) {
771 warned = GetCurrentStatementStartTimestamp();
772 if (PG_NARGS() > 2 && !PG_ARGISNULL(2) && PG_GETARG_BOOL(2))
773 provsql_warning_tagged(PROVSQL_DELIBERATE, "window-order-undetermined",
774 "a window function reads rows whose order the "
775 "query does not determine (lag or lead with "
776 "rows tying on its ORDER BY, first_value, "
777 "last_value or nth_value with tying rows of "
778 "different values): the order of the database "
779 "as it is is read in every world");
780 else
781 provsql_warning_tagged(PROVSQL_DELIBERATE, "aggregate-order-undetermined",
782 "an order-dependent aggregate reads rows whose "
783 "order the query does not determine (without "
784 "ORDER BY, or tying on it, with different values): "
785 "their order in the database as it is is read in "
786 "every world");
787 }
788 if (PG_ARGISNULL(0))
789 PG_RETURN_NULL();
790 PG_RETURN_DATUM(PG_GETARG_DATUM(0));
791}
Datum agg_token_to_numeric(PG_FUNCTION_ARGS)
Cast an agg_token to numeric, extracting only the value.
Definition agg_token.c:354
Datum order_checked(PG_FUNCTION_ARGS)
The value of an order-dependent aggregate, with a warning, once per statement, where determined says ...
Definition agg_token.c:765
Datum agg_token_btree_cmp(PG_FUNCTION_ARGS)
Order two agg_token values by the value each carries.
Definition agg_token.c:318
Datum agg_token_value(PG_FUNCTION_ARGS)
Extract the running value of an agg_token as numeric.
Definition agg_token.c:383
static bool agg_token_val_is_null(const agg_token *aggtok)
True when an agg_token value string cannot carry a number.
Definition agg_token.c:212
static void warn_ordering_once(void)
The "sorted on the plain value" warning, once for a statement.
Definition agg_token.c:262
Datum order_determined_transfn(PG_FUNCTION_ARGS)
Transition of order_determined(nvals, v_1, ..., v_nvals, k_1, ..., k_m): reads the rows of a gr...
Definition agg_token.c:660
void agg_token_set_value(agg_token *aggtok, const char *val, size_t len)
Set the value of aggtok to the len first bytes of val.
Definition agg_token.c:40
Datum agg_token_out(PG_FUNCTION_ARGS)
Produce a display string for an agg_token.
Definition agg_token.c:151
Datum order_determined_finalfn(PG_FUNCTION_ARGS)
Final function of order_determined: whether no two peers have different values.
Definition agg_token.c:746
static bool same_value(Datum a, Datum b, int16 typlen, bool typbyval)
Whether two values of the same type are the same value, written the same way: equal bytes,...
Definition agg_token.c:636
static bool text_is_number(const char *v)
Whether v is the text of a number, as numeric_in would read it: the check a comparison makes before p...
Definition agg_token.c:277
const char * agg_token_value_cstring(const agg_token *aggtok)
The value of aggtok, as a C string.
Definition agg_token.c:59
Datum agg_token_cast(PG_FUNCTION_ARGS)
Cast an agg_token to text, returning only the UUID part.
Definition agg_token.c:186
Datum agg_token_plain_text(PG_FUNCTION_ARGS)
The value of an agg_token as text, NULL for a NULL value, without the "provenance information is lost...
Definition agg_token.c:526
Datum agg_token_to_int4(PG_FUNCTION_ARGS)
Cast an agg_token to integer, extracting only the value.
Definition agg_token.c:429
Datum agg_token_to_int8(PG_FUNCTION_ARGS)
Cast an agg_token to bigint, extracting only the value.
Definition agg_token.c:452
Datum ntile_as_rank(PG_FUNCTION_ARGS)
The agg_token of the bucket ntile() gives a row, read over its rank.
Definition agg_token.c:550
Datum agg_token_to_text(PG_FUNCTION_ARGS)
Cast an agg_token to text, extracting only the value.
Definition agg_token.c:498
static void warn_conversion_once(const char *target)
The "provenance information is lost" warning of a conversion, once for a statement and for each targe...
Definition agg_token.c:228
Datum agg_token_to_float8(PG_FUNCTION_ARGS)
Cast an agg_token to double precision, extracting only the value.
Definition agg_token.c:406
Datum agg_token_to_bool(PG_FUNCTION_ARGS)
Cast an agg_token to boolean, extracting only the value.
Definition agg_token.c:476
Datum row_number_as_rank(PG_FUNCTION_ARGS)
The agg_token of rank() standing for row_number().
Definition agg_token.c:583
Datum agg_token_in(PG_FUNCTION_ARGS)
Parse an agg_token value from its text representation.
Definition agg_token.c:100
Aggregate-provenance token type used in SQL aggregate functions.
#define AGG_TOKEN_PREFIX_LEN
Length of the prefix of a value too long for agg_token::val.
Definition agg_token.h:38
#define AGG_TOKEN_TRUNCATED
Last byte of agg_token::val when the value is a prefix.
Definition agg_token.h:40
unsigned provsql_stmt_serial
Counts the user's statements, so that a warning a conversion emits at run time is given once for a st...
Definition provsql.c:254
bool provsql_aggtoken_text_as_uuid
When true, agg_token::text emits the underlying provenance UUID instead of "value (*)".
Definition provsql.c:121
#define PROVSQL_DELIBERATE
What kind of limit a refusal or a freezing is.
#define provsql_warning_tagged(scope, tag, fmt,...)
Emit a ProvSQL warning that names its cause by a stable tag.
Core types, constants, and utilities shared across ProvSQL.
Aggregate token bundling a provenance UUID with a running value.
Definition agg_token.h:32
char val[80]
Aggregate running value as a text string.
Definition agg_token.h:34
char tok[2 *UUID_LEN+5]
Provenance UUID as a text string.
Definition agg_token.h:33
Transition state of order_determined.
Definition agg_token.c:621
bool * prevnull
Which of them are NULL.
Definition agg_token.c:627
bool * typbyval
Whether passed by value.
Definition agg_token.c:629
bool determined
No two peers so far with different values.
Definition agg_token.c:625
int16 * typlen
Their type lengths.
Definition agg_token.c:628
FmgrInfo ** keyeq
Equality of each sort key (NULL for a value).
Definition agg_token.c:630
int nvals
Number of aggregated arguments.
Definition agg_token.c:622
Datum * prev
The previous row's arguments.
Definition agg_token.c:626
bool have_prev
A row was read.
Definition agg_token.c:624
int nargs
Aggregated arguments, then the sort keys.
Definition agg_token.c:623