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"
42 if(len <
sizeof(aggtok->
val) - 1) {
43 memcpy(aggtok->
val, val, len);
44 aggtok->
val[len] =
'\0';
61 MemoryContext caller = CurrentMemoryContext;
62 Oid argtypes[1] = {TEXTOID};
70 args[0] = CStringGetTextDatum(aggtok->
tok);
71 if(SPI_connect() != SPI_OK_CONNECT)
73 if(SPI_execute_with_args(
"SELECT provsql.agg_token_value_text($1::uuid)",
74 1, argtypes, args, NULL,
true, 1) == SPI_OK_SELECT &&
76 char *v = SPI_getvalue(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1);
81 strcmp(v + n - 4,
" (*)") == 0 &&
84 full = MemoryContextStrdup(caller, v);
88 return full != NULL ? full : aggtok->
val;
102 char *str = PG_GETARG_CSTRING(0);
104 const unsigned toklen=
sizeof(result->
tok)-1;
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] !=
')')
118 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
119 errmsg(
"invalid input syntax for agg_token: \"%s\"",
122 strncpy(result->
tok, str+2, toklen);
123 result->
tok[toklen]=
'\0';
125 vallen=strlen(str)-toklen-2-3-2;
128 PG_RETURN_POINTER(result);
157 result = psprintf(
"%s", aggtok->
tok);
158 else if (strcmp(aggtok->
val,
"NULL") == 0)
170 result = pstrdup(
"(*)");
174 PG_RETURN_CSTRING(result);
193 result = psprintf(
"%s", aggtok->
tok);
194 len = strlen(result);
196 txt_result = (text *) palloc(len + ((int32)
sizeof(int32)));
198 SET_VARSIZE(txt_result, len + ((int32)
sizeof(int32)));
199 memcpy(VARDATA(txt_result), result, len);
201 PG_RETURN_TEXT_P(txt_result);
214 return aggtok->
val[0] ==
'\0' || strcmp(aggtok->
val,
"NULL") == 0;
230 static const char *seen_target[8];
231 static unsigned seen_serial[8];
232 static int nseen = 0;
242 for (i = 0; i < nseen; ++i)
243 if (seen_target[i] == target) {
251 if (nseen < (
int)(
sizeof(seen_target) /
sizeof(seen_target[0]))) {
252 seen_target[nseen] = target;
264 static unsigned seen = (unsigned)-1;
270 "ordering or grouping an aggregate result reads "
271 "the value shown, not per world");
284 while (*p ==
' ') ++p;
285 if (*p ==
'+' || *p ==
'-') ++p;
286 while (*p >=
'0' && *p <=
'9') { ++p; digits =
true; }
289 while (*p >=
'0' && *p <=
'9') { ++p; digits =
true; }
291 if (digits && (*p ==
'e' || *p ==
'E')) {
293 if (*p ==
'+' || *p ==
'-') ++p;
294 if (!(*p >=
'0' && *p <=
'9'))
return false;
295 while (*p >=
'0' && *p <=
'9') ++p;
297 while (*p ==
' ') ++p;
298 return digits && *p ==
'\0';
327 if (a_null || b_null)
328 PG_RETURN_INT32(a_null && b_null ? 0 : (a_null ? -1 : 1));
332 Datum na = DirectFunctionCall3(numeric_in, CStringGetDatum(av),
333 ObjectIdGetDatum(InvalidOid),
335 Datum nb = DirectFunctionCall3(numeric_in, CStringGetDatum(bv),
336 ObjectIdGetDatum(InvalidOid),
338 PG_RETURN_INT32(DatumGetInt32(DirectFunctionCall2(numeric_cmp, na, nb)));
341 int c = strcmp(av, bv);
342 PG_RETURN_INT32(c < 0 ? -1 : (c > 0 ? 1 : 0));
364 result = DirectFunctionCall3(numeric_in,
366 ObjectIdGetDatum(InvalidOid),
368 PG_RETURN_DATUM(result);
391 result = DirectFunctionCall3(numeric_in,
393 ObjectIdGetDatum(InvalidOid),
395 PG_RETURN_DATUM(result);
416 result = DirectFunctionCall1(float8in,
418 PG_RETURN_DATUM(result);
439 result = DirectFunctionCall1(int4in,
441 PG_RETURN_DATUM(result);
462 result = DirectFunctionCall1(int8in,
464 PG_RETURN_DATUM(result);
509 txt_result = (text *) palloc(len + VARHDRSZ);
510 SET_VARSIZE(txt_result, len + VARHDRSZ);
511 memcpy(VARDATA(txt_result), val, len);
513 PG_RETURN_TEXT_P(txt_result);
552 static TimestampTz warned = 0;
554 int64 sql_bucket = PG_GETARG_INT64(1);
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 "
565 PG_RETURN_POINTER(bucket);
585 static TimestampTz warned = 0;
591 rank = (
agg_token *) PG_GETARG_POINTER(0);
594 if (PG_NARGS() > 2 && !PG_ARGISNULL(2) && PG_GETARG_BOOL(2) &&
595 warned != GetCurrentStatementStartTimestamp()) {
596 warned = GetCurrentStatementStartTimestamp();
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");
605 PG_RETURN_POINTER(rank);
606 row_number = PG_GETARG_INT64(1);
609 strtoll(rank->
val, NULL, 10) != row_number &&
610 warned != GetCurrentStatementStartTimestamp()) {
611 warned = GetCurrentStatementStartTimestamp();
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");
617 PG_RETURN_POINTER(rank);
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);
643 return la == lb && memcmp(VARDATA_ANY(va), VARDATA_ANY(vb), la) == 0;
645 return datumIsEqual(a, b, typbyval, typlen);
662 MemoryContext aggcxt, old;
665 bool peers =
true, same =
true;
667 if (!AggCheckCallContext(fcinfo, &aggcxt))
668 elog(ERROR,
"order_determined_transfn called in non-aggregate context");
670 if (PG_ARGISNULL(0)) {
671 old = MemoryContextSwitchTo(aggcxt);
673 st->
nvals = PG_GETARG_INT32(1);
674 st->
nargs = PG_NARGS() - 2;
676 st->
prev = palloc0(st->
nargs *
sizeof(Datum));
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);
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;
690 MemoryContextSwitchTo(old);
695 PG_RETURN_POINTER(st);
698 for (i = st->
nvals; i < st->nargs && peers; ++i) {
699 bool n = PG_ARGISNULL(i + 2);
703 peers = st->
keyeq[i] != NULL
704 ? DatumGetBool(FunctionCall2Coll(st->
keyeq[i],
705 OidIsValid(PG_GET_COLLATION())
707 : DEFAULT_COLLATION_OID,
708 st->
prev[i], PG_GETARG_DATUM(i + 2)))
713 for (i = 0; i < st->
nvals && same; ++i) {
714 bool n = PG_ARGISNULL(i + 2);
723 PG_RETURN_POINTER(st);
728 old = MemoryContextSwitchTo(aggcxt);
729 for (i = 0; i < st->
nargs; ++i) {
731 pfree(DatumGetPointer(st->
prev[i]));
732 st->
prevnull[i] = PG_ARGISNULL(i + 2);
735 : datumCopy(PG_GETARG_DATUM(i + 2), st->
typbyval[i], st->
typlen[i]);
737 MemoryContextSwitchTo(old);
739 PG_RETURN_POINTER(st);
749 PG_RETURN_BOOL(
true);
767 static TimestampTz warned = 0;
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))
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");
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 "
790 PG_RETURN_DATUM(PG_GETARG_DATUM(0));
Datum agg_token_to_numeric(PG_FUNCTION_ARGS)
Cast an agg_token to numeric, extracting only the value.
Datum order_checked(PG_FUNCTION_ARGS)
The value of an order-dependent aggregate, with a warning, once per statement, where determined says ...
Datum agg_token_btree_cmp(PG_FUNCTION_ARGS)
Order two agg_token values by the value each carries.
Datum agg_token_value(PG_FUNCTION_ARGS)
Extract the running value of an agg_token as numeric.
static bool agg_token_val_is_null(const agg_token *aggtok)
True when an agg_token value string cannot carry a number.
static void warn_ordering_once(void)
The "sorted on the plain value" warning, once for a statement.
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...
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.
Datum agg_token_out(PG_FUNCTION_ARGS)
Produce a display string for an agg_token.
Datum order_determined_finalfn(PG_FUNCTION_ARGS)
Final function of order_determined: whether no two peers have different values.
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,...
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...
const char * agg_token_value_cstring(const agg_token *aggtok)
The value of aggtok, as a C string.
Datum agg_token_cast(PG_FUNCTION_ARGS)
Cast an agg_token to text, returning only the UUID part.
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...
Datum agg_token_to_int4(PG_FUNCTION_ARGS)
Cast an agg_token to integer, extracting only the value.
Datum agg_token_to_int8(PG_FUNCTION_ARGS)
Cast an agg_token to bigint, extracting only the value.
Datum ntile_as_rank(PG_FUNCTION_ARGS)
The agg_token of the bucket ntile() gives a row, read over its rank.
Datum agg_token_to_text(PG_FUNCTION_ARGS)
Cast an agg_token to text, extracting only the value.
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...
Datum agg_token_to_float8(PG_FUNCTION_ARGS)
Cast an agg_token to double precision, extracting only the value.
Datum agg_token_to_bool(PG_FUNCTION_ARGS)
Cast an agg_token to boolean, extracting only the value.
Datum row_number_as_rank(PG_FUNCTION_ARGS)
The agg_token of rank() standing for row_number().
Datum agg_token_in(PG_FUNCTION_ARGS)
Parse an agg_token value from its text representation.
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.
#define AGG_TOKEN_TRUNCATED
Last byte of agg_token::val when the value is a prefix.
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...
bool provsql_aggtoken_text_as_uuid
When true, agg_token::text emits the underlying provenance UUID instead of "value (*)".
#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.
char val[80]
Aggregate running value as a text string.
char tok[2 *UUID_LEN+5]
Provenance UUID as a text string.
Transition state of order_determined.
bool * prevnull
Which of them are NULL.
bool * typbyval
Whether passed by value.
bool determined
No two peers so far with different values.
int16 * typlen
Their type lengths.
FmgrInfo ** keyeq
Equality of each sort key (NULL for a value).
int nvals
Number of aggregated arguments.
Datum * prev
The previous row's arguments.
bool have_prev
A row was read.
int nargs
Aggregated arguments, then the sort keys.