Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : * stat_utils.c
3 : : *
4 : : * PostgreSQL statistics manipulation utilities.
5 : : *
6 : : * Code supporting the direct manipulation of statistics.
7 : : *
8 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
9 : : * Portions Copyright (c) 1994, Regents of the University of California
10 : : *
11 : : * IDENTIFICATION
12 : : * src/backend/statistics/stat_utils.c
13 : : *
14 : : *-------------------------------------------------------------------------
15 : : */
16 : :
17 : : #include "postgres.h"
18 : :
19 : : #include "access/htup_details.h"
20 : : #include "access/relation.h"
21 : : #include "catalog/index.h"
22 : : #include "catalog/namespace.h"
23 : : #include "catalog/pg_class.h"
24 : : #include "catalog/pg_collation.h"
25 : : #include "catalog/pg_database.h"
26 : : #include "catalog/pg_statistic.h"
27 : : #include "funcapi.h"
28 : : #include "miscadmin.h"
29 : : #include "nodes/nodeFuncs.h"
30 : : #include "statistics/stat_utils.h"
31 : : #include "storage/lmgr.h"
32 : : #include "utils/acl.h"
33 : : #include "utils/array.h"
34 : : #include "utils/builtins.h"
35 : : #include "utils/lsyscache.h"
36 : : #include "utils/rangetypes.h"
37 : : #include "utils/rel.h"
38 : : #include "utils/syscache.h"
39 : : #include "utils/typcache.h"
40 : :
41 : : /* Default values assigned to new pg_statistic tuples. */
42 : : #define DEFAULT_STATATT_NULL_FRAC Float4GetDatum(0.0) /* stanullfrac */
43 : : #define DEFAULT_STATATT_AVG_WIDTH Int32GetDatum(0) /* stawidth, same as
44 : : * unknown */
45 : : #define DEFAULT_STATATT_N_DISTINCT Float4GetDatum(0.0) /* stadistinct, same as
46 : : * unknown */
47 : :
48 : : static Node *statatt_get_index_expr(Relation rel, int attnum);
49 : :
50 : : /*
51 : : * Ensure that a given argument is not null.
52 : : */
53 : : void
54 : 7108 : stats_check_required_arg(const NullableDatum *args,
55 : : struct StatsArgInfo *arginfo,
56 : : int argnum)
57 : : {
58 [ + + ]: 7108 : if (args[argnum].isnull)
59 [ + - ]: 88 : ereport(ERROR,
60 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
61 : : errmsg("argument \"%s\" must not be null",
62 : : arginfo[argnum].argname)));
63 : 7020 : }
64 : :
65 : : /*
66 : : * Check that argument is either NULL or a one dimensional array with no
67 : : * NULLs.
68 : : *
69 : : * If a problem is found, emit a WARNING, and return false. Otherwise return
70 : : * true.
71 : : */
72 : : bool
73 : 2559 : stats_check_arg_array(const NullableDatum *arg, const char *argname)
74 : : {
75 : : ArrayType *arr;
76 : :
77 [ + + ]: 2559 : if (arg->isnull)
78 : 2094 : return true;
79 : :
80 : 465 : arr = DatumGetArrayTypeP(arg->value);
81 : :
82 [ - + ]: 465 : if (ARR_NDIM(arr) != 1)
83 : : {
84 [ # # ]: 0 : ereport(WARNING,
85 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
86 : : errmsg("argument \"%s\" must not be a multidimensional array",
87 : : argname)));
88 : 0 : return false;
89 : : }
90 : :
91 [ + + ]: 465 : if (array_contains_nulls(arr))
92 : : {
93 [ + - ]: 4 : ereport(WARNING,
94 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
95 : : errmsg("argument \"%s\" array must not contain null values",
96 : : argname)));
97 : 4 : return false;
98 : : }
99 : :
100 : 461 : return true;
101 : : }
102 : :
103 : : /*
104 : : * Enforce parameter pairs that must be specified together (or not at all) for
105 : : * a particular stakind, such as most_common_vals and most_common_freqs for
106 : : * STATISTIC_KIND_MCV.
107 : : *
108 : : * If a problem is found, emit a WARNING, and return false. Otherwise return
109 : : * true.
110 : : */
111 : : bool
112 : 2559 : stats_check_arg_pair(const NullableDatum *arg1, const NullableDatum *arg2,
113 : : const char *argname1, const char *argname2)
114 : : {
115 [ + + + + ]: 2559 : if (arg1->isnull && arg2->isnull)
116 : 2077 : return true;
117 : :
118 [ + + + + ]: 482 : if (arg1->isnull || arg2->isnull)
119 : : {
120 [ + + ]: 28 : const char *nullarg = arg1->isnull ? argname1 : argname2;
121 [ + + ]: 28 : const char *otherarg = arg1->isnull ? argname2 : argname1;
122 : :
123 [ + - ]: 28 : ereport(WARNING,
124 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
125 : : errmsg("argument \"%s\" must be specified when argument \"%s\" is specified",
126 : : nullarg, otherarg)));
127 : :
128 : 28 : return false;
129 : : }
130 : :
131 : 454 : return true;
132 : : }
133 : :
134 : : /*
135 : : * A role has privileges to set statistics on the relation if any of the
136 : : * following are true:
137 : : * - the role owns the current database and the relation is not shared
138 : : * - the role has the MAINTAIN privilege on the relation
139 : : */
140 : : void
141 : 2473 : RangeVarCallbackForStats(const RangeVar *relation,
142 : : Oid relId, Oid oldRelId, void *arg)
143 : : {
144 : 2473 : Oid *locked_oid = (Oid *) arg;
145 : 2473 : Oid table_oid = relId;
146 : : HeapTuple tuple;
147 : : Form_pg_class form;
148 : : char relkind;
149 : :
150 : : /*
151 : : * If we previously locked some other index's heap, and the name we're
152 : : * looking up no longer refers to that relation, release the now-useless
153 : : * lock.
154 : : */
155 [ + + - + ]: 2473 : if (relId != oldRelId && OidIsValid(*locked_oid))
156 : : {
157 : 0 : UnlockRelationOid(*locked_oid, ShareUpdateExclusiveLock);
158 : 0 : *locked_oid = InvalidOid;
159 : : }
160 : :
161 : : /* If the relation does not exist, there's nothing more to do. */
162 [ + + ]: 2473 : if (!OidIsValid(relId))
163 : 21 : return;
164 : :
165 : : /* If the relation does exist, check whether it's an index. */
166 : 2452 : relkind = get_rel_relkind(relId);
167 [ + + + + ]: 2452 : if (relkind == RELKIND_INDEX ||
168 : : relkind == RELKIND_PARTITIONED_INDEX)
169 : 341 : table_oid = IndexGetRelation(relId, false);
170 : :
171 : : /*
172 : : * If retrying yields the same OID, there are a couple of extremely
173 : : * unlikely scenarios we need to handle.
174 : : */
175 [ + + ]: 2452 : if (relId == oldRelId)
176 : : {
177 : : /*
178 : : * If a previous lookup found an index, but the current lookup did
179 : : * not, the index was dropped and the OID was reused for something
180 : : * else between lookups. In theory, we could simply drop our lock on
181 : : * the index's parent table and proceed, but in the interest of
182 : : * avoiding complexity, we just error.
183 : : */
184 [ + + - + ]: 5 : if (table_oid == relId && OidIsValid(*locked_oid))
185 [ # # ]: 0 : ereport(ERROR,
186 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
187 : : errmsg("index \"%s\" was concurrently dropped",
188 : : relation->relname)));
189 : :
190 : : /*
191 : : * If the current lookup found an index but a previous lookup either
192 : : * did not find an index or found one with a different parent
193 : : * relation, the relation was dropped and the OID was reused for an
194 : : * index between lookups. RangeVarGetRelidExtended() will have
195 : : * already locked the index at this point, so we can't just lock the
196 : : * newly discovered parent table OID without risking deadlock. As
197 : : * above, we just error in this case.
198 : : */
199 [ + + - + ]: 5 : if (table_oid != relId && table_oid != *locked_oid)
200 [ # # ]: 0 : ereport(ERROR,
201 : : (errcode(ERRCODE_UNDEFINED_OBJECT),
202 : : errmsg("index \"%s\" was concurrently created",
203 : : relation->relname)));
204 : : }
205 : :
206 : 2452 : tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(table_oid));
207 [ - + ]: 2452 : if (!HeapTupleIsValid(tuple))
208 [ # # ]: 0 : elog(ERROR, "cache lookup failed for OID %u", table_oid);
209 : 2452 : form = (Form_pg_class) GETSTRUCT(tuple);
210 : :
211 : : /* the relkinds that can be used with ANALYZE */
212 [ + + ]: 2452 : switch (form->relkind)
213 : : {
214 : 2432 : case RELKIND_RELATION:
215 : : case RELKIND_MATVIEW:
216 : : case RELKIND_FOREIGN_TABLE:
217 : : case RELKIND_PARTITIONED_TABLE:
218 : 2432 : break;
219 : 20 : default:
220 [ + - ]: 20 : ereport(ERROR,
221 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
222 : : errmsg("cannot modify statistics for relation \"%s\"",
223 : : NameStr(form->relname)),
224 : : errdetail_relkind_not_supported(form->relkind)));
225 : : }
226 : :
227 [ - + ]: 2432 : if (form->relisshared)
228 [ # # ]: 0 : ereport(ERROR,
229 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
230 : : errmsg("cannot modify statistics for shared relation")));
231 : :
232 : : /* Check permissions */
233 [ + + ]: 2432 : if (!object_ownercheck(DatabaseRelationId, MyDatabaseId, GetUserId()))
234 : : {
235 : 16 : AclResult aclresult = pg_class_aclcheck(table_oid,
236 : : GetUserId(),
237 : : ACL_MAINTAIN);
238 : :
239 [ + + ]: 16 : if (aclresult != ACLCHECK_OK)
240 : 8 : aclcheck_error(aclresult,
241 : 8 : get_relkind_objtype(form->relkind),
242 : 8 : NameStr(form->relname));
243 : : }
244 : :
245 : 2424 : ReleaseSysCache(tuple);
246 : :
247 : : /* Lock heap before index to avoid deadlock. */
248 [ + + + + ]: 2424 : if (relId != oldRelId && table_oid != relId)
249 : : {
250 : 339 : LockRelationOid(table_oid, ShareUpdateExclusiveLock);
251 : 339 : *locked_oid = table_oid;
252 : : }
253 : : }
254 : :
255 : :
256 : : /*
257 : : * Find the argument number for the given argument name, returning -1 if not
258 : : * found.
259 : : */
260 : : static int
261 : 17021 : get_arg_by_name(const char *argname, struct StatsArgInfo *arginfo)
262 : : {
263 : : int argnum;
264 : :
265 [ + + ]: 81589 : for (argnum = 0; arginfo[argnum].argname != NULL; argnum++)
266 [ + + ]: 81581 : if (pg_strcasecmp(argname, arginfo[argnum].argname) == 0)
267 : 17013 : return argnum;
268 : :
269 [ + - ]: 8 : ereport(WARNING,
270 : : (errmsg("unrecognized argument name: \"%s\"", argname)));
271 : :
272 : 8 : return -1;
273 : : }
274 : :
275 : : /*
276 : : * Ensure that a given argument matched the expected type.
277 : : */
278 : : static bool
279 : 17013 : stats_check_arg_type(const char *argname, Oid argtype, Oid expectedtype)
280 : : {
281 [ + + ]: 17013 : if (argtype != expectedtype)
282 : : {
283 [ + - ]: 16 : ereport(WARNING,
284 : : (errmsg("argument \"%s\" has type %s, expected type %s",
285 : : argname, format_type_be(argtype),
286 : : format_type_be(expectedtype))));
287 : 16 : return false;
288 : : }
289 : :
290 : 16997 : return true;
291 : : }
292 : :
293 : : /*
294 : : * Check if attribute of an index is an expression, then retrieve the
295 : : * expression if is it the case.
296 : : *
297 : : * If the attnum specified is known to be an expression, then we must
298 : : * walk the list attributes up to the specified attnum to get the right
299 : : * expression.
300 : : */
301 : : static Node *
302 : 853 : statatt_get_index_expr(Relation rel, int attnum)
303 : : {
304 : : List *index_exprs;
305 : : ListCell *indexpr_item;
306 : :
307 : : /* relation is not an index */
308 [ + + ]: 853 : if (rel->rd_rel->relkind != RELKIND_INDEX &&
309 [ + - ]: 843 : rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX)
310 : 843 : return NULL;
311 : :
312 : 10 : index_exprs = RelationGetIndexExpressions(rel);
313 : :
314 : : /* index has no expressions to give */
315 [ - + ]: 10 : if (index_exprs == NIL)
316 : 0 : return NULL;
317 : :
318 : : /*
319 : : * The index's attnum points directly to a relation attnum, hence it is
320 : : * not an expression attribute.
321 : : */
322 [ - + ]: 10 : if (rel->rd_index->indkey.values[attnum - 1] != 0)
323 : 0 : return NULL;
324 : :
325 : 10 : indexpr_item = list_head(rel->rd_indexprs);
326 : :
327 [ - + ]: 10 : for (int i = 0; i < attnum - 1; i++)
328 [ # # ]: 0 : if (rel->rd_index->indkey.values[i] == 0)
329 : 0 : indexpr_item = lnext(rel->rd_indexprs, indexpr_item);
330 : :
331 [ - + ]: 10 : if (indexpr_item == NULL) /* shouldn't happen */
332 [ # # ]: 0 : elog(ERROR, "too few entries in indexprs list");
333 : :
334 : 10 : return (Node *) lfirst(indexpr_item);
335 : : }
336 : :
337 : : /*
338 : : * Translate variadic argument pairs from 'pairs_fcinfo' into a
339 : : * NullableDatum[] appropriate for calling the internal statistics update
340 : : * functions for relation stats, attribute stats, or extended stats.
341 : : *
342 : : * Caller should have already initialized args with a size appropriate for
343 : : * calling the intended function, and arginfo should also match the intended
344 : : * function.
345 : : */
346 : : bool
347 : 2451 : stats_fill_args_from_arg_pairs(FunctionCallInfo pairs_fcinfo,
348 : : NullableDatum *positional_args,
349 : : struct StatsArgInfo *arginfo)
350 : : {
351 : : Datum *args;
352 : : bool *argnulls;
353 : : Oid *types;
354 : : int nargs;
355 : 2451 : bool result = true;
356 : :
357 : : /* clear positional args */
358 [ + + ]: 29409 : for (int i = 0; arginfo[i].argname != NULL; i++)
359 : : {
360 : 26958 : positional_args[i].value = (Datum) 0;
361 : 26958 : positional_args[i].isnull = true;
362 : : }
363 : :
364 : 2451 : nargs = extract_variadic_args(pairs_fcinfo, 0, true,
365 : : &args, &types, &argnulls);
366 : :
367 [ + + ]: 2451 : if (nargs % 2 != 0)
368 [ + - ]: 4 : ereport(ERROR,
369 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
370 : : errmsg("variadic arguments must be name/value pairs"),
371 : : errhint("Provide an even number of variadic arguments that can be divided into pairs.")));
372 : :
373 : : /*
374 : : * For each argument name/value pair, find corresponding positional
375 : : * argument for the argument name, and assign the argument value to
376 : : * positional_fcinfo.
377 : : */
378 [ + + ]: 21535 : for (int i = 0; i < nargs; i += 2)
379 : : {
380 : : int argnum;
381 : : char *argname;
382 : :
383 [ + + ]: 19092 : if (argnulls[i])
384 [ + - ]: 4 : ereport(ERROR,
385 : : (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
386 : : errmsg("name at variadic position %d is null", i + 1)));
387 : :
388 [ - + ]: 19088 : if (types[i] != TEXTOID)
389 [ # # ]: 0 : ereport(ERROR,
390 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
391 : : errmsg("name at variadic position %d has type %s, expected type %s",
392 : : i + 1, format_type_be(types[i]),
393 : : format_type_be(TEXTOID))));
394 : :
395 [ + + ]: 19088 : if (argnulls[i + 1])
396 : 204 : continue;
397 : :
398 : 18884 : argname = TextDatumGetCString(args[i]);
399 : :
400 : : /*
401 : : * The 'version' argument is a special case, not handled by arginfo
402 : : * because it's not a valid positional argument.
403 : : *
404 : : * For now, 'version' is accepted but ignored. In the future it can be
405 : : * used to interpret older statistics properly.
406 : : */
407 [ + + ]: 18884 : if (pg_strcasecmp(argname, "version") == 0)
408 : 1863 : continue;
409 : :
410 : 17021 : argnum = get_arg_by_name(argname, arginfo);
411 : :
412 [ + + + + ]: 34034 : if (argnum < 0 || !stats_check_arg_type(argname, types[i + 1],
413 : 17013 : arginfo[argnum].argtype))
414 : : {
415 : 24 : result = false;
416 : 24 : continue;
417 : : }
418 : :
419 : 16997 : positional_args[argnum].value = args[i + 1];
420 : 16997 : positional_args[argnum].isnull = false;
421 : : }
422 : :
423 : 2443 : return result;
424 : : }
425 : :
426 : : /*
427 : : * Derive type information from a relation attribute.
428 : : *
429 : : * This is needed for setting most slot statistics for all data types.
430 : : *
431 : : * This duplicates the logic in examine_attribute() but it will not skip the
432 : : * attribute if the attstattarget is 0.
433 : : *
434 : : * This information, retrieved from pg_attribute and pg_type with some
435 : : * specific handling for index expressions, is a prerequisite to calling
436 : : * any of the other statatt_*() functions.
437 : : */
438 : : void
439 : 853 : statatt_get_type(Oid reloid, AttrNumber attnum,
440 : : Oid *atttypid, int32 *atttypmod,
441 : : char *atttyptype, Oid *atttypcoll,
442 : : Oid *eq_opr, Oid *lt_opr)
443 : : {
444 : 853 : Relation rel = relation_open(reloid, AccessShareLock);
445 : : Form_pg_attribute attr;
446 : : HeapTuple atup;
447 : : Node *expr;
448 : : TypeCacheEntry *typcache;
449 : :
450 : 853 : atup = SearchSysCache2(ATTNUM, ObjectIdGetDatum(reloid),
451 : : Int16GetDatum(attnum));
452 : :
453 : : /* Attribute not found */
454 [ - + ]: 853 : if (!HeapTupleIsValid(atup))
455 [ # # ]: 0 : ereport(ERROR,
456 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
457 : : errmsg("column %d of relation \"%s\" does not exist",
458 : : attnum, RelationGetRelationName(rel))));
459 : :
460 : 853 : attr = (Form_pg_attribute) GETSTRUCT(atup);
461 : :
462 [ - + ]: 853 : if (attr->attisdropped)
463 [ # # ]: 0 : ereport(ERROR,
464 : : (errcode(ERRCODE_UNDEFINED_COLUMN),
465 : : errmsg("column %d of relation \"%s\" does not exist",
466 : : attnum, RelationGetRelationName(rel))));
467 : :
468 : 853 : expr = statatt_get_index_expr(rel, attr->attnum);
469 : :
470 : : /*
471 : : * When analyzing an expression index, believe the expression tree's type
472 : : * not the column datatype --- the latter might be the opckeytype storage
473 : : * type of the opclass, which is not interesting for our purposes. This
474 : : * mimics the behavior of examine_attribute().
475 : : */
476 [ + + ]: 853 : if (expr == NULL)
477 : : {
478 : 843 : *atttypid = attr->atttypid;
479 : 843 : *atttypmod = attr->atttypmod;
480 : 843 : *atttypcoll = attr->attcollation;
481 : : }
482 : : else
483 : : {
484 : 10 : *atttypid = exprType(expr);
485 : 10 : *atttypmod = exprTypmod(expr);
486 : :
487 [ - + ]: 10 : if (OidIsValid(attr->attcollation))
488 : 0 : *atttypcoll = attr->attcollation;
489 : : else
490 : 10 : *atttypcoll = exprCollation(expr);
491 : : }
492 : 853 : ReleaseSysCache(atup);
493 : :
494 : : /* finds the right operators even if atttypid is a domain */
495 : 853 : typcache = lookup_type_cache(*atttypid, TYPECACHE_LT_OPR | TYPECACHE_EQ_OPR);
496 : 853 : *atttyptype = typcache->typtype;
497 : 853 : *eq_opr = typcache->eq_opr;
498 : 853 : *lt_opr = typcache->lt_opr;
499 : :
500 : : /*
501 : : * Special case: collation for tsvector is DEFAULT_COLLATION_OID. See
502 : : * compute_tsvector_stats().
503 : : */
504 [ + + ]: 853 : if (*atttypid == TSVECTOROID)
505 : 1 : *atttypcoll = DEFAULT_COLLATION_OID;
506 : :
507 : 853 : relation_close(rel, NoLock);
508 : 853 : }
509 : :
510 : : /*
511 : : * Derive element type information from the attribute type. This information
512 : : * is needed when the given type is one that contains elements of other types.
513 : : *
514 : : * The atttypid and atttyptype should be derived from a previous call to
515 : : * statatt_get_type().
516 : : */
517 : : bool
518 : 60 : statatt_get_elem_type(Oid atttypid, char atttyptype,
519 : : Oid *elemtypid, Oid *elem_eq_opr)
520 : : {
521 : : TypeCacheEntry *elemtypcache;
522 : :
523 [ + + ]: 60 : if (atttypid == TSVECTOROID)
524 : : {
525 : : /*
526 : : * Special case: element type for tsvector is text. See
527 : : * compute_tsvector_stats().
528 : : */
529 : 5 : *elemtypid = TEXTOID;
530 : : }
531 : : else
532 : : {
533 : : /* find underlying element type through any domain */
534 : 55 : *elemtypid = get_base_element_type(atttypid);
535 : : }
536 : :
537 [ + + ]: 60 : if (!OidIsValid(*elemtypid))
538 : 20 : return false;
539 : :
540 : : /* finds the right operator even if elemtypid is a domain */
541 : 40 : elemtypcache = lookup_type_cache(*elemtypid, TYPECACHE_EQ_OPR);
542 [ - + ]: 40 : if (!OidIsValid(elemtypcache->eq_opr))
543 : 0 : return false;
544 : :
545 : 40 : *elem_eq_opr = elemtypcache->eq_opr;
546 : :
547 : 40 : return true;
548 : : }
549 : :
550 : : /*
551 : : * Build an array with element type typid from a text datum, used as
552 : : * value of an attribute in a tuple to-be-inserted into pg_statistic.
553 : : *
554 : : * The typid and typmod should be derived from a previous call to
555 : : * statatt_get_type().
556 : : *
557 : : * If an error is encountered, capture it and throw a WARNING, with "ok" set
558 : : * to false. If the resulting array contains NULLs, raise a WARNING and
559 : : * set "ok" to false. When the operation succeeds, set "ok" to true.
560 : : */
561 : : Datum
562 : 857 : statatt_build_stavalues(const char *staname, FmgrInfo *array_in, Datum d, Oid typid,
563 : : int32 typmod, bool *ok)
564 : : {
565 : : char *s;
566 : : Datum result;
567 : 857 : ErrorSaveContext escontext = {T_ErrorSaveContext};
568 : :
569 : 857 : escontext.details_wanted = true;
570 : :
571 : 857 : s = TextDatumGetCString(d);
572 : :
573 [ + + ]: 857 : if (!InputFunctionCallSafe(array_in, s, typid, typmod,
574 : : (Node *) &escontext, &result))
575 : : {
576 : 8 : pfree(s);
577 : 8 : escontext.error_data->elevel = WARNING;
578 : 8 : ThrowErrorData(escontext.error_data);
579 : 8 : *ok = false;
580 : 8 : return (Datum) 0;
581 : : }
582 : :
583 : 849 : pfree(s);
584 : :
585 [ + + ]: 849 : if (ARR_NDIM(DatumGetArrayTypeP(result)) != 1)
586 : : {
587 [ + - ]: 4 : ereport(WARNING,
588 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
589 : : errmsg("\"%s\" must be a one-dimensional array", staname)));
590 : 4 : *ok = false;
591 : 4 : return (Datum) 0;
592 : : }
593 : :
594 [ + + ]: 845 : if (array_contains_nulls(DatumGetArrayTypeP(result)))
595 : : {
596 [ + - ]: 4 : ereport(WARNING,
597 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
598 : : errmsg("\"%s\" array must not contain null values", staname)));
599 : 4 : *ok = false;
600 : 4 : return (Datum) 0;
601 : : }
602 : :
603 : 841 : *ok = true;
604 : :
605 : 841 : return result;
606 : : }
607 : :
608 : : /*
609 : : * Find and update the slot of a stakind, or use the first empty slot.
610 : : *
611 : : * Core statistics types expect the stakind value to be one of the
612 : : * STATISTIC_KIND_* constants defined in pg_statistic.h, but types defined
613 : : * by extensions are not restricted to those values.
614 : : *
615 : : * In the case of core statistics, the required staop is determined by the
616 : : * stakind given and will either be a hardcoded oid, or the eq/lt operator
617 : : * derived from statatt_get_type(). Likewise, types defined by extensions
618 : : * have no such restriction.
619 : : *
620 : : * The stacoll value should be either the atttypcoll derived from
621 : : * statatt_get_type(), or a hardcoded value required by that particular
622 : : * stakind.
623 : : *
624 : : * The value/null pairs for stanumbers and stavalues should be calculated
625 : : * based on the stakind, using statatt_build_stavalues() or constructed arrays.
626 : : */
627 : : void
628 : 1653 : statatt_set_slot(Datum *values, bool *nulls, bool *replaces,
629 : : int16 stakind, Oid staop, Oid stacoll,
630 : : Datum stanumbers, bool stanumbers_isnull,
631 : : Datum stavalues, bool stavalues_isnull)
632 : : {
633 : : int slotidx;
634 : 1653 : int first_empty = -1;
635 : : AttrNumber stakind_attnum;
636 : : AttrNumber staop_attnum;
637 : : AttrNumber stacoll_attnum;
638 : :
639 : : /* find existing slot with given stakind */
640 [ + + ]: 9918 : for (slotidx = 0; slotidx < STATISTIC_NUM_SLOTS; slotidx++)
641 : : {
642 : 8265 : stakind_attnum = Anum_pg_statistic_stakind1 - 1 + slotidx;
643 : :
644 [ + + + + ]: 10955 : if (first_empty < 0 &&
645 : 2690 : DatumGetInt16(values[stakind_attnum]) == 0)
646 : 1653 : first_empty = slotidx;
647 [ - + ]: 8265 : if (DatumGetInt16(values[stakind_attnum]) == stakind)
648 : 0 : break;
649 : : }
650 : :
651 [ + - + - ]: 1653 : if (slotidx >= STATISTIC_NUM_SLOTS && first_empty >= 0)
652 : 1653 : slotidx = first_empty;
653 : :
654 [ - + ]: 1653 : if (slotidx >= STATISTIC_NUM_SLOTS)
655 [ # # ]: 0 : ereport(ERROR,
656 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
657 : : errmsg("maximum number of statistics slots exceeded: %d",
658 : : slotidx + 1)));
659 : :
660 : 1653 : stakind_attnum = Anum_pg_statistic_stakind1 - 1 + slotidx;
661 : 1653 : staop_attnum = Anum_pg_statistic_staop1 - 1 + slotidx;
662 : 1653 : stacoll_attnum = Anum_pg_statistic_stacoll1 - 1 + slotidx;
663 : :
664 [ + - ]: 1653 : if (DatumGetInt16(values[stakind_attnum]) != stakind)
665 : : {
666 : 1653 : values[stakind_attnum] = Int16GetDatum(stakind);
667 : 1653 : replaces[stakind_attnum] = true;
668 : : }
669 [ + + ]: 1653 : if (DatumGetObjectId(values[staop_attnum]) != staop)
670 : : {
671 : 1629 : values[staop_attnum] = ObjectIdGetDatum(staop);
672 : 1629 : replaces[staop_attnum] = true;
673 : : }
674 [ + + ]: 1653 : if (DatumGetObjectId(values[stacoll_attnum]) != stacoll)
675 : : {
676 : 366 : values[stacoll_attnum] = ObjectIdGetDatum(stacoll);
677 : 366 : replaces[stacoll_attnum] = true;
678 : : }
679 [ + + ]: 1653 : if (!stanumbers_isnull)
680 : : {
681 : 1226 : values[Anum_pg_statistic_stanumbers1 - 1 + slotidx] = stanumbers;
682 : 1226 : nulls[Anum_pg_statistic_stanumbers1 - 1 + slotidx] = false;
683 : 1226 : replaces[Anum_pg_statistic_stanumbers1 - 1 + slotidx] = true;
684 : : }
685 [ + + ]: 1653 : if (!stavalues_isnull)
686 : : {
687 : 924 : values[Anum_pg_statistic_stavalues1 - 1 + slotidx] = stavalues;
688 : 924 : nulls[Anum_pg_statistic_stavalues1 - 1 + slotidx] = false;
689 : 924 : replaces[Anum_pg_statistic_stavalues1 - 1 + slotidx] = true;
690 : : }
691 : 1653 : }
692 : :
693 : : /*
694 : : * Initialize values and nulls for a new pg_statistic tuple.
695 : : *
696 : : * The caller is responsible for allocating the arrays where the results are
697 : : * stored, which should be of size Natts_pg_statistic.
698 : : *
699 : : * When using this routine for a tuple inserted into pg_statistic, reloid,
700 : : * attnum and inherited flags should all be set.
701 : : *
702 : : * When using this routine for a tuple that is an element of a stxdexpr
703 : : * array inserted into pg_statistic_ext_data, reloid, attnum and inherited
704 : : * should be respectively set to InvalidOid, InvalidAttrNumber and false.
705 : : */
706 : : void
707 : 916 : statatt_init_empty_tuple(Oid reloid, int16 attnum, bool inherited,
708 : : Datum *values, bool *nulls, bool *replaces)
709 : : {
710 : 916 : memset(nulls, true, sizeof(bool) * Natts_pg_statistic);
711 : 916 : memset(replaces, true, sizeof(bool) * Natts_pg_statistic);
712 : :
713 : : /* This must initialize non-NULL attributes */
714 : 916 : values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(reloid);
715 : 916 : nulls[Anum_pg_statistic_starelid - 1] = false;
716 : 916 : values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(attnum);
717 : 916 : nulls[Anum_pg_statistic_staattnum - 1] = false;
718 : 916 : values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inherited);
719 : 916 : nulls[Anum_pg_statistic_stainherit - 1] = false;
720 : :
721 : 916 : values[Anum_pg_statistic_stanullfrac - 1] = DEFAULT_STATATT_NULL_FRAC;
722 : 916 : nulls[Anum_pg_statistic_stanullfrac - 1] = false;
723 : 916 : values[Anum_pg_statistic_stawidth - 1] = DEFAULT_STATATT_AVG_WIDTH;
724 : 916 : nulls[Anum_pg_statistic_stawidth - 1] = false;
725 : 916 : values[Anum_pg_statistic_stadistinct - 1] = DEFAULT_STATATT_N_DISTINCT;
726 : 916 : nulls[Anum_pg_statistic_stadistinct - 1] = false;
727 : :
728 : : /* initialize stakind, staop, and stacoll slots */
729 [ + + ]: 5496 : for (int slotnum = 0; slotnum < STATISTIC_NUM_SLOTS; slotnum++)
730 : : {
731 : 4580 : values[Anum_pg_statistic_stakind1 + slotnum - 1] = (Datum) 0;
732 : 4580 : nulls[Anum_pg_statistic_stakind1 + slotnum - 1] = false;
733 : 4580 : values[Anum_pg_statistic_staop1 + slotnum - 1] = ObjectIdGetDatum(InvalidOid);
734 : 4580 : nulls[Anum_pg_statistic_staop1 + slotnum - 1] = false;
735 : 4580 : values[Anum_pg_statistic_stacoll1 + slotnum - 1] = ObjectIdGetDatum(InvalidOid);
736 : 4580 : nulls[Anum_pg_statistic_stacoll1 + slotnum - 1] = false;
737 : : }
738 : 916 : }
739 : :
740 : : /*
741 : : * Check that an imported bounds histogram (STATISTIC_KIND_BOUNDS_HISTOGRAM)
742 : : * is shaped the same way ANALYZE builds it in compute_range_stats().
743 : : *
744 : : * For both range-typed and multirange-typed columns the histogram is an array
745 : : * of ranges, so we take the range type from the array's element type.
746 : : */
747 : : bool
748 : 40 : statatt_check_bounds_histogram(Datum arrayval)
749 : : {
750 : 40 : ArrayType *arr = DatumGetArrayTypeP(arrayval);
751 : 40 : Oid rngtypid = ARR_ELEMTYPE(arr);
752 : : TypeCacheEntry *typcache;
753 : : int16 elmlen;
754 : : bool elmbyval;
755 : : char elmalign;
756 : : Datum *elems;
757 : : bool *nulls;
758 : : int nelems;
759 : 40 : RangeBound prev_lower = {0};
760 : 40 : RangeBound prev_upper = {0};
761 : :
762 : 40 : typcache = lookup_type_cache(rngtypid, TYPECACHE_RANGE_INFO);
763 : :
764 : : /*
765 : : * The element type should always be a range type here. This is
766 : : * defensive. If it isn't, the bounds histogram is never consulted by the
767 : : * range estimator, and there is nothing to verify.
768 : : */
769 [ - + ]: 40 : if (typcache->rngelemtype == NULL)
770 : 0 : return true;
771 : :
772 : 40 : get_typlenbyvalalign(rngtypid, &elmlen, &elmbyval, &elmalign);
773 : 40 : deconstruct_array(arr, rngtypid, elmlen, elmbyval, elmalign,
774 : : &elems, &nulls, &nelems);
775 : :
776 [ + + ]: 330 : for (int i = 0; i < nelems; i++)
777 : : {
778 : : RangeBound lower,
779 : : upper;
780 : : bool empty;
781 : :
782 : : /*
783 : : * NULL elements are already rejected by statatt_build_stavalues() and
784 : : * array_in_safe().
785 : : */
786 : 306 : range_deserialize(typcache, DatumGetRangeTypeP(elems[i]),
787 : : &lower, &upper, &empty);
788 : :
789 [ + + ]: 306 : if (empty)
790 : : {
791 [ + - ]: 8 : ereport(WARNING,
792 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
793 : : errmsg("\"%s\" must not contain empty ranges",
794 : : "range_bounds_histogram")));
795 : 16 : return false;
796 : : }
797 : :
798 [ + + + + ]: 564 : if (i > 0 &&
799 [ - + ]: 524 : (range_cmp_bounds(typcache, &lower, &prev_lower) < 0 ||
800 : 258 : range_cmp_bounds(typcache, &upper, &prev_upper) < 0))
801 : : {
802 [ + - ]: 8 : ereport(WARNING,
803 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
804 : : errmsg("\"%s\" must have its lower and upper bounds sorted in ascending order",
805 : : "range_bounds_histogram")));
806 : 8 : return false;
807 : : }
808 : :
809 : 290 : prev_lower = lower;
810 : 290 : prev_upper = upper;
811 : : }
812 : :
813 : 24 : return true;
814 : : }
|