Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * extended_stats_funcs.c
4 : : * Functions for manipulating extended statistics.
5 : : *
6 : : * This file includes the set of facilities required to support the direct
7 : : * manipulations of extended statistics objects.
8 : : *
9 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
10 : : * Portions Copyright (c) 1994, Regents of the University of California
11 : : *
12 : : * IDENTIFICATION
13 : : * src/backend/statistics/extended_stats_funcs.c
14 : : *
15 : : *-------------------------------------------------------------------------
16 : : */
17 : : #include "postgres.h"
18 : :
19 : : #include "access/heapam.h"
20 : : #include "access/relation.h"
21 : : #include "catalog/indexing.h"
22 : : #include "catalog/namespace.h"
23 : : #include "catalog/pg_collation_d.h"
24 : : #include "catalog/pg_database.h"
25 : : #include "catalog/pg_operator.h"
26 : : #include "catalog/pg_statistic_ext.h"
27 : : #include "catalog/pg_statistic_ext_data.h"
28 : : #include "miscadmin.h"
29 : : #include "nodes/makefuncs.h"
30 : : #include "nodes/nodeFuncs.h"
31 : : #include "optimizer/optimizer.h"
32 : : #include "statistics/extended_stats_internal.h"
33 : : #include "statistics/stat_utils.h"
34 : : #include "utils/acl.h"
35 : : #include "utils/array.h"
36 : : #include "utils/builtins.h"
37 : : #include "utils/fmgroids.h"
38 : : #include "utils/jsonb.h"
39 : : #include "utils/lsyscache.h"
40 : : #include "utils/syscache.h"
41 : : #include "utils/typcache.h"
42 : :
43 : :
44 : : /*
45 : : * Index of the arguments for the SQL functions.
46 : : */
47 : : enum extended_stats_argnum
48 : : {
49 : : RELSCHEMA_ARG = 0,
50 : : RELNAME_ARG,
51 : : STATSCHEMA_ARG,
52 : : STATNAME_ARG,
53 : : INHERITED_ARG,
54 : : NDISTINCT_ARG,
55 : : DEPENDENCIES_ARG,
56 : : MOST_COMMON_VALS_ARG,
57 : : MOST_COMMON_FREQS_ARG,
58 : : MOST_COMMON_BASE_FREQS_ARG,
59 : : EXPRESSIONS_ARG,
60 : : NUM_EXTENDED_STATS_ARGS,
61 : : };
62 : :
63 : : /*
64 : : * The argument names and type OIDs of the arguments for the SQL
65 : : * functions.
66 : : */
67 : : static struct StatsArgInfo extarginfo[] =
68 : : {
69 : : [RELSCHEMA_ARG] = {"schemaname", TEXTOID},
70 : : [RELNAME_ARG] = {"relname", TEXTOID},
71 : : [STATSCHEMA_ARG] = {"statistics_schemaname", TEXTOID},
72 : : [STATNAME_ARG] = {"statistics_name", TEXTOID},
73 : : [INHERITED_ARG] = {"inherited", BOOLOID},
74 : : [NDISTINCT_ARG] = {"n_distinct", PG_NDISTINCTOID},
75 : : [DEPENDENCIES_ARG] = {"dependencies", PG_DEPENDENCIESOID},
76 : : [MOST_COMMON_VALS_ARG] = {"most_common_vals", TEXTARRAYOID},
77 : : [MOST_COMMON_FREQS_ARG] = {"most_common_freqs", FLOAT8ARRAYOID},
78 : : [MOST_COMMON_BASE_FREQS_ARG] = {"most_common_base_freqs", FLOAT8ARRAYOID},
79 : : [EXPRESSIONS_ARG] = {"exprs", JSONBOID},
80 : : [NUM_EXTENDED_STATS_ARGS] = {0},
81 : : };
82 : :
83 : : /*
84 : : * An index of the elements of a stxdexpr Datum, which repeat for each
85 : : * expression in the extended statistics object.
86 : : */
87 : : enum extended_stats_exprs_element
88 : : {
89 : : NULL_FRAC_ELEM = 0,
90 : : AVG_WIDTH_ELEM,
91 : : N_DISTINCT_ELEM,
92 : : MOST_COMMON_VALS_ELEM,
93 : : MOST_COMMON_FREQS_ELEM,
94 : : HISTOGRAM_BOUNDS_ELEM,
95 : : CORRELATION_ELEM,
96 : : MOST_COMMON_ELEMS_ELEM,
97 : : MOST_COMMON_ELEM_FREQS_ELEM,
98 : : ELEM_COUNT_HISTOGRAM_ELEM,
99 : : RANGE_LENGTH_HISTOGRAM_ELEM,
100 : : RANGE_EMPTY_FRAC_ELEM,
101 : : RANGE_BOUNDS_HISTOGRAM_ELEM,
102 : : NUM_ATTRIBUTE_STATS_ELEMS
103 : : };
104 : :
105 : : /*
106 : : * The argument names of the repeating arguments for stxdexpr.
107 : : */
108 : : static const char *extexprargname[NUM_ATTRIBUTE_STATS_ELEMS] =
109 : : {
110 : : "null_frac",
111 : : "avg_width",
112 : : "n_distinct",
113 : : "most_common_vals",
114 : : "most_common_freqs",
115 : : "histogram_bounds",
116 : : "correlation",
117 : : "most_common_elems",
118 : : "most_common_elem_freqs",
119 : : "elem_count_histogram",
120 : : "range_length_histogram",
121 : : "range_empty_frac",
122 : : "range_bounds_histogram"
123 : : };
124 : :
125 : : static bool extended_statistics_update(FunctionCallInfo fcinfo);
126 : :
127 : : static HeapTuple get_pg_statistic_ext(Relation pg_stext, Oid nspoid,
128 : : const char *stxname);
129 : : static bool delete_pg_statistic_ext_data(Oid stxoid, bool inherited);
130 : :
131 : : /*
132 : : * Track the extended statistics kinds expected for a pg_statistic_ext
133 : : * tuple.
134 : : */
135 : : typedef struct
136 : : {
137 : : bool ndistinct;
138 : : bool dependencies;
139 : : bool mcv;
140 : : bool expressions;
141 : : } StakindFlags;
142 : :
143 : : static void expand_stxkind(HeapTuple tup, StakindFlags *enabled);
144 : : static void upsert_pg_statistic_ext_data(const Datum *values,
145 : : const bool *nulls,
146 : : const bool *replaces);
147 : :
148 : : static bool check_mcvlist_array(const ArrayType *arr, int argindex,
149 : : int required_ndims, int mcv_length);
150 : : static Datum import_expressions(Relation pgsd, int numexprs,
151 : : Oid *atttypids, int32 *atttypmods,
152 : : Oid *atttypcolls, Jsonb *exprs_jsonb,
153 : : bool *exprs_is_perfect);
154 : : static Datum import_mcv(const ArrayType *mcv_arr,
155 : : const ArrayType *freqs_arr,
156 : : const ArrayType *base_freqs_arr,
157 : : Oid *atttypids, int32 *atttypmods,
158 : : Oid *atttypcolls, int numattrs,
159 : : bool *ok);
160 : :
161 : : static char *jbv_string_get_cstr(JsonbValue *jval);
162 : : static bool jbv_to_infunc_datum(JsonbValue *jval, PGFunction func,
163 : : AttrNumber exprnum, const char *argname,
164 : : Datum *datum);
165 : : static bool key_in_expr_argnames(JsonbValue *key);
166 : : static bool check_all_expr_argnames_valid(JsonbContainer *cont, AttrNumber exprnum);
167 : : static Datum array_in_safe(FmgrInfo *array_in, const char *s, Oid typid,
168 : : int32 typmod, AttrNumber exprnum,
169 : : const char *element_name, bool allow_empty, bool *ok);
170 : : static Datum import_pg_statistic(Relation pgsd, JsonbContainer *cont,
171 : : AttrNumber exprnum, FmgrInfo *array_in_fn,
172 : : Oid typid, int32 typmod, Oid typcoll,
173 : : bool *pg_statistic_ok);
174 : :
175 : : /*
176 : : * Fetch a pg_statistic_ext row by name and namespace OID.
177 : : */
178 : : static HeapTuple
179 : 352 : get_pg_statistic_ext(Relation pg_stext, Oid nspoid, const char *stxname)
180 : : {
181 : : ScanKeyData key[2];
182 : : SysScanDesc scan;
183 : : HeapTuple tup;
184 : 352 : Oid stxoid = InvalidOid;
185 : :
186 : 352 : ScanKeyInit(&key[0],
187 : : Anum_pg_statistic_ext_stxname,
188 : : BTEqualStrategyNumber,
189 : : F_NAMEEQ,
190 : : CStringGetDatum(stxname));
191 : 352 : ScanKeyInit(&key[1],
192 : : Anum_pg_statistic_ext_stxnamespace,
193 : : BTEqualStrategyNumber,
194 : : F_OIDEQ,
195 : : ObjectIdGetDatum(nspoid));
196 : :
197 : : /*
198 : : * Try to find matching pg_statistic_ext row.
199 : : */
200 : 352 : scan = systable_beginscan(pg_stext,
201 : : StatisticExtNameIndexId,
202 : : true,
203 : : NULL,
204 : : 2,
205 : : key);
206 : :
207 : : /* Lookup is based on a unique index, so we get either 0 or 1 tuple. */
208 : 352 : tup = systable_getnext(scan);
209 : :
210 [ + + ]: 352 : if (HeapTupleIsValid(tup))
211 : 344 : stxoid = ((Form_pg_statistic_ext) GETSTRUCT(tup))->oid;
212 : :
213 : 352 : systable_endscan(scan);
214 : :
215 [ + + ]: 352 : if (!OidIsValid(stxoid))
216 : 8 : return NULL;
217 : :
218 : 344 : return SearchSysCacheCopy1(STATEXTOID, ObjectIdGetDatum(stxoid));
219 : : }
220 : :
221 : : /*
222 : : * Decode the stxkind column so that we know which stats types to expect,
223 : : * returning a StakindFlags set depending on the stats kinds expected by
224 : : * a pg_statistic_ext tuple.
225 : : */
226 : : static void
227 : 324 : expand_stxkind(HeapTuple tup, StakindFlags *enabled)
228 : : {
229 : : Datum datum;
230 : : ArrayType *arr;
231 : : char *kinds;
232 : :
233 : 324 : datum = SysCacheGetAttrNotNull(STATEXTOID,
234 : : tup,
235 : : Anum_pg_statistic_ext_stxkind);
236 : 324 : arr = DatumGetArrayTypeP(datum);
237 [ + - + - : 324 : if (ARR_NDIM(arr) != 1 || ARR_HASNULL(arr) || ARR_ELEMTYPE(arr) != CHAROID)
- + ]
238 [ # # ]: 0 : elog(ERROR, "stxkind is not a one-dimensional char array");
239 : :
240 [ - + ]: 324 : kinds = (char *) ARR_DATA_PTR(arr);
241 : :
242 [ + + ]: 1341 : for (int i = 0; i < ARR_DIMS(arr)[0]; i++)
243 : : {
244 [ + + + + : 1017 : switch (kinds[i])
- ]
245 : : {
246 : 248 : case STATS_EXT_NDISTINCT:
247 : 248 : enabled->ndistinct = true;
248 : 248 : break;
249 : 249 : case STATS_EXT_DEPENDENCIES:
250 : 249 : enabled->dependencies = true;
251 : 249 : break;
252 : 267 : case STATS_EXT_MCV:
253 : 267 : enabled->mcv = true;
254 : 267 : break;
255 : 253 : case STATS_EXT_EXPRESSIONS:
256 : 253 : enabled->expressions = true;
257 : 253 : break;
258 : 0 : default:
259 [ # # ]: 0 : elog(ERROR, "incorrect stxkind %c found", kinds[i]);
260 : : break;
261 : : }
262 : : }
263 : 324 : }
264 : :
265 : : /*
266 : : * Perform the actual storage of a pg_statistic_ext_data tuple.
267 : : */
268 : : static void
269 : 316 : upsert_pg_statistic_ext_data(const Datum *values, const bool *nulls,
270 : : const bool *replaces)
271 : : {
272 : : Relation pg_stextdata;
273 : : HeapTuple stxdtup;
274 : : HeapTuple newtup;
275 : :
276 : 316 : pg_stextdata = table_open(StatisticExtDataRelationId, RowExclusiveLock);
277 : :
278 : 316 : stxdtup = SearchSysCache2(STATEXTDATASTXOID,
279 : : values[Anum_pg_statistic_ext_data_stxoid - 1],
280 : 316 : values[Anum_pg_statistic_ext_data_stxdinherit - 1]);
281 : :
282 [ + + ]: 316 : if (HeapTupleIsValid(stxdtup))
283 : : {
284 : 284 : newtup = heap_modify_tuple(stxdtup,
285 : : RelationGetDescr(pg_stextdata),
286 : : values,
287 : : nulls,
288 : : replaces);
289 : 284 : CatalogTupleUpdate(pg_stextdata, &newtup->t_self, newtup);
290 : 284 : ReleaseSysCache(stxdtup);
291 : : }
292 : : else
293 : : {
294 : 32 : newtup = heap_form_tuple(RelationGetDescr(pg_stextdata), values, nulls);
295 : 32 : CatalogTupleInsert(pg_stextdata, newtup);
296 : : }
297 : :
298 : 316 : heap_freetuple(newtup);
299 : :
300 : 316 : CommandCounterIncrement();
301 : :
302 : 316 : table_close(pg_stextdata, RowExclusiveLock);
303 : 316 : }
304 : :
305 : : /*
306 : : * Insert or update an extended statistics object.
307 : : *
308 : : * Major errors, such as the table not existing or permission errors, are
309 : : * reported as ERRORs. There are a couple of paths that generate a WARNING,
310 : : * like when the statistics object or its schema do not exist, a conversion
311 : : * failure on one statistic kind, or when other statistic kinds may still
312 : : * be updated.
313 : : */
314 : : static bool
315 : 368 : extended_statistics_update(FunctionCallInfo fcinfo)
316 : : {
317 : : char *relnspname;
318 : : char *relname;
319 : : Oid nspoid;
320 : : char *nspname;
321 : : char *stxname;
322 : : bool inherited;
323 : 368 : Relation pg_stext = NULL;
324 : 368 : Relation targetrel = NULL;
325 : 368 : HeapTuple tup = NULL;
326 : :
327 : 368 : StakindFlags enabled = {false, false, false, false};
328 : 368 : StakindFlags has = {false, false, false, false};
329 : :
330 : : Form_pg_statistic_ext stxform;
331 : :
332 : 368 : Datum values[Natts_pg_statistic_ext_data] = {0};
333 : 368 : bool nulls[Natts_pg_statistic_ext_data] = {0};
334 : 368 : bool replaces[Natts_pg_statistic_ext_data] = {0};
335 : 368 : bool success = true;
336 : : Datum exprdatum;
337 : : bool isnull;
338 : 368 : List *exprs = NIL;
339 : 368 : int numattnums = 0;
340 : 368 : int numexprs = 0;
341 : 368 : int numattrs = 0;
342 : :
343 : : /* arrays of type info, if we need them */
344 : 368 : Oid *atttypids = NULL;
345 : 368 : int32 *atttypmods = NULL;
346 : 368 : Oid *atttypcolls = NULL;
347 : : Oid relid;
348 : 368 : Oid locked_table = InvalidOid;
349 : :
350 : : /*
351 : : * Fill out the StakindFlags "has" structure based on which parameters
352 : : * were provided to the function.
353 : : *
354 : : * The MCV stats composite value is an array of record type, but this is
355 : : * externally represented as three arrays that must be interleaved into
356 : : * the array of records (pg_stats_ext stores four arrays,
357 : : * most_common_val_nulls is built from the contents of most_common_vals).
358 : : * Therefore, none of the three array values is meaningful unless the
359 : : * other two are also present and in sync in terms of array length.
360 : : */
361 : 791 : has.mcv = (!PG_ARGISNULL(MOST_COMMON_VALS_ARG) &&
362 [ + + + + ]: 419 : !PG_ARGISNULL(MOST_COMMON_FREQS_ARG) &&
363 [ + + ]: 51 : !PG_ARGISNULL(MOST_COMMON_BASE_FREQS_ARG));
364 : 368 : has.ndistinct = !PG_ARGISNULL(NDISTINCT_ARG);
365 : 368 : has.dependencies = !PG_ARGISNULL(DEPENDENCIES_ARG);
366 : 368 : has.expressions = !PG_ARGISNULL(EXPRESSIONS_ARG);
367 : :
368 [ - + ]: 368 : if (RecoveryInProgress())
369 : : {
370 [ # # ]: 0 : ereport(WARNING,
371 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
372 : : errmsg("recovery is in progress"),
373 : : errhint("Statistics cannot be modified during recovery."));
374 : 0 : return false;
375 : : }
376 : :
377 : : /* relation arguments */
378 : 368 : stats_check_required_arg(fcinfo, extarginfo, RELSCHEMA_ARG);
379 : 364 : relnspname = TextDatumGetCString(PG_GETARG_DATUM(RELSCHEMA_ARG));
380 : 364 : stats_check_required_arg(fcinfo, extarginfo, RELNAME_ARG);
381 : 360 : relname = TextDatumGetCString(PG_GETARG_DATUM(RELNAME_ARG));
382 : :
383 : : /* extended statistics arguments */
384 : 360 : stats_check_required_arg(fcinfo, extarginfo, STATSCHEMA_ARG);
385 : 356 : nspname = TextDatumGetCString(PG_GETARG_DATUM(STATSCHEMA_ARG));
386 : 356 : stats_check_required_arg(fcinfo, extarginfo, STATNAME_ARG);
387 : 352 : stxname = TextDatumGetCString(PG_GETARG_DATUM(STATNAME_ARG));
388 : 352 : stats_check_required_arg(fcinfo, extarginfo, INHERITED_ARG);
389 : 348 : inherited = PG_GETARG_BOOL(INHERITED_ARG);
390 : :
391 : : /*
392 : : * First open the relation where we expect to find the statistics. This
393 : : * is similar to relation and attribute statistics, so as ACL checks are
394 : : * done before any locks are taken, even before any attempts related to
395 : : * the extended stats object.
396 : : */
397 : 348 : relid = RangeVarGetRelidExtended(makeRangeVar(relnspname, relname, -1),
398 : : ShareUpdateExclusiveLock, 0,
399 : : RangeVarCallbackForStats, &locked_table);
400 : :
401 : : /*
402 : : * Parsing the MCV and expression inputs below can run user-defined code
403 : : * (such as a domain's CHECK constraint) that alters a column's type
404 : : * within our own transaction, which our lock does not prevent. Hold the
405 : : * relation open so that such a reentrant ALTER TABLE is rejected by
406 : : * CheckTableNotInUse(). NoLock is fine here as we already hold
407 : : * ShareUpdateExclusiveLock on it.
408 : : */
409 : 336 : targetrel = relation_open(relid, NoLock);
410 : :
411 : 336 : nspoid = get_namespace_oid(nspname, true);
412 [ + + ]: 336 : if (nspoid == InvalidOid)
413 : : {
414 [ + - ]: 4 : ereport(WARNING,
415 : : errcode(ERRCODE_UNDEFINED_OBJECT),
416 : : errmsg("could not find schema \"%s\"", nspname));
417 : 4 : success = false;
418 : 4 : goto cleanup;
419 : : }
420 : :
421 : 332 : pg_stext = table_open(StatisticExtRelationId, RowExclusiveLock);
422 : 332 : tup = get_pg_statistic_ext(pg_stext, nspoid, stxname);
423 : :
424 [ + + ]: 332 : if (!HeapTupleIsValid(tup))
425 : : {
426 [ + - ]: 4 : ereport(WARNING,
427 : : errcode(ERRCODE_UNDEFINED_OBJECT),
428 : : errmsg("could not find extended statistics object \"%s.%s\"",
429 : : nspname, stxname));
430 : 4 : success = false;
431 : 4 : goto cleanup;
432 : : }
433 : :
434 : 328 : stxform = (Form_pg_statistic_ext) GETSTRUCT(tup);
435 : :
436 : : /*
437 : : * The relation tracked by the stats object has to match with the relation
438 : : * we have already locked.
439 : : */
440 [ + + ]: 328 : if (stxform->stxrelid != relid)
441 : : {
442 [ + - ]: 4 : ereport(WARNING,
443 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
444 : : errmsg("could not restore extended statistics object \"%s.%s\": incorrect relation \"%s.%s\" specified",
445 : : nspname, stxname,
446 : : relnspname, relname));
447 : :
448 : 4 : success = false;
449 : 4 : goto cleanup;
450 : : }
451 : :
452 : : /* Find out what extended statistics kinds we should expect. */
453 : 324 : expand_stxkind(tup, &enabled);
454 : 324 : numattnums = stxform->stxkeys.dim1;
455 : :
456 : : /* decode expression (if any) */
457 : 324 : exprdatum = SysCacheGetAttr(STATEXTOID,
458 : : tup,
459 : : Anum_pg_statistic_ext_stxexprs,
460 : : &isnull);
461 [ + + ]: 324 : if (!isnull)
462 : : {
463 : : char *s;
464 : :
465 : 253 : s = TextDatumGetCString(exprdatum);
466 : 253 : exprs = (List *) stringToNode(s);
467 : 253 : pfree(s);
468 : :
469 : : /*
470 : : * Run the expressions through eval_const_expressions(). This is not
471 : : * just an optimization, but is necessary, because the planner will be
472 : : * comparing them to similarly-processed qual clauses, and may fail to
473 : : * detect valid matches without this.
474 : : *
475 : : * We must not use canonicalize_qual(), however, since these are not
476 : : * qual expressions.
477 : : */
478 : 253 : exprs = (List *) eval_const_expressions(NULL, (Node *) exprs);
479 : :
480 : : /* May as well fix opfuncids too */
481 : 253 : fix_opfuncids((Node *) exprs);
482 : :
483 : : /* Compute the number of expression, for input validation. */
484 : 253 : numexprs = list_length(exprs);
485 : : }
486 : :
487 : 324 : numattrs = numattnums + numexprs;
488 : :
489 : : /*
490 : : * If the object cannot support ndistinct, we should not have data for it.
491 : : */
492 [ + + + + ]: 324 : if (has.ndistinct && !enabled.ndistinct)
493 : : {
494 [ + - ]: 4 : ereport(WARNING,
495 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
496 : : errmsg("cannot specify parameter \"%s\"",
497 : : extarginfo[NDISTINCT_ARG].argname),
498 : : errhint("Extended statistics object \"%s.%s\" does not support statistics of this type.",
499 : : nspname, stxname));
500 : :
501 : 4 : has.ndistinct = false;
502 : 4 : success = false;
503 : : }
504 : :
505 : : /*
506 : : * If the object cannot support dependencies, we should not have data for
507 : : * it.
508 : : */
509 [ + + + + ]: 324 : if (has.dependencies && !enabled.dependencies)
510 : : {
511 [ + - ]: 4 : ereport(WARNING,
512 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
513 : : errmsg("cannot specify parameter \"%s\"",
514 : : extarginfo[DEPENDENCIES_ARG].argname),
515 : : errhint("Extended statistics object \"%s.%s\" does not support statistics of this type.",
516 : : nspname, stxname));
517 : 4 : has.dependencies = false;
518 : 4 : success = false;
519 : : }
520 : :
521 : : /*
522 : : * If the object cannot hold an MCV value, but any of the MCV parameters
523 : : * are set, then issue a WARNING and ensure that we do not try to load MCV
524 : : * stats later. In pg_stats_ext, most_common_val_nulls, most_common_freqs
525 : : * and most_common_base_freqs are NULL if most_common_vals is NULL.
526 : : */
527 [ + + ]: 324 : if (!enabled.mcv)
528 : : {
529 [ + + ]: 57 : if (!PG_ARGISNULL(MOST_COMMON_VALS_ARG) ||
530 [ + - ]: 53 : !PG_ARGISNULL(MOST_COMMON_FREQS_ARG) ||
531 [ - + ]: 53 : !PG_ARGISNULL(MOST_COMMON_BASE_FREQS_ARG))
532 : : {
533 [ + - ]: 4 : ereport(WARNING,
534 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
535 : : errmsg("cannot specify parameters \"%s\", \"%s\", or \"%s\"",
536 : : extarginfo[MOST_COMMON_VALS_ARG].argname,
537 : : extarginfo[MOST_COMMON_FREQS_ARG].argname,
538 : : extarginfo[MOST_COMMON_BASE_FREQS_ARG].argname),
539 : : errhint("Extended statistics object \"%s.%s\" does not support statistics of this type.",
540 : : nspname, stxname));
541 : :
542 : 4 : has.mcv = false;
543 : 4 : success = false;
544 : : }
545 : : }
546 [ + + ]: 267 : else if (!has.mcv)
547 : : {
548 : : /*
549 : : * If we do not have all of the MCV arrays set while the extended
550 : : * statistics object expects something, something is wrong. This
551 : : * issues a WARNING if a partial input has been provided.
552 : : */
553 [ + + ]: 224 : if (!PG_ARGISNULL(MOST_COMMON_VALS_ARG) ||
554 [ + + ]: 216 : !PG_ARGISNULL(MOST_COMMON_FREQS_ARG) ||
555 [ - + ]: 212 : !PG_ARGISNULL(MOST_COMMON_BASE_FREQS_ARG))
556 : : {
557 [ + - ]: 12 : ereport(WARNING,
558 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
559 : : errmsg("could not use \"%s\", \"%s\", and \"%s\": missing one or more parameters",
560 : : extarginfo[MOST_COMMON_VALS_ARG].argname,
561 : : extarginfo[MOST_COMMON_FREQS_ARG].argname,
562 : : extarginfo[MOST_COMMON_BASE_FREQS_ARG].argname));
563 : 12 : success = false;
564 : : }
565 : : }
566 : :
567 : : /*
568 : : * If the object cannot support expressions, we should not have data for
569 : : * them.
570 : : */
571 [ + + + + ]: 324 : if (has.expressions && !enabled.expressions)
572 : : {
573 [ + - ]: 4 : ereport(WARNING,
574 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
575 : : errmsg("cannot specify parameter \"%s\"",
576 : : extarginfo[EXPRESSIONS_ARG].argname),
577 : : errhint("Extended statistics object \"%s.%s\" does not support statistics of this type.",
578 : : nspname, stxname));
579 : :
580 : 4 : has.expressions = false;
581 : 4 : success = false;
582 : : }
583 : :
584 : : /*
585 : : * Either of these statistic types requires that we supply a semi-filled
586 : : * VacAttrStatsP array.
587 : : *
588 : : * It is not possible to use the existing lookup_var_attr_stats() and
589 : : * examine_attribute() because these functions will skip attributes where
590 : : * attstattarget is 0, and we may have statistics data to import for those
591 : : * attributes.
592 : : */
593 [ + + + + ]: 324 : if (has.mcv || has.expressions)
594 : : {
595 : 260 : atttypids = palloc0_array(Oid, numattrs);
596 : 260 : atttypmods = palloc0_array(int32, numattrs);
597 : 260 : atttypcolls = palloc0_array(Oid, numattrs);
598 : :
599 : : /*
600 : : * The leading stxkeys are attribute numbers up through numattnums.
601 : : * These keys must be in ascending AttrNumber order, but we do not
602 : : * rely on that.
603 : : */
604 [ + + ]: 681 : for (int i = 0; i < numattnums; i++)
605 : : {
606 : 421 : AttrNumber attnum = stxform->stxkeys.values[i];
607 : 421 : HeapTuple atup = SearchSysCache2(ATTNUM,
608 : : ObjectIdGetDatum(relid),
609 : : Int16GetDatum(attnum));
610 : :
611 : : Form_pg_attribute attr;
612 : :
613 : : /* Attribute not found */
614 [ - + ]: 421 : if (!HeapTupleIsValid(atup))
615 [ # # ]: 0 : elog(ERROR, "stxkeys references nonexistent attnum %d", attnum);
616 : :
617 : 421 : attr = (Form_pg_attribute) GETSTRUCT(atup);
618 : :
619 [ - + ]: 421 : if (attr->attisdropped)
620 [ # # ]: 0 : elog(ERROR, "stxkeys references dropped attnum %d", attnum);
621 : :
622 : 421 : atttypids[i] = attr->atttypid;
623 : 421 : atttypmods[i] = attr->atttypmod;
624 : 421 : atttypcolls[i] = attr->attcollation;
625 : 421 : ReleaseSysCache(atup);
626 : : }
627 : :
628 : : /*
629 : : * After all the positive number attnums in stxkeys come the negative
630 : : * numbers (if any) which represent expressions in the order that they
631 : : * appear in stxdexpr. Because the expressions are always
632 : : * monotonically decreasing from -1, there is no point in looking at
633 : : * the values in stxkeys, it's enough to know how many of them there
634 : : * are.
635 : : */
636 [ + + ]: 619 : for (int i = numattnums; i < numattrs; i++)
637 : : {
638 : 359 : Node *expr = list_nth(exprs, i - numattnums);
639 : :
640 : 359 : atttypids[i] = exprType(expr);
641 : 359 : atttypmods[i] = exprTypmod(expr);
642 : 359 : atttypcolls[i] = exprCollation(expr);
643 : : }
644 : : }
645 : :
646 : : /*
647 : : * Populate the pg_statistic_ext_data result tuple.
648 : : */
649 : :
650 : : /* Primary Key: cannot be NULL or replaced. */
651 : 324 : values[Anum_pg_statistic_ext_data_stxoid - 1] = ObjectIdGetDatum(stxform->oid);
652 : 324 : nulls[Anum_pg_statistic_ext_data_stxoid - 1] = false;
653 : 324 : values[Anum_pg_statistic_ext_data_stxdinherit - 1] = BoolGetDatum(inherited);
654 : 324 : nulls[Anum_pg_statistic_ext_data_stxdinherit - 1] = false;
655 : :
656 : : /* All unspecified parameters will be left unmodified */
657 : 324 : nulls[Anum_pg_statistic_ext_data_stxdndistinct - 1] = true;
658 : 324 : nulls[Anum_pg_statistic_ext_data_stxddependencies - 1] = true;
659 : 324 : nulls[Anum_pg_statistic_ext_data_stxdmcv - 1] = true;
660 : 324 : nulls[Anum_pg_statistic_ext_data_stxdexpr - 1] = true;
661 : :
662 : : /*
663 : : * For each stats kind, deserialize the data at hand and perform a round
664 : : * of validation. The resulting tuple is filled with a set of updated
665 : : * values.
666 : : */
667 : :
668 [ + + ]: 324 : if (has.ndistinct)
669 : : {
670 : 32 : Datum ndistinct_datum = PG_GETARG_DATUM(NDISTINCT_ARG);
671 : 32 : bytea *data = DatumGetByteaPP(ndistinct_datum);
672 : 32 : MVNDistinct *ndistinct = statext_ndistinct_deserialize(data);
673 : :
674 [ + + ]: 32 : if (statext_ndistinct_validate(ndistinct, &stxform->stxkeys,
675 : : numexprs, WARNING))
676 : : {
677 : 24 : values[Anum_pg_statistic_ext_data_stxdndistinct - 1] = ndistinct_datum;
678 : 24 : nulls[Anum_pg_statistic_ext_data_stxdndistinct - 1] = false;
679 : 24 : replaces[Anum_pg_statistic_ext_data_stxdndistinct - 1] = true;
680 : : }
681 : : else
682 : 8 : success = false;
683 : :
684 : 32 : statext_ndistinct_free(ndistinct);
685 : : }
686 : :
687 [ + + ]: 324 : if (has.dependencies)
688 : : {
689 : 29 : Datum dependencies_datum = PG_GETARG_DATUM(DEPENDENCIES_ARG);
690 : 29 : bytea *data = DatumGetByteaPP(dependencies_datum);
691 : 29 : MVDependencies *dependencies = statext_dependencies_deserialize(data);
692 : :
693 [ + + ]: 29 : if (statext_dependencies_validate(dependencies, &stxform->stxkeys,
694 : : numexprs, WARNING))
695 : : {
696 : 21 : values[Anum_pg_statistic_ext_data_stxddependencies - 1] = dependencies_datum;
697 : 21 : nulls[Anum_pg_statistic_ext_data_stxddependencies - 1] = false;
698 : 21 : replaces[Anum_pg_statistic_ext_data_stxddependencies - 1] = true;
699 : : }
700 : : else
701 : 8 : success = false;
702 : :
703 : 29 : statext_dependencies_free(dependencies);
704 : : }
705 : :
706 [ + + ]: 324 : if (has.mcv)
707 : : {
708 : : Datum datum;
709 : 43 : bool val_ok = false;
710 : :
711 : 43 : datum = import_mcv(PG_GETARG_ARRAYTYPE_P(MOST_COMMON_VALS_ARG),
712 : 43 : PG_GETARG_ARRAYTYPE_P(MOST_COMMON_FREQS_ARG),
713 : 43 : PG_GETARG_ARRAYTYPE_P(MOST_COMMON_BASE_FREQS_ARG),
714 : : atttypids, atttypmods, atttypcolls, numattrs,
715 : : &val_ok);
716 : :
717 [ + + ]: 43 : if (val_ok)
718 : : {
719 : : Assert(datum != (Datum) 0);
720 : 23 : values[Anum_pg_statistic_ext_data_stxdmcv - 1] = datum;
721 : 23 : nulls[Anum_pg_statistic_ext_data_stxdmcv - 1] = false;
722 : 23 : replaces[Anum_pg_statistic_ext_data_stxdmcv - 1] = true;
723 : : }
724 : : else
725 : 20 : success = false;
726 : : }
727 : :
728 [ + + ]: 324 : if (has.expressions)
729 : : {
730 : : Datum datum;
731 : : Relation pgsd;
732 : 229 : bool ok = false;
733 : :
734 : 229 : pgsd = table_open(StatisticRelationId, RowExclusiveLock);
735 : :
736 : : /*
737 : : * Generate the expressions array.
738 : : *
739 : : * The atttypids, atttypmods, and atttypcolls arrays have all the
740 : : * regular attributes listed first, so we can pass those arrays with a
741 : : * start point after the last regular attribute. There are numexprs
742 : : * elements remaining.
743 : : */
744 : 229 : datum = import_expressions(pgsd, numexprs,
745 : 229 : &atttypids[numattnums],
746 : 229 : &atttypmods[numattnums],
747 : 229 : &atttypcolls[numattnums],
748 : : PG_GETARG_JSONB_P(EXPRESSIONS_ARG),
749 : : &ok);
750 : :
751 : 225 : table_close(pgsd, RowExclusiveLock);
752 : :
753 [ + + ]: 225 : if (ok)
754 : : {
755 : : Assert(datum != (Datum) 0);
756 : 65 : values[Anum_pg_statistic_ext_data_stxdexpr - 1] = datum;
757 : 65 : replaces[Anum_pg_statistic_ext_data_stxdexpr - 1] = true;
758 : 65 : nulls[Anum_pg_statistic_ext_data_stxdexpr - 1] = false;
759 : : }
760 : : else
761 : 160 : success = false;
762 : : }
763 : :
764 : : /*
765 : : * The user-defined code run while parsing the inputs above can also drop
766 : : * the statistics object itself, which holding the relation open does not
767 : : * prevent. The object must not go away in the middle of restoring its
768 : : * statistics, so error out, which also rolls back the drop.
769 : : */
770 [ + + ]: 320 : if (!SearchSysCacheExists1(STATEXTOID, ObjectIdGetDatum(stxform->oid)))
771 [ + - ]: 4 : ereport(ERROR,
772 : : errcode(ERRCODE_UNDEFINED_OBJECT),
773 : : errmsg("could not restore extended statistics object \"%s.%s\": it was dropped during the import",
774 : : nspname, stxname));
775 : :
776 : 316 : upsert_pg_statistic_ext_data(values, nulls, replaces);
777 : :
778 : 328 : cleanup:
779 : 328 : relation_close(targetrel, NoLock);
780 [ + + ]: 328 : if (HeapTupleIsValid(tup))
781 : 320 : heap_freetuple(tup);
782 [ + + ]: 328 : if (pg_stext != NULL)
783 : 324 : table_close(pg_stext, RowExclusiveLock);
784 [ + + ]: 328 : if (atttypids != NULL)
785 : 252 : pfree(atttypids);
786 [ + + ]: 328 : if (atttypmods != NULL)
787 : 252 : pfree(atttypmods);
788 [ + + ]: 328 : if (atttypcolls != NULL)
789 : 252 : pfree(atttypcolls);
790 : 328 : return success;
791 : : }
792 : :
793 : : /*
794 : : * Consistency checks to ensure that other mcvlist arrays are in alignment
795 : : * with the mcv array.
796 : : */
797 : : static bool
798 : 58 : check_mcvlist_array(const ArrayType *arr, int argindex, int required_ndims,
799 : : int mcv_length)
800 : : {
801 [ - + ]: 58 : if (ARR_NDIM(arr) != required_ndims)
802 : : {
803 [ # # ]: 0 : ereport(WARNING,
804 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
805 : : errmsg("could not parse array \"%s\": incorrect number of dimensions (%d required)",
806 : : extarginfo[argindex].argname, required_ndims));
807 : 0 : return false;
808 : : }
809 : :
810 [ - + ]: 58 : if (array_contains_nulls(arr))
811 : : {
812 [ # # ]: 0 : ereport(WARNING,
813 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
814 : : errmsg("could not parse array \"%s\": NULL value found",
815 : : extarginfo[argindex].argname));
816 : 0 : return false;
817 : : }
818 : :
819 [ + + ]: 58 : if (ARR_DIMS(arr)[0] != mcv_length)
820 : : {
821 [ + - ]: 8 : ereport(WARNING,
822 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
823 : : errmsg("could not parse array \"%s\": incorrect number of elements (same as \"%s\" required)",
824 : : extarginfo[argindex].argname,
825 : : extarginfo[MOST_COMMON_VALS_ARG].argname));
826 : 8 : return false;
827 : : }
828 : :
829 : 50 : return true;
830 : : }
831 : :
832 : : /*
833 : : * Create the stxdmcv datum from the equal-sized arrays of most common values,
834 : : * their null flags, and the frequency and base frequency associated with
835 : : * each value.
836 : : */
837 : : static Datum
838 : 43 : import_mcv(const ArrayType *mcv_arr, const ArrayType *freqs_arr,
839 : : const ArrayType *base_freqs_arr, Oid *atttypids, int32 *atttypmods,
840 : : Oid *atttypcolls, int numattrs, bool *ok)
841 : : {
842 : : int nitems;
843 : : Datum *mcv_elems;
844 : : bool *mcv_nulls;
845 : : int check_nummcv;
846 : 43 : Datum mcv = (Datum) 0;
847 : :
848 : 43 : *ok = false;
849 : :
850 : : /*
851 : : * mcv_arr is an array of arrays. Each inner array must have the same
852 : : * number of elements "numattrs".
853 : : */
854 [ + + ]: 43 : if (ARR_NDIM(mcv_arr) != 2)
855 : : {
856 [ + - ]: 4 : ereport(WARNING,
857 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
858 : : errmsg("could not parse array \"%s\": incorrect number of dimensions (%d required)",
859 : : extarginfo[MOST_COMMON_VALS_ARG].argname, 2));
860 : 4 : goto mcv_error;
861 : : }
862 : :
863 [ + + ]: 39 : if (ARR_DIMS(mcv_arr)[1] != numattrs)
864 : : {
865 [ + - ]: 4 : ereport(WARNING,
866 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
867 : : errmsg("could not parse array \"%s\": found %d attributes but expected %d",
868 : : extarginfo[MOST_COMMON_VALS_ARG].argname,
869 : : ARR_DIMS(mcv_arr)[1], numattrs));
870 : 4 : goto mcv_error;
871 : : }
872 : :
873 : : /*
874 : : * "most_common_freqs" and "most_common_base_freqs" arrays must be of the
875 : : * same length, one-dimension and cannot contain NULLs. We use mcv_arr as
876 : : * the reference array for determining their length.
877 : : */
878 : 35 : nitems = ARR_DIMS(mcv_arr)[0];
879 : :
880 : : /*
881 : : * Reject a MCV list larger than what statext_mcv_deserialize() is able to
882 : : * accept.
883 : : */
884 [ + + ]: 35 : if (nitems > STATS_MCVLIST_MAX_ITEMS)
885 : : {
886 [ + - ]: 4 : ereport(WARNING,
887 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
888 : : errmsg("could not parse array \"%s\": number of items (%d) exceeds maximum (%d)",
889 : : extarginfo[MOST_COMMON_VALS_ARG].argname,
890 : : nitems, STATS_MCVLIST_MAX_ITEMS));
891 : 4 : goto mcv_error;
892 : : }
893 : :
894 [ + + ]: 31 : if (!check_mcvlist_array(freqs_arr, MOST_COMMON_FREQS_ARG, 1, nitems) ||
895 [ + + ]: 27 : !check_mcvlist_array(base_freqs_arr, MOST_COMMON_BASE_FREQS_ARG, 1, nitems))
896 : : {
897 : : /* inconsistent input arrays found */
898 : 8 : goto mcv_error;
899 : : }
900 : :
901 : : /*
902 : : * This part builds the contents for "most_common_val_nulls", based on the
903 : : * values from "most_common_vals".
904 : : */
905 : 23 : deconstruct_array_builtin(mcv_arr, TEXTOID, &mcv_elems,
906 : : &mcv_nulls, &check_nummcv);
907 : :
908 : 23 : mcv = statext_mcv_import(WARNING, numattrs,
909 : : atttypids, atttypmods, atttypcolls,
910 : : nitems, mcv_elems, mcv_nulls,
911 [ - + ]: 23 : (float8 *) ARR_DATA_PTR(freqs_arr),
912 [ - + ]: 23 : (float8 *) ARR_DATA_PTR(base_freqs_arr));
913 : :
914 : 23 : *ok = (mcv != (Datum) 0);
915 : :
916 : 43 : mcv_error:
917 : 43 : return mcv;
918 : : }
919 : :
920 : : /*
921 : : * Check if key is found in the list of expression argnames.
922 : : */
923 : : static bool
924 : 814 : key_in_expr_argnames(JsonbValue *key)
925 : : {
926 : : Assert(key->type == jbvString);
927 [ + + ]: 5310 : for (int i = 0; i < NUM_ATTRIBUTE_STATS_ELEMS; i++)
928 : : {
929 [ + + ]: 5298 : if (strlen(extexprargname[i]) == key->val.string.len &&
930 [ + + ]: 1217 : strncmp(extexprargname[i], key->val.string.val, key->val.string.len) == 0)
931 : 802 : return true;
932 : : }
933 : 12 : return false;
934 : : }
935 : :
936 : : /*
937 : : * Verify that all of the keys in the object are valid argnames.
938 : : */
939 : : static bool
940 : 283 : check_all_expr_argnames_valid(JsonbContainer *cont, AttrNumber exprnum)
941 : : {
942 : 283 : bool all_keys_valid = true;
943 : :
944 : : JsonbIterator *jbit;
945 : : JsonbIteratorToken jitok;
946 : : JsonbValue jkey;
947 : :
948 : : Assert(JsonContainerIsObject(cont));
949 : :
950 : 283 : jbit = JsonbIteratorInit(cont);
951 : :
952 : : /* We always start off with a BEGIN OBJECT */
953 : 283 : jitok = JsonbIteratorNext(&jbit, &jkey, false);
954 : : Assert(jitok == WJB_BEGIN_OBJECT);
955 : :
956 : : while (true)
957 : 850 : {
958 : : JsonbValue jval;
959 : :
960 : 1133 : jitok = JsonbIteratorNext(&jbit, &jkey, false);
961 : :
962 : : /*
963 : : * We have run of keys. This is the only condition where it is
964 : : * memory-safe to break out of the loop.
965 : : */
966 [ + + ]: 1133 : if (jitok == WJB_END_OBJECT)
967 : 283 : break;
968 : :
969 : : /* We can only find keys inside an object */
970 : : Assert(jitok == WJB_KEY);
971 : : Assert(jkey.type == jbvString);
972 : :
973 : : /* A value must follow the key. Skip nested containers. */
974 : 850 : jitok = JsonbIteratorNext(&jbit, &jval, true);
975 : : Assert(jitok == WJB_VALUE);
976 : :
977 : : /*
978 : : * If we have already found an invalid key, there is no point in
979 : : * looking for more, because additional WARNINGs are just clutter. We
980 : : * must continue iterating over the json to ensure that we clean up
981 : : * all allocated memory.
982 : : */
983 [ + + ]: 850 : if (!all_keys_valid)
984 : 36 : continue;
985 : :
986 [ + + ]: 814 : if (!key_in_expr_argnames(&jkey))
987 : : {
988 [ + - ]: 12 : ereport(WARNING,
989 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
990 : : errmsg("could not import element in expression %d: invalid key name",
991 : : exprnum));
992 : 12 : all_keys_valid = false;
993 : : }
994 : : }
995 : 283 : return all_keys_valid;
996 : : }
997 : :
998 : : /*
999 : : * Simple conversion of jbvString to cstring
1000 : : */
1001 : : static char *
1002 : 586 : jbv_string_get_cstr(JsonbValue *jval)
1003 : : {
1004 : : char *s;
1005 : :
1006 : : Assert(jval->type == jbvString);
1007 : :
1008 : 586 : s = palloc0(jval->val.string.len + 1);
1009 : 586 : memcpy(s, jval->val.string.val, jval->val.string.len);
1010 : :
1011 : 586 : return s;
1012 : : }
1013 : :
1014 : : /*
1015 : : * Apply a jbvString value to a safe scalar input function.
1016 : : */
1017 : : static bool
1018 : 252 : jbv_to_infunc_datum(JsonbValue *jval, PGFunction func, AttrNumber exprnum,
1019 : : const char *argname, Datum *datum)
1020 : : {
1021 : 252 : ErrorSaveContext escontext = {
1022 : : .type = T_ErrorSaveContext,
1023 : : .details_wanted = true
1024 : : };
1025 : :
1026 : 252 : char *s = jbv_string_get_cstr(jval);
1027 : : bool ok;
1028 : :
1029 : 252 : ok = DirectInputFunctionCallSafe(func, s, InvalidOid, -1,
1030 : : (Node *) &escontext, datum);
1031 : :
1032 : : /*
1033 : : * If we got a type import error, use the report generated and add an
1034 : : * error hint before throwing a warning.
1035 : : */
1036 [ + + ]: 252 : if (!ok)
1037 : : {
1038 : : StringInfoData hint_str;
1039 : :
1040 : 16 : initStringInfo(&hint_str);
1041 : 16 : appendStringInfo(&hint_str,
1042 : : "Element \"%s\" in expression %d could not be parsed.",
1043 : : argname, exprnum);
1044 : :
1045 : 16 : escontext.error_data->elevel = WARNING;
1046 : 16 : escontext.error_data->hint = hint_str.data;
1047 : :
1048 : 16 : ThrowErrorData(escontext.error_data);
1049 : 16 : pfree(hint_str.data);
1050 : : }
1051 : :
1052 : 252 : pfree(s);
1053 : 252 : return ok;
1054 : : }
1055 : :
1056 : : /*
1057 : : * Build an array datum with element type typid from a text datum, used as
1058 : : * value of an attribute in a pg_statistic tuple.
1059 : : *
1060 : : * If an error is encountered, capture it, and reduce the elevel to WARNING.
1061 : : *
1062 : : * The array must be one-dimensional. If "allow_empty" is true, an empty
1063 : : * array is also accepted.
1064 : : *
1065 : : * This is an adaptation of statatt_build_stavalues().
1066 : : */
1067 : : static Datum
1068 : 334 : array_in_safe(FmgrInfo *array_in, const char *s, Oid typid, int32 typmod,
1069 : : AttrNumber exprnum, const char *element_name, bool allow_empty,
1070 : : bool *ok)
1071 : : {
1072 : : Datum result;
1073 : : int ndim;
1074 : :
1075 : 334 : ErrorSaveContext escontext = {
1076 : : .type = T_ErrorSaveContext,
1077 : : .details_wanted = true
1078 : : };
1079 : :
1080 : 334 : *ok = false;
1081 : :
1082 : : /*
1083 : : * If the array_in function returned an error, we will want to report that
1084 : : * ERROR as a WARNING, and add some location context to the error message.
1085 : : * Overwriting the existing hint (if any) is not ideal, and an error
1086 : : * context would only work for level >= ERROR.
1087 : : */
1088 [ + + ]: 334 : if (!InputFunctionCallSafe(array_in, s, typid, typmod,
1089 : : (Node *) &escontext, &result))
1090 : : {
1091 : : StringInfoData hint_str;
1092 : :
1093 : 28 : initStringInfo(&hint_str);
1094 : 28 : appendStringInfo(&hint_str,
1095 : : "Element \"%s\" in expression %d could not be parsed.",
1096 : : element_name, exprnum);
1097 : 28 : escontext.error_data->elevel = WARNING;
1098 : 28 : escontext.error_data->hint = hint_str.data;
1099 : 28 : ThrowErrorData(escontext.error_data);
1100 : 28 : pfree(hint_str.data);
1101 : 28 : return (Datum) 0;
1102 : : }
1103 : :
1104 : 302 : ndim = ARR_NDIM(DatumGetArrayTypeP(result));
1105 [ + + + + : 302 : if (ndim != 1 && !(allow_empty && ndim == 0))
- + ]
1106 : : {
1107 [ - + ]: 16 : if (allow_empty)
1108 [ # # ]: 0 : ereport(WARNING,
1109 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1110 : : errmsg("could not import element \"%s\" in expression %d: must be an empty or one-dimensional array",
1111 : : element_name, exprnum)));
1112 : : else
1113 [ + - ]: 16 : ereport(WARNING,
1114 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1115 : : errmsg("could not import element \"%s\" in expression %d: must be a one-dimensional array",
1116 : : element_name, exprnum)));
1117 : 16 : return (Datum) 0;
1118 : : }
1119 : :
1120 [ - + ]: 286 : if (array_contains_nulls(DatumGetArrayTypeP(result)))
1121 : : {
1122 [ # # ]: 0 : ereport(WARNING,
1123 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1124 : : errmsg("could not import element \"%s\" in expression %d: null value found",
1125 : : element_name, exprnum));
1126 : 0 : return (Datum) 0;
1127 : : }
1128 : :
1129 : 286 : *ok = true;
1130 : 286 : return result;
1131 : : }
1132 : :
1133 : : /*
1134 : : * Create a pg_statistic tuple from an expression JSONB container.
1135 : : *
1136 : : * The pg_statistic tuple is pre-populated with acceptable defaults, therefore
1137 : : * even if there is an issue with all of the keys in the container, we can
1138 : : * still return a legit tuple datum.
1139 : : *
1140 : : * Set pg_statistic_ok to true if all of the values found in the container
1141 : : * were imported without issue. pg_statistic_ok is switched to "true" once
1142 : : * the full pg_statistic tuple has been built and validated.
1143 : : */
1144 : : static Datum
1145 : 291 : import_pg_statistic(Relation pgsd, JsonbContainer *cont,
1146 : : AttrNumber exprnum, FmgrInfo *array_in_fn,
1147 : : Oid typid, int32 typmod, Oid typcoll,
1148 : : bool *pg_statistic_ok)
1149 : : {
1150 : 291 : const char *argname = extarginfo[EXPRESSIONS_ARG].argname;
1151 : : TypeCacheEntry *basetypcache;
1152 : : Datum values[Natts_pg_statistic];
1153 : : bool nulls[Natts_pg_statistic];
1154 : : bool replaces[Natts_pg_statistic];
1155 : 291 : HeapTuple pgstup = NULL;
1156 : 291 : Datum pgstdat = (Datum) 0;
1157 : 291 : Oid elemtypid = InvalidOid;
1158 : 291 : Oid elemeqopr = InvalidOid;
1159 : 291 : Oid rtypid = InvalidOid;
1160 : 291 : bool found[NUM_ATTRIBUTE_STATS_ELEMS] = {0};
1161 : 291 : JsonbValue val[NUM_ATTRIBUTE_STATS_ELEMS] = {0};
1162 : :
1163 : : /* Assume the worst by default. */
1164 : 291 : *pg_statistic_ok = false;
1165 : :
1166 [ + + ]: 291 : if (!JsonContainerIsObject(cont))
1167 : : {
1168 [ + - ]: 4 : ereport(WARNING,
1169 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1170 : : errmsg("could not parse \"%s\": invalid element in expression %d",
1171 : : argname, exprnum));
1172 : 4 : goto pg_statistic_error;
1173 : : }
1174 : :
1175 : : /*
1176 : : * Loop through all keys that we need to look up. If any value found is
1177 : : * neither a string nor a NULL, there is not much we can do, so just give
1178 : : * on the entire tuple for this expression.
1179 : : */
1180 [ + + ]: 3966 : for (int i = 0; i < NUM_ATTRIBUTE_STATS_ELEMS; i++)
1181 : : {
1182 : 3683 : const char *s = extexprargname[i];
1183 : 3683 : int len = strlen(s);
1184 : :
1185 [ + + ]: 3683 : if (getKeyJsonValueFromContainer(cont, s, len, &val[i]) == NULL)
1186 : 2841 : continue;
1187 : :
1188 [ + + + ]: 842 : switch (val[i].type)
1189 : : {
1190 : 718 : case jbvString:
1191 : 718 : found[i] = true;
1192 : 718 : break;
1193 : :
1194 : 120 : case jbvNull:
1195 : 120 : break;
1196 : :
1197 : 4 : default:
1198 [ + - ]: 4 : ereport(WARNING,
1199 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1200 : : errmsg("could not parse \"%s\": invalid element in expression %d", argname, exprnum),
1201 : : errhint("Value of element \"%s\" must be a null or a string.", s));
1202 : 4 : goto pg_statistic_error;
1203 : : }
1204 : : }
1205 : :
1206 : : /* Look for invalid keys */
1207 [ + + ]: 283 : if (!check_all_expr_argnames_valid(cont, exprnum))
1208 : 12 : goto pg_statistic_error;
1209 : :
1210 : : /*
1211 : : * There are three arg pairs, MCV+MCF, MCEV+MCEF, and RLH+REF. Both
1212 : : * values must either be found or not be found. Any disagreement is a
1213 : : * warning. Once we have ruled out disagreeing pairs, we can use either
1214 : : * found flag as a proxy for the other.
1215 : : */
1216 [ + + ]: 271 : if (found[MOST_COMMON_VALS_ELEM] != found[MOST_COMMON_FREQS_ELEM])
1217 : : {
1218 [ + - ]: 16 : ereport(WARNING,
1219 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1220 : : errmsg("could not parse \"%s\": invalid element in expression %d",
1221 : : argname, exprnum),
1222 : : errhint("\"%s\" and \"%s\" must be both either strings or nulls.",
1223 : : extexprargname[MOST_COMMON_VALS_ELEM],
1224 : : extexprargname[MOST_COMMON_FREQS_ELEM]));
1225 : 16 : goto pg_statistic_error;
1226 : : }
1227 [ + + ]: 255 : if (found[MOST_COMMON_ELEMS_ELEM] != found[MOST_COMMON_ELEM_FREQS_ELEM])
1228 : : {
1229 [ + - ]: 16 : ereport(WARNING,
1230 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1231 : : errmsg("could not parse \"%s\": invalid element in expression %d",
1232 : : argname, exprnum),
1233 : : errhint("\"%s\" and \"%s\" must be both either strings or nulls.",
1234 : : extexprargname[MOST_COMMON_ELEMS_ELEM],
1235 : : extexprargname[MOST_COMMON_ELEM_FREQS_ELEM]));
1236 : 16 : goto pg_statistic_error;
1237 : : }
1238 : :
1239 [ + + ]: 239 : if (found[RANGE_LENGTH_HISTOGRAM_ELEM] != found[RANGE_EMPTY_FRAC_ELEM])
1240 : : {
1241 [ + - ]: 8 : ereport(WARNING,
1242 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1243 : : errmsg("could not parse \"%s\": invalid element in expression %d",
1244 : : argname, exprnum),
1245 : : errhint("\"%s\" and \"%s\" must be both either strings or nulls.",
1246 : : extexprargname[RANGE_LENGTH_HISTOGRAM_ELEM],
1247 : : extexprargname[RANGE_EMPTY_FRAC_ELEM]));
1248 : 8 : goto pg_statistic_error;
1249 : : }
1250 : :
1251 : : /* This finds the right operators even if atttypid is a domain */
1252 : 231 : basetypcache = lookup_type_cache(typid, TYPECACHE_LT_OPR |
1253 : : TYPECACHE_EQ_OPR |
1254 : : TYPECACHE_DOMAIN_BASE_INFO);
1255 [ + + ]: 231 : if (OidIsValid(basetypcache->domainBaseType))
1256 : 28 : basetypcache = lookup_type_cache(basetypcache->domainBaseType,
1257 : : TYPECACHE_LT_OPR |
1258 : : TYPECACHE_EQ_OPR);
1259 : :
1260 : 231 : statatt_init_empty_tuple(InvalidOid, InvalidAttrNumber, false,
1261 : : values, nulls, replaces);
1262 : :
1263 : : /*
1264 : : * Special case: collation for tsvector is DEFAULT_COLLATION_OID. See
1265 : : * compute_tsvector_stats().
1266 : : */
1267 [ + + ]: 231 : if (basetypcache->type_id == TSVECTOROID)
1268 : 8 : typcoll = DEFAULT_COLLATION_OID;
1269 : :
1270 : : /*
1271 : : * We only need to fetch element type and eq operator if we have a stat of
1272 : : * type MCELEM or DECHIST, otherwise the values are unnecessary and not
1273 : : * meaningful.
1274 : : */
1275 [ + + + + ]: 231 : if (found[MOST_COMMON_ELEMS_ELEM] || found[ELEM_COUNT_HISTOGRAM_ELEM])
1276 : : {
1277 [ + + ]: 40 : if (!statatt_get_elem_type(basetypcache, &elemtypid, &elemeqopr))
1278 : : {
1279 [ + - ]: 8 : ereport(WARNING,
1280 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1281 : : errmsg("could not parse \"%s\": invalid element type in expression %d",
1282 : : argname, exprnum));
1283 : 8 : goto pg_statistic_error;
1284 : : }
1285 : : }
1286 : :
1287 : : /*
1288 : : * These three fields can only be set if dealing with a range or
1289 : : * multi-range type.
1290 : : */
1291 [ + + ]: 223 : if (found[RANGE_LENGTH_HISTOGRAM_ELEM] ||
1292 [ + - ]: 179 : found[RANGE_EMPTY_FRAC_ELEM] ||
1293 [ + + ]: 179 : found[RANGE_BOUNDS_HISTOGRAM_ELEM])
1294 : : {
1295 [ + + ]: 52 : if (!statatt_get_range_type(basetypcache, &rtypid))
1296 : : {
1297 [ + - ]: 4 : ereport(WARNING,
1298 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1299 : : errmsg("could not parse \"%s\": invalid data in expression %d",
1300 : : argname, exprnum),
1301 : : errhint("\"%s\", \"%s\", and \"%s\" can only be set for a range type.",
1302 : : extexprargname[RANGE_LENGTH_HISTOGRAM_ELEM],
1303 : : extexprargname[RANGE_EMPTY_FRAC_ELEM],
1304 : : extexprargname[RANGE_BOUNDS_HISTOGRAM_ELEM]));
1305 : 4 : goto pg_statistic_error;
1306 : : }
1307 : : }
1308 : :
1309 : : /* null_frac */
1310 [ + + ]: 219 : if (found[NULL_FRAC_ELEM])
1311 : : {
1312 : : Datum datum;
1313 : :
1314 [ + + ]: 63 : if (jbv_to_infunc_datum(&val[NULL_FRAC_ELEM], float4in, exprnum,
1315 : : extexprargname[NULL_FRAC_ELEM], &datum))
1316 : 59 : values[Anum_pg_statistic_stanullfrac - 1] = datum;
1317 : : else
1318 : 4 : goto pg_statistic_error;
1319 : : }
1320 : :
1321 : : /* avg_width */
1322 [ + + ]: 215 : if (found[AVG_WIDTH_ELEM])
1323 : : {
1324 : : Datum datum;
1325 : :
1326 [ + + ]: 59 : if (jbv_to_infunc_datum(&val[AVG_WIDTH_ELEM], int4in, exprnum,
1327 : : extexprargname[AVG_WIDTH_ELEM], &datum))
1328 : 55 : values[Anum_pg_statistic_stawidth - 1] = datum;
1329 : : else
1330 : 4 : goto pg_statistic_error;
1331 : : }
1332 : :
1333 : : /* n_distinct */
1334 [ + + ]: 211 : if (found[N_DISTINCT_ELEM])
1335 : : {
1336 : : Datum datum;
1337 : :
1338 [ + + ]: 59 : if (jbv_to_infunc_datum(&val[N_DISTINCT_ELEM], float4in, exprnum,
1339 : : extexprargname[N_DISTINCT_ELEM], &datum))
1340 : 55 : values[Anum_pg_statistic_stadistinct - 1] = datum;
1341 : : else
1342 : 4 : goto pg_statistic_error;
1343 : : }
1344 : :
1345 : : /*
1346 : : * The STAKIND statistics are the same as the ones found in attribute
1347 : : * stats. However, these are all derived from json strings, whereas the
1348 : : * ones derived for attribute stats are a mix of datatypes. This limits
1349 : : * the opportunities for code sharing between the two.
1350 : : *
1351 : : * Some statistic kinds have both a stanumbers and a stavalues components.
1352 : : * In those cases, both values must either be NOT NULL or both NULL, and
1353 : : * if they aren't then we need to reject that stakind completely.
1354 : : * Currently we go a step further and reject the expression array
1355 : : * completely.
1356 : : */
1357 : :
1358 [ + + ]: 207 : if (found[MOST_COMMON_VALS_ELEM])
1359 : : {
1360 : : Datum stavalues;
1361 : : Datum stanumbers;
1362 : 91 : bool val_ok = false;
1363 : 91 : bool num_ok = false;
1364 : : char *s;
1365 : :
1366 : 91 : s = jbv_string_get_cstr(&val[MOST_COMMON_VALS_ELEM]);
1367 : 91 : stavalues = array_in_safe(array_in_fn, s, typid, typmod, exprnum,
1368 : : extexprargname[MOST_COMMON_VALS_ELEM],
1369 : : false, &val_ok);
1370 : :
1371 : 87 : pfree(s);
1372 : :
1373 : 87 : s = jbv_string_get_cstr(&val[MOST_COMMON_FREQS_ELEM]);
1374 : 87 : stanumbers = array_in_safe(array_in_fn, s, FLOAT4OID, -1, exprnum,
1375 : : extexprargname[MOST_COMMON_FREQS_ELEM],
1376 : : false, &num_ok);
1377 : 87 : pfree(s);
1378 : :
1379 : : /* Only set the slot if both datums have been built */
1380 [ + + + + ]: 87 : if (val_ok && num_ok)
1381 : 67 : {
1382 : 71 : ArrayType *vals_arr = DatumGetArrayTypeP(stavalues);
1383 : 71 : ArrayType *nums_arr = DatumGetArrayTypeP(stanumbers);
1384 : 71 : int nvals = ARR_DIMS(vals_arr)[0];
1385 : 71 : int nnums = ARR_DIMS(nums_arr)[0];
1386 : :
1387 [ + + ]: 71 : if (nvals != nnums)
1388 : : {
1389 [ + - ]: 4 : ereport(WARNING,
1390 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1391 : : errmsg("could not parse \"%s\": incorrect number of elements (same as \"%s\" required)",
1392 : : "most_common_vals",
1393 : : "most_common_freqs")));
1394 : 20 : goto pg_statistic_error;
1395 : : }
1396 : :
1397 : 67 : statatt_set_slot(values, nulls, replaces,
1398 : : STATISTIC_KIND_MCV,
1399 : : basetypcache->eq_opr, typcoll,
1400 : : stanumbers, false, stavalues, false);
1401 : : }
1402 : : else
1403 : 16 : goto pg_statistic_error;
1404 : : }
1405 : :
1406 : : /* STATISTIC_KIND_HISTOGRAM */
1407 [ + + ]: 183 : if (found[HISTOGRAM_BOUNDS_ELEM])
1408 : : {
1409 : : Datum stavalues;
1410 : 20 : bool val_ok = false;
1411 : 20 : char *s = jbv_string_get_cstr(&val[HISTOGRAM_BOUNDS_ELEM]);
1412 : :
1413 : 20 : stavalues = array_in_safe(array_in_fn, s, typid, typmod, exprnum,
1414 : : extexprargname[HISTOGRAM_BOUNDS_ELEM],
1415 : : false, &val_ok);
1416 : 20 : pfree(s);
1417 : :
1418 [ + + ]: 20 : if (val_ok)
1419 : 16 : statatt_set_slot(values, nulls, replaces,
1420 : : STATISTIC_KIND_HISTOGRAM,
1421 : : basetypcache->lt_opr, typcoll,
1422 : : 0, true, stavalues, false);
1423 : : else
1424 : 4 : goto pg_statistic_error;
1425 : : }
1426 : :
1427 : : /* STATISTIC_KIND_CORRELATION */
1428 [ + + ]: 179 : if (found[CORRELATION_ELEM])
1429 : : {
1430 : 43 : Datum corr[] = {(Datum) 0};
1431 : :
1432 [ + + ]: 43 : if (jbv_to_infunc_datum(&val[CORRELATION_ELEM], float4in, exprnum,
1433 : : extexprargname[CORRELATION_ELEM], &corr[0]))
1434 : : {
1435 : 39 : ArrayType *arry = construct_array_builtin(corr, 1, FLOAT4OID);
1436 : 39 : Datum stanumbers = PointerGetDatum(arry);
1437 : :
1438 : 39 : statatt_set_slot(values, nulls, replaces,
1439 : : STATISTIC_KIND_CORRELATION,
1440 : : basetypcache->lt_opr, typcoll,
1441 : : stanumbers, false, 0, true);
1442 : : }
1443 : : else
1444 : 4 : goto pg_statistic_error;
1445 : : }
1446 : :
1447 : : /* STATISTIC_KIND_MCELEM */
1448 [ + + ]: 175 : if (found[MOST_COMMON_ELEMS_ELEM])
1449 : : {
1450 : : Datum stavalues;
1451 : : Datum stanumbers;
1452 : 28 : bool val_ok = false;
1453 : 28 : bool num_ok = false;
1454 : : char *s;
1455 : :
1456 : 28 : s = jbv_string_get_cstr(&val[MOST_COMMON_ELEMS_ELEM]);
1457 : 28 : stavalues = array_in_safe(array_in_fn, s, elemtypid, typmod, exprnum,
1458 : : extexprargname[MOST_COMMON_ELEMS_ELEM],
1459 : : true, &val_ok);
1460 : 28 : pfree(s);
1461 : :
1462 : :
1463 : 28 : s = jbv_string_get_cstr(&val[MOST_COMMON_ELEM_FREQS_ELEM]);
1464 : 28 : stanumbers = array_in_safe(array_in_fn, s, FLOAT4OID, -1, exprnum,
1465 : : extexprargname[MOST_COMMON_ELEM_FREQS_ELEM],
1466 : : false, &num_ok);
1467 : 28 : pfree(s);
1468 : :
1469 : : /* Only set the slot if both datums have been built */
1470 [ + + + + ]: 28 : if (val_ok && num_ok)
1471 : 16 : statatt_set_slot(values, nulls, replaces,
1472 : : STATISTIC_KIND_MCELEM,
1473 : : elemeqopr, typcoll,
1474 : : stanumbers, false, stavalues, false);
1475 : : else
1476 : 12 : goto pg_statistic_error;
1477 : : }
1478 : :
1479 : : /* STATISTIC_KIND_DECHIST */
1480 [ + + ]: 163 : if (found[ELEM_COUNT_HISTOGRAM_ELEM])
1481 : : {
1482 : : Datum stanumbers;
1483 : 12 : bool num_ok = false;
1484 : : char *s;
1485 : :
1486 : 12 : s = jbv_string_get_cstr(&val[ELEM_COUNT_HISTOGRAM_ELEM]);
1487 : 12 : stanumbers = array_in_safe(array_in_fn, s, FLOAT4OID, -1, exprnum,
1488 : : extexprargname[ELEM_COUNT_HISTOGRAM_ELEM],
1489 : : false, &num_ok);
1490 : 12 : pfree(s);
1491 : :
1492 [ + + ]: 12 : if (num_ok)
1493 : 8 : statatt_set_slot(values, nulls, replaces, STATISTIC_KIND_DECHIST,
1494 : : elemeqopr, typcoll, stanumbers, false, 0, true);
1495 : : else
1496 : 4 : goto pg_statistic_error;
1497 : : }
1498 : :
1499 : : /*
1500 : : * STATISTIC_KIND_BOUNDS_HISTOGRAM
1501 : : *
1502 : : * This stakind appears before STATISTIC_KIND_RANGE_LENGTH_HISTOGRAM even
1503 : : * though it is numerically greater, and all other stakinds appear in
1504 : : * numerical order.
1505 : : */
1506 [ + + ]: 159 : if (found[RANGE_BOUNDS_HISTOGRAM_ELEM])
1507 : : {
1508 : : Datum stavalues;
1509 : 40 : bool val_ok = false;
1510 : : char *s;
1511 : :
1512 : : Assert(OidIsValid(rtypid));
1513 : :
1514 : 40 : s = jbv_string_get_cstr(&val[RANGE_BOUNDS_HISTOGRAM_ELEM]);
1515 : :
1516 : 40 : stavalues = array_in_safe(array_in_fn, s, rtypid, typmod, exprnum,
1517 : : extexprargname[RANGE_BOUNDS_HISTOGRAM_ELEM],
1518 : : false, &val_ok);
1519 : :
1520 [ + + + + ]: 40 : if (val_ok && statatt_check_bounds_histogram(stavalues))
1521 : 24 : statatt_set_slot(values, nulls, replaces,
1522 : : STATISTIC_KIND_BOUNDS_HISTOGRAM,
1523 : : InvalidOid, InvalidOid,
1524 : : 0, true, stavalues, false);
1525 : : else
1526 : 16 : goto pg_statistic_error;
1527 : : }
1528 : :
1529 : : /* STATISTIC_KIND_RANGE_LENGTH_HISTOGRAM */
1530 [ + + ]: 143 : if (found[RANGE_LENGTH_HISTOGRAM_ELEM])
1531 : : {
1532 : 28 : Datum empty_frac[] = {(Datum) 0};
1533 : : Datum stavalues;
1534 : : Datum stanumbers;
1535 : 28 : bool val_ok = false;
1536 : : char *s;
1537 : :
1538 [ + - ]: 28 : if (jbv_to_infunc_datum(&val[RANGE_EMPTY_FRAC_ELEM], float4in, exprnum,
1539 : : extexprargname[RANGE_EMPTY_FRAC_ELEM], &empty_frac[0]))
1540 : : {
1541 : 28 : ArrayType *arry = construct_array_builtin(empty_frac, 1, FLOAT4OID);
1542 : :
1543 : 28 : stanumbers = PointerGetDatum(arry);
1544 : : }
1545 : : else
1546 : 0 : goto pg_statistic_error;
1547 : :
1548 : 28 : s = jbv_string_get_cstr(&val[RANGE_LENGTH_HISTOGRAM_ELEM]);
1549 : 28 : stavalues = array_in_safe(array_in_fn, s, FLOAT8OID, -1, exprnum,
1550 : : extexprargname[RANGE_LENGTH_HISTOGRAM_ELEM],
1551 : : true, &val_ok);
1552 : :
1553 [ + - ]: 28 : if (val_ok)
1554 : 28 : statatt_set_slot(values, nulls, replaces,
1555 : : STATISTIC_KIND_RANGE_LENGTH_HISTOGRAM,
1556 : : Float8LessOperator, InvalidOid,
1557 : : stanumbers, false, stavalues, false);
1558 : : else
1559 : 0 : goto pg_statistic_error;
1560 : : }
1561 : :
1562 : 143 : pgstup = heap_form_tuple(RelationGetDescr(pgsd), values, nulls);
1563 : 143 : pgstdat = heap_copy_tuple_as_datum(pgstup, RelationGetDescr(pgsd));
1564 : :
1565 : 143 : heap_freetuple(pgstup);
1566 : :
1567 : 143 : *pg_statistic_ok = true;
1568 : :
1569 : 143 : return pgstdat;
1570 : :
1571 : 144 : pg_statistic_error:
1572 : 144 : return (Datum) 0;
1573 : : }
1574 : :
1575 : : /*
1576 : : * Create the stxdexpr datum, which is an array of pg_statistic rows with all
1577 : : * of the object identification fields left at defaults, using the json array
1578 : : * of objects/nulls referenced against the datatypes for the expressions.
1579 : : *
1580 : : * The exprs_is_perfect will be set to true if all pg_statistic rows were
1581 : : * imported cleanly. If any of them experienced a problem (and thus were
1582 : : * set as if they were null), then the expression is kept but exprs_is_perfect
1583 : : * will be marked as false.
1584 : : *
1585 : : * This datum is needed to fill out a complete pg_statistic_ext_data tuple.
1586 : : */
1587 : : static Datum
1588 : 229 : import_expressions(Relation pgsd, int numexprs,
1589 : : Oid *atttypids, int32 *atttypmods,
1590 : : Oid *atttypcolls, Jsonb *exprs_jsonb,
1591 : : bool *exprs_is_perfect)
1592 : : {
1593 : 229 : const char *argname = extarginfo[EXPRESSIONS_ARG].argname;
1594 : 229 : Oid pgstypoid = get_rel_type_id(StatisticRelationId);
1595 : 229 : ArrayBuildState *astate = NULL;
1596 : 229 : Datum result = (Datum) 0;
1597 : 229 : int num_import_ok = 0;
1598 : : JsonbContainer *root;
1599 : : int num_root_elements;
1600 : :
1601 : : FmgrInfo array_in_fn;
1602 : :
1603 : 229 : *exprs_is_perfect = false;
1604 : :
1605 : : /* Json schema must be [{expr},...] */
1606 [ + + ]: 229 : if (!JB_ROOT_IS_ARRAY(exprs_jsonb))
1607 : : {
1608 [ + - ]: 4 : ereport(WARNING,
1609 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1610 : : errmsg("could not parse \"%s\": root-level array required", argname));
1611 : 4 : goto exprs_error;
1612 : : }
1613 : :
1614 : 225 : root = &exprs_jsonb->root;
1615 : :
1616 : : /*
1617 : : * The number of elements in the array must match the number of
1618 : : * expressions in the stats object definition.
1619 : : */
1620 : 225 : num_root_elements = JsonContainerSize(root);
1621 [ + + ]: 225 : if (numexprs != num_root_elements)
1622 : : {
1623 [ + - ]: 8 : ereport(WARNING,
1624 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1625 : : errmsg("could not parse \"%s\": incorrect number of elements (%d required)",
1626 : : argname, numexprs));
1627 : 8 : goto exprs_error;
1628 : : }
1629 : :
1630 : 217 : fmgr_info(F_ARRAY_IN, &array_in_fn);
1631 : :
1632 : : /*
1633 : : * Iterate over each expected expression object in the array. Some of
1634 : : * them could be null. If the element is a completely wrong data type,
1635 : : * give a WARNING and then treat the element like a NULL element in the
1636 : : * result array.
1637 : : *
1638 : : * Each expression *MUST* have a value appended in the result pg_statistic
1639 : : * array.
1640 : : */
1641 [ + + ]: 532 : for (int i = 0; i < numexprs; i++)
1642 : : {
1643 : 323 : Datum pgstdat = (Datum) 0;
1644 : 323 : bool isnull = false;
1645 : 323 : AttrNumber exprattnum = -1 - i;
1646 : :
1647 : 323 : JsonbValue *elem = getIthJsonbValueFromContainer(root, i);
1648 : :
1649 [ + + + ]: 323 : switch (elem->type)
1650 : : {
1651 : 291 : case jbvBinary:
1652 : : {
1653 : 291 : bool sta_ok = false;
1654 : :
1655 : : /* a real stats object */
1656 : 291 : pgstdat = import_pg_statistic(pgsd, elem->val.binary.data,
1657 : : exprattnum, &array_in_fn,
1658 : 291 : atttypids[i], atttypmods[i],
1659 : 291 : atttypcolls[i], &sta_ok);
1660 : :
1661 : : /*
1662 : : * If some incorrect data has been found, assign NULL for
1663 : : * this expression as a mean to give up.
1664 : : */
1665 [ + + ]: 287 : if (sta_ok)
1666 : 143 : num_import_ok++;
1667 : : else
1668 : : {
1669 : 144 : isnull = true;
1670 : 144 : pgstdat = (Datum) 0;
1671 : : }
1672 : : }
1673 : 287 : break;
1674 : :
1675 : 28 : case jbvNull:
1676 : : /* NULL placeholder for invalid data, still fine */
1677 : 28 : isnull = true;
1678 : 28 : num_import_ok++;
1679 : 28 : break;
1680 : :
1681 : 4 : default:
1682 : : /* cannot possibly be valid */
1683 [ + - ]: 4 : ereport(WARNING,
1684 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1685 : : errmsg("could not parse \"%s\": invalid element in expression %d",
1686 : : argname, exprattnum));
1687 : 4 : goto exprs_error;
1688 : : }
1689 : :
1690 : 315 : astate = accumArrayResult(astate, pgstdat, isnull, pgstypoid,
1691 : : CurrentMemoryContext);
1692 : : }
1693 : :
1694 : : /*
1695 : : * The expressions datum is perfect *if and only if* all of the
1696 : : * pg_statistic elements were also ok, for a number of elements equal to
1697 : : * the number of expressions. Anything else means a failure in restoring
1698 : : * the data of this statistics object.
1699 : : */
1700 : 209 : *exprs_is_perfect = (num_import_ok == numexprs);
1701 : :
1702 [ + - ]: 209 : if (astate != NULL)
1703 : 209 : result = makeArrayResult(astate, CurrentMemoryContext);
1704 : :
1705 : 209 : return result;
1706 : :
1707 : 16 : exprs_error:
1708 [ - + ]: 16 : if (astate != NULL)
1709 : 0 : pfree(astate);
1710 : 16 : return (Datum) 0;
1711 : : };
1712 : :
1713 : : /*
1714 : : * Remove an existing pg_statistic_ext_data row for a given pg_statistic_ext
1715 : : * row and "inherited" pair.
1716 : : */
1717 : : static bool
1718 : 12 : delete_pg_statistic_ext_data(Oid stxoid, bool inherited)
1719 : : {
1720 : 12 : Relation sed = table_open(StatisticExtDataRelationId, RowExclusiveLock);
1721 : : HeapTuple oldtup;
1722 : 12 : bool result = false;
1723 : :
1724 : : /* Is there already a pg_statistic_ext_data tuple for this attribute? */
1725 : 12 : oldtup = SearchSysCache2(STATEXTDATASTXOID,
1726 : : ObjectIdGetDatum(stxoid),
1727 : : BoolGetDatum(inherited));
1728 : :
1729 [ + + ]: 12 : if (HeapTupleIsValid(oldtup))
1730 : : {
1731 : 8 : CatalogTupleDelete(sed, &oldtup->t_self);
1732 : 8 : ReleaseSysCache(oldtup);
1733 : 8 : result = true;
1734 : : }
1735 : :
1736 : 12 : table_close(sed, RowExclusiveLock);
1737 : :
1738 : 12 : CommandCounterIncrement();
1739 : :
1740 : 12 : return result;
1741 : : }
1742 : :
1743 : : /*
1744 : : * Restore (insert or replace) statistics for the given statistics object.
1745 : : *
1746 : : * This function accepts variadic arguments in key-value pairs, which are
1747 : : * given to stats_fill_fcinfo_from_arg_pairs to be mapped into positional
1748 : : * arguments.
1749 : : */
1750 : : Datum
1751 : 368 : pg_restore_extended_stats(PG_FUNCTION_ARGS)
1752 : : {
1753 : 368 : LOCAL_FCINFO(positional_fcinfo, NUM_EXTENDED_STATS_ARGS);
1754 : 368 : bool result = true;
1755 : :
1756 : 368 : InitFunctionCallInfoData(*positional_fcinfo, NULL, NUM_EXTENDED_STATS_ARGS,
1757 : : InvalidOid, NULL, NULL);
1758 : :
1759 [ - + ]: 368 : if (!stats_fill_fcinfo_from_arg_pairs(fcinfo, positional_fcinfo, extarginfo))
1760 : 0 : result = false;
1761 : :
1762 [ + + ]: 368 : if (!extended_statistics_update(positional_fcinfo))
1763 : 236 : result = false;
1764 : :
1765 : 328 : PG_RETURN_BOOL(result);
1766 : : }
1767 : :
1768 : : /*
1769 : : * Delete statistics for the given statistics object.
1770 : : */
1771 : : Datum
1772 : 56 : pg_clear_extended_stats(PG_FUNCTION_ARGS)
1773 : : {
1774 : : char *relnspname;
1775 : : char *relname;
1776 : : char *nspname;
1777 : : Oid nspoid;
1778 : : Oid relid;
1779 : : char *stxname;
1780 : : bool inherited;
1781 : : Relation pg_stext;
1782 : : HeapTuple tup;
1783 : : Form_pg_statistic_ext stxform;
1784 : 56 : Oid locked_table = InvalidOid;
1785 : :
1786 : : /* relation arguments */
1787 : 56 : stats_check_required_arg(fcinfo, extarginfo, RELSCHEMA_ARG);
1788 : 52 : relnspname = TextDatumGetCString(PG_GETARG_DATUM(RELSCHEMA_ARG));
1789 : 52 : stats_check_required_arg(fcinfo, extarginfo, RELNAME_ARG);
1790 : 48 : relname = TextDatumGetCString(PG_GETARG_DATUM(RELNAME_ARG));
1791 : :
1792 : : /* extended statistics arguments */
1793 : 48 : stats_check_required_arg(fcinfo, extarginfo, STATSCHEMA_ARG);
1794 : 44 : nspname = TextDatumGetCString(PG_GETARG_DATUM(STATSCHEMA_ARG));
1795 : 44 : stats_check_required_arg(fcinfo, extarginfo, STATNAME_ARG);
1796 : 40 : stxname = TextDatumGetCString(PG_GETARG_DATUM(STATNAME_ARG));
1797 : 40 : stats_check_required_arg(fcinfo, extarginfo, INHERITED_ARG);
1798 : 36 : inherited = PG_GETARG_BOOL(INHERITED_ARG);
1799 : :
1800 [ - + ]: 36 : if (RecoveryInProgress())
1801 : : {
1802 [ # # ]: 0 : ereport(WARNING,
1803 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1804 : : errmsg("recovery is in progress"),
1805 : : errhint("Statistics cannot be modified during recovery."));
1806 : 0 : PG_RETURN_VOID();
1807 : : }
1808 : :
1809 : : /*
1810 : : * First open the relation where we expect to find the statistics. This
1811 : : * is similar to relation and attribute statistics, so as ACL checks are
1812 : : * done before any locks are taken, even before any attempts related to
1813 : : * the extended stats object.
1814 : : */
1815 : 36 : relid = RangeVarGetRelidExtended(makeRangeVar(relnspname, relname, -1),
1816 : : ShareUpdateExclusiveLock, 0,
1817 : : RangeVarCallbackForStats, &locked_table);
1818 : :
1819 : : /* Now check if the namespace of the stats object exists. */
1820 : 24 : nspoid = get_namespace_oid(nspname, true);
1821 [ + + ]: 24 : if (nspoid == InvalidOid)
1822 : : {
1823 [ + - ]: 4 : ereport(WARNING,
1824 : : errcode(ERRCODE_UNDEFINED_OBJECT),
1825 : : errmsg("could not find schema \"%s\"", nspname));
1826 : 4 : PG_RETURN_VOID();
1827 : : }
1828 : :
1829 : 20 : pg_stext = table_open(StatisticExtRelationId, RowExclusiveLock);
1830 : 20 : tup = get_pg_statistic_ext(pg_stext, nspoid, stxname);
1831 : :
1832 [ + + ]: 20 : if (!HeapTupleIsValid(tup))
1833 : : {
1834 : 4 : table_close(pg_stext, RowExclusiveLock);
1835 [ + - ]: 4 : ereport(WARNING,
1836 : : errcode(ERRCODE_UNDEFINED_OBJECT),
1837 : : errmsg("could not find extended statistics object \"%s.%s\"",
1838 : : nspname, stxname));
1839 : 4 : PG_RETURN_VOID();
1840 : : }
1841 : :
1842 : 16 : stxform = (Form_pg_statistic_ext) GETSTRUCT(tup);
1843 : :
1844 : : /*
1845 : : * This should be consistent, based on the lock taken on the table when we
1846 : : * started.
1847 : : */
1848 [ + + ]: 16 : if (stxform->stxrelid != relid)
1849 : : {
1850 : 4 : heap_freetuple(tup);
1851 : 4 : table_close(pg_stext, RowExclusiveLock);
1852 [ + - ]: 4 : ereport(WARNING,
1853 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1854 : : errmsg("could not clear extended statistics object \"%s.%s\": incorrect relation \"%s.%s\" specified",
1855 : : get_namespace_name(nspoid), stxname,
1856 : : relnspname, relname));
1857 : 4 : PG_RETURN_VOID();
1858 : : }
1859 : :
1860 : 12 : delete_pg_statistic_ext_data(stxform->oid, inherited);
1861 : 12 : heap_freetuple(tup);
1862 : :
1863 : 12 : table_close(pg_stext, RowExclusiveLock);
1864 : :
1865 : 12 : PG_RETURN_VOID();
1866 : : }
|