Debian Codegraph @

src/backend/commands/statscmds.c

raw
1 /*-------------------------------------------------------------------------
2 *
3 * statscmds.c
4 * Commands for creating and altering extended statistics objects
5 *
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/commands/statscmds.c
12 *
13 *-------------------------------------------------------------------------
14 */
15 #include "postgres.h"
16
17 #include "access/relation.h"
18 #include "access/table.h"
19 #include "catalog/catalog.h"
20 #include "catalog/dependency.h"
21 #include "catalog/indexing.h"
22 #include "catalog/namespace.h"
23 #include "catalog/objectaccess.h"
24 #include "catalog/pg_namespace.h"
25 #include "catalog/pg_statistic_ext.h"
26 #include "catalog/pg_statistic_ext_data.h"
27 #include "commands/comment.h"
28 #include "commands/defrem.h"
29 #include "miscadmin.h"
30 #include "nodes/nodeFuncs.h"
31 #include "optimizer/optimizer.h"
32 #include "statistics/statistics.h"
33 #include "utils/acl.h"
34 #include "utils/builtins.h"
35 #include "utils/inval.h"
36 #include "utils/lsyscache.h"
37 #include "utils/rel.h"
38 #include "utils/syscache.h"
39 #include "utils/typcache.h"
40
41
42 static char *ChooseExtendedStatisticName(const char *name1, const char *name2,
43 const char *label, Oid namespaceid);
44 static char *ChooseExtendedStatisticNameAddition(List *exprs);
45
46
47 /* qsort comparator for the attnums in CreateStatistics */
48 static int
49 compare_int16(const void *a, const void *b)
50 {
51 int av = *(const int16 *) a;
52 int bv = *(const int16 *) b;
53
54 /* this can't overflow if int is wider than int16 */
55 return (av - bv);
56 }
57
58 /*
59 * CREATE STATISTICS
60 *
61 * relids is a list of OIDs of relations specified in the FROM clause, on which
62 * the statistics object is defined. We identify the target by the passed-in
63 * OID rather than re-resolving stmt->relations by name, so that we operate
64 * on exactly the relation the caller looked up. Only a single relation is
65 * supported for now.
66 */
67 ObjectAddress
68 CreateStatistics(List *relids, CreateStatsStmt *stmt, bool check_rights)
69 {
70 int16 attnums[STATS_MAX_DIMENSIONS];
71 int nattnums = 0;
72 int numcols;
73 char *namestr;
74 NameData stxname;
75 Oid statoid;
76 Oid namespaceId;
77 Oid stxowner = OidIsValid(stmt->owner) ? stmt->owner : GetUserId();
78 HeapTuple htup;
79 Datum values[Natts_pg_statistic_ext];
80 bool nulls[Natts_pg_statistic_ext];
81 int2vector *stxkeys;
82 List *stxexprs = NIL;
83 Datum exprsDatum;
84 Relation statrel;
85 Relation rel = NULL;
86 Oid relid = InvalidOid;
87 ObjectAddress parentobject,
88 myself;
89 Datum types[4]; /* one for each possible type of statistic */
90 int ntypes;
91 ArrayType *stxkind;
92 bool build_ndistinct;
93 bool build_dependencies;
94 bool build_mcv;
95 bool build_expressions;
96 bool requested_type = false;
97 int i;
98 ListCell *cell;
99 ListCell *cell2;
100
101 Assert(IsA(stmt, CreateStatsStmt));
102
103 /*
104 * Currently, we only allow the FROM clause to be a single simple table,
105 * but later we'll probably allow multiple tables and JOIN syntax. The
106 * grammar and the loop below are already prepared for that, but examining
107 * the FROM clause is the caller's job, so all we do here is assert that
108 * the caller rejected what we can't support.
109 */
110 Assert(list_length(relids) == 1);
111
112 foreach(cell, relids)
113 {
114 relid = lfirst_oid(cell);
115
116 /*
117 * CREATE STATISTICS will influence future execution plans but does
118 * not interfere with currently executing plans. So it should be
119 * enough to take only ShareUpdateExclusiveLock on relation,
120 * conflicting with ANALYZE and other DDL that sets statistical
121 * information, but not with normal queries.
122 */
123 rel = relation_open(relid, ShareUpdateExclusiveLock);
124
125 /* Restrict to allowed relation types */
126 if (rel->rd_rel->relkind != RELKIND_RELATION &&
127 rel->rd_rel->relkind != RELKIND_MATVIEW &&
128 rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
129 rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
130 ereport(ERROR,
131 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
132 errmsg("cannot define statistics for relation \"%s\"",
133 RelationGetRelationName(rel)),
134 errdetail_relkind_not_supported(rel->rd_rel->relkind)));
135
136 /*
137 * You must own the relation to create stats on it. Skip check if
138 * caller doesn't want it.
139 */
140 if (check_rights &&
141 !object_ownercheck(RelationRelationId, RelationGetRelid(rel), stxowner))
142 aclcheck_error(ACLCHECK_NOT_OWNER, get_relkind_objtype(rel->rd_rel->relkind),
143 RelationGetRelationName(rel));
144
145 /* Creating statistics on system catalogs is not allowed */
146 if (!allowSystemTableMods && IsSystemRelation(rel))
147 ereport(ERROR,
148 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
149 errmsg("permission denied: \"%s\" is a system catalog",
150 RelationGetRelationName(rel))));
151 }
152
153 Assert(rel);
154
155 /*
156 * If the node has a name, split it up and determine creation namespace.
157 * If not, put the object in the same namespace as the relation, and cons
158 * up a name for it. (This can happen either via "CREATE STATISTICS ..."
159 * or via "CREATE TABLE ... (LIKE)".)
160 */
161 if (stmt->defnames)
162 namespaceId = QualifiedNameGetCreationNamespace(stmt->defnames,
163 &namestr);
164 else
165 {
166 namespaceId = RelationGetNamespace(rel);
167 namestr = ChooseExtendedStatisticName(RelationGetRelationName(rel),
168 ChooseExtendedStatisticNameAddition(stmt->exprs),
169 "stat",
170 namespaceId);
171 }
172 namestrcpy(&stxname, namestr);
173
174 /*
175 * Check we have creation rights in target namespace. Skip check if
176 * caller doesn't want it.
177 */
178 if (check_rights)
179 {
180 AclResult aclresult;
181
182 aclresult = object_aclcheck(NamespaceRelationId, namespaceId,
183 GetUserId(), ACL_CREATE);
184 if (aclresult != ACLCHECK_OK)
185 aclcheck_error(aclresult, OBJECT_SCHEMA,
186 get_namespace_name(namespaceId));
187 }
188
189 /*
190 * Deal with the possibility that the statistics object already exists.
191 */
192 if (SearchSysCacheExists2(STATEXTNAMENSP,
193 CStringGetDatum(namestr),
194 ObjectIdGetDatum(namespaceId)))
195 {
196 if (stmt->if_not_exists)
197 {
198 /*
199 * Since stats objects aren't members of extensions (see comments
200 * below), no need for checkMembershipInCurrentExtension here.
201 */
202 ereport(NOTICE,
203 (errcode(ERRCODE_DUPLICATE_OBJECT),
204 errmsg("statistics object \"%s\" already exists, skipping",
205 namestr)));
206 relation_close(rel, NoLock);
207 return InvalidObjectAddress;
208 }
209
210 ereport(ERROR,
211 (errcode(ERRCODE_DUPLICATE_OBJECT),
212 errmsg("statistics object \"%s\" already exists", namestr)));
213 }
214
215 /*
216 * Make sure no more than STATS_MAX_DIMENSIONS columns are used. There
217 * might be duplicates and so on, but we'll deal with those later.
218 */
219 numcols = list_length(stmt->exprs);
220 if (numcols > STATS_MAX_DIMENSIONS)
221 ereport(ERROR,
222 (errcode(ERRCODE_TOO_MANY_COLUMNS),
223 errmsg("cannot have more than %d columns in statistics",
224 STATS_MAX_DIMENSIONS)));
225
226 /*
227 * Convert the expression list to a simple array of attnums, but also keep
228 * a list of more complex expressions. While at it, enforce some
229 * constraints - we don't allow extended statistics on system attributes,
230 * and we require the data type to have a less-than operator.
231 *
232 * There are many ways to "mask" a simple attribute reference as an
233 * expression, for example "(a+0)" etc. We can't possibly detect all of
234 * them, but we handle at least the simple case with the attribute in
235 * parens. There'll always be a way around this, if the user is determined
236 * (like the "(a+0)" example), but this makes it somewhat consistent with
237 * how indexes treat attributes/expressions.
238 */
239 foreach(cell, stmt->exprs)
240 {
241 StatsElem *selem = lfirst_node(StatsElem, cell);
242
243 if (selem->name) /* column reference */
244 {
245 char *attname;
246 HeapTuple atttuple;
247 Form_pg_attribute attForm;
248 TypeCacheEntry *type;
249
250 attname = selem->name;
251
252 atttuple = SearchSysCacheAttName(relid, attname);
253 if (!HeapTupleIsValid(atttuple))
254 ereport(ERROR,
255 (errcode(ERRCODE_UNDEFINED_COLUMN),
256 errmsg("column \"%s\" does not exist",
257 attname)));
258 attForm = (Form_pg_attribute) GETSTRUCT(atttuple);
259
260 /* Disallow use of system attributes in extended stats */
261 if (attForm->attnum <= 0)
262 ereport(ERROR,
263 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
264 errmsg("statistics creation on system columns is not supported")));
265
266 /* Disallow use of virtual generated columns in extended stats */
267 if (attForm->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
268 ereport(ERROR,
269 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
270 errmsg("statistics creation on virtual generated columns is not supported")));
271
272 /* Disallow data types without a less-than operator */
273 type = lookup_type_cache(attForm->atttypid, TYPECACHE_LT_OPR);
274 if (type->lt_opr == InvalidOid)
275 ereport(ERROR,
276 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
277 errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class",
278 attname, format_type_be(attForm->atttypid))));
279
280 attnums[nattnums] = attForm->attnum;
281 nattnums++;
282 ReleaseSysCache(atttuple);
283 }
284 else if (IsA(selem->expr, Var)) /* column reference in parens */
285 {
286 Var *var = (Var *) selem->expr;
287 TypeCacheEntry *type;
288
289 /* Disallow use of system attributes in extended stats */
290 if (var->varattno <= 0)
291 ereport(ERROR,
292 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
293 errmsg("statistics creation on system columns is not supported")));
294
295 /* Disallow use of virtual generated columns in extended stats */
296 if (get_attgenerated(relid, var->varattno) == ATTRIBUTE_GENERATED_VIRTUAL)
297 ereport(ERROR,
298 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
299 errmsg("statistics creation on virtual generated columns is not supported")));
300
301 /* Disallow data types without a less-than operator */
302 type = lookup_type_cache(var->vartype, TYPECACHE_LT_OPR);
303 if (type->lt_opr == InvalidOid)
304 ereport(ERROR,
305 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
306 errmsg("column \"%s\" cannot be used in statistics because its type %s has no default btree operator class",
307 get_attname(relid, var->varattno, false), format_type_be(var->vartype))));
308
309 attnums[nattnums] = var->varattno;
310 nattnums++;
311 }
312 else /* expression */
313 {
314 Node *expr = selem->expr;
315 Oid atttype;
316 TypeCacheEntry *type;
317 Bitmapset *attnums = NULL;
318 int k;
319
320 Assert(expr != NULL);
321
322 pull_varattnos(expr, 1, &attnums);
323
324 k = -1;
325 while ((k = bms_next_member(attnums, k)) >= 0)
326 {
327 AttrNumber attnum = k + FirstLowInvalidHeapAttributeNumber;
328
329 /* Disallow expressions referencing system attributes. */
330 if (attnum <= 0)
331 ereport(ERROR,
332 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
333 errmsg("statistics creation on system columns is not supported")));
334
335 /* Disallow use of virtual generated columns in extended stats */
336 if (get_attgenerated(relid, attnum) == ATTRIBUTE_GENERATED_VIRTUAL)
337 ereport(ERROR,
338 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
339 errmsg("statistics creation on virtual generated columns is not supported")));
340 }
341
342 /*
343 * Disallow data types without a less-than operator.
344 *
345 * We ignore this for statistics on a single expression, in which
346 * case we'll build the regular statistics only (and that code can
347 * deal with such data types).
348 */
349 if (list_length(stmt->exprs) > 1)
350 {
351 atttype = exprType(expr);
352 type = lookup_type_cache(atttype, TYPECACHE_LT_OPR);
353 if (type->lt_opr == InvalidOid)
354 ereport(ERROR,
355 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
356 errmsg("expression cannot be used in multivariate statistics because its type %s has no default btree operator class",
357 format_type_be(atttype))));
358 }
359
360 stxexprs = lappend(stxexprs, expr);
361 }
362 }
363
364 /*
365 * Parse the statistics kinds.
366 *
367 * First check that if this is the case with a single expression, there
368 * are no statistics kinds specified (we don't allow that for the simple
369 * CREATE STATISTICS form).
370 */
371 if ((list_length(stmt->exprs) == 1) && (list_length(stxexprs) == 1))
372 {
373 /* statistics kinds not specified */
374 if (stmt->stat_types != NIL)
375 ereport(ERROR,
376 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
377 errmsg("when building statistics on a single expression, statistics kinds may not be specified")));
378 }
379
380 /* OK, let's check that we recognize the statistics kinds. */
381 build_ndistinct = false;
382 build_dependencies = false;
383 build_mcv = false;
384 foreach(cell, stmt->stat_types)
385 {
386 char *type = strVal(lfirst(cell));
387
388 if (strcmp(type, "ndistinct") == 0)
389 {
390 build_ndistinct = true;
391 requested_type = true;
392 }
393 else if (strcmp(type, "dependencies") == 0)
394 {
395 build_dependencies = true;
396 requested_type = true;
397 }
398 else if (strcmp(type, "mcv") == 0)
399 {
400 build_mcv = true;
401 requested_type = true;
402 }
403 else
404 ereport(ERROR,
405 (errcode(ERRCODE_SYNTAX_ERROR),
406 errmsg("unrecognized statistics kind \"%s\"",
407 type)));
408 }
409
410 /*
411 * If no statistic type was specified, build them all (but only when the
412 * statistics is defined on more than one column/expression).
413 */
414 if ((!requested_type) && (numcols >= 2))
415 {
416 build_ndistinct = true;
417 build_dependencies = true;
418 build_mcv = true;
419 }
420
421 /*
422 * When there are non-trivial expressions, build the expression stats
423 * automatically. This allows calculating good estimates for stats that
424 * consider per-clause estimates (e.g. functional dependencies).
425 */
426 build_expressions = (stxexprs != NIL);
427
428 /*
429 * Check that at least two columns were specified in the statement, or
430 * that we're building statistics on a single expression.
431 */
432 if ((numcols < 2) && (list_length(stxexprs) != 1))
433 ereport(ERROR,
434 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
435 errmsg("extended statistics require at least 2 columns")));
436
437 /*
438 * Sort the attnums, which makes detecting duplicates somewhat easier, and
439 * it does not hurt (it does not matter for the contents, unlike for
440 * indexes, for example).
441 */
442 qsort(attnums, nattnums, sizeof(int16), compare_int16);
443
444 /*
445 * Check for duplicates in the list of columns. The attnums are sorted so
446 * just check consecutive elements.
447 */
448 for (i = 1; i < nattnums; i++)
449 {
450 if (attnums[i] == attnums[i - 1])
451 ereport(ERROR,
452 (errcode(ERRCODE_DUPLICATE_COLUMN),
453 errmsg("duplicate column name in statistics definition")));
454 }
455
456 /*
457 * Check for duplicate expressions. We do two loops, counting the
458 * occurrences of each expression. This is O(N^2) but we only allow small
459 * number of expressions and it's not executed often.
460 *
461 * XXX We don't cross-check attributes and expressions, because it does
462 * not seem worth it. In principle we could check that expressions don't
463 * contain trivial attribute references like "(a)", but the reasoning is
464 * similar to why we don't bother with extracting columns from
465 * expressions. It's either expensive or very easy to defeat for
466 * determined user, and there's no risk if we allow such statistics (the
467 * statistics is useless, but harmless).
468 */
469 foreach(cell, stxexprs)
470 {
471 Node *expr1 = (Node *) lfirst(cell);
472 int cnt = 0;
473
474 foreach(cell2, stxexprs)
475 {
476 Node *expr2 = (Node *) lfirst(cell2);
477
478 if (equal(expr1, expr2))
479 cnt += 1;
480 }
481
482 /* every expression should find at least itself */
483 Assert(cnt >= 1);
484
485 if (cnt > 1)
486 ereport(ERROR,
487 (errcode(ERRCODE_DUPLICATE_COLUMN),
488 errmsg("duplicate expression in statistics definition")));
489 }
490
491 /* Form an int2vector representation of the sorted column list */
492 stxkeys = buildint2vector(attnums, nattnums);
493
494 /* construct the char array of enabled statistic types */
495 ntypes = 0;
496 if (build_ndistinct)
497 types[ntypes++] = CharGetDatum(STATS_EXT_NDISTINCT);
498 if (build_dependencies)
499 types[ntypes++] = CharGetDatum(STATS_EXT_DEPENDENCIES);
500 if (build_mcv)
501 types[ntypes++] = CharGetDatum(STATS_EXT_MCV);
502 if (build_expressions)
503 types[ntypes++] = CharGetDatum(STATS_EXT_EXPRESSIONS);
504 Assert(ntypes > 0 && ntypes <= lengthof(types));
505 stxkind = construct_array_builtin(types, ntypes, CHAROID);
506
507 /* convert the expressions (if any) to a text datum */
508 if (stxexprs != NIL)
509 {
510 char *exprsString;
511
512 exprsString = nodeToString(stxexprs);
513 exprsDatum = CStringGetTextDatum(exprsString);
514 pfree(exprsString);
515 }
516 else
517 exprsDatum = (Datum) 0;
518
519 statrel = table_open(StatisticExtRelationId, RowExclusiveLock);
520
521 /*
522 * Everything seems fine, so let's build the pg_statistic_ext tuple.
523 */
524 memset(values, 0, sizeof(values));
525 memset(nulls, false, sizeof(nulls));
526
527 statoid = GetNewOidWithIndex(statrel, StatisticExtOidIndexId,
528 Anum_pg_statistic_ext_oid);
529 values[Anum_pg_statistic_ext_oid - 1] = ObjectIdGetDatum(statoid);
530 values[Anum_pg_statistic_ext_stxrelid - 1] = ObjectIdGetDatum(relid);
531 values[Anum_pg_statistic_ext_stxname - 1] = NameGetDatum(&stxname);
532 values[Anum_pg_statistic_ext_stxnamespace - 1] = ObjectIdGetDatum(namespaceId);
533 values[Anum_pg_statistic_ext_stxowner - 1] = ObjectIdGetDatum(stxowner);
534 values[Anum_pg_statistic_ext_stxkeys - 1] = PointerGetDatum(stxkeys);
535 nulls[Anum_pg_statistic_ext_stxstattarget - 1] = true;
536 values[Anum_pg_statistic_ext_stxkind - 1] = PointerGetDatum(stxkind);
537
538 values[Anum_pg_statistic_ext_stxexprs - 1] = exprsDatum;
539 if (exprsDatum == (Datum) 0)
540 nulls[Anum_pg_statistic_ext_stxexprs - 1] = true;
541
542 /* insert it into pg_statistic_ext */
543 htup = heap_form_tuple(statrel->rd_att, values, nulls);
544 CatalogTupleInsert(statrel, htup);
545 heap_freetuple(htup);
546
547 relation_close(statrel, RowExclusiveLock);
548
549 /*
550 * We used to create the pg_statistic_ext_data tuple too, but it's not
551 * clear what value should the stxdinherit flag have (it depends on
552 * whether the rel is partitioned, contains data, etc.)
553 */
554
555 InvokeObjectPostCreateHook(StatisticExtRelationId, statoid, 0);
556
557 /*
558 * Invalidate relcache so that others see the new statistics object.
559 */
560 CacheInvalidateRelcache(rel);
561
562 relation_close(rel, NoLock);
563
564 /*
565 * Add an AUTO dependency on each column used in the stats, so that the
566 * stats object goes away if any or all of them get dropped.
567 */
568 ObjectAddressSet(myself, StatisticExtRelationId, statoid);
569
570 /* add dependencies for plain column references */
571 for (i = 0; i < nattnums; i++)
572 {
573 ObjectAddressSubSet(parentobject, RelationRelationId, relid, attnums[i]);
574 recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);
575 }
576
577 /*
578 * If there are no dependencies on a column, give the statistics object an
579 * auto dependency on the whole table. In most cases, this will be
580 * redundant, but it might not be if the statistics expressions contain no
581 * Vars (which might seem strange but possible). This is consistent with
582 * what we do for indexes in index_create.
583 *
584 * XXX We intentionally don't consider the expressions before adding this
585 * dependency, because recordDependencyOnSingleRelExpr may not create any
586 * dependencies for whole-row Vars.
587 */
588 if (!nattnums)
589 {
590 ObjectAddressSet(parentobject, RelationRelationId, relid);
591 recordDependencyOn(&myself, &parentobject, DEPENDENCY_AUTO);
592 }
593
594 /*
595 * Store dependencies on anything mentioned in statistics expressions,
596 * just like we do for index expressions.
597 */
598 if (stxexprs)
599 {
600 if (check_rights)
601 CheckUsageOnTypesInSingleRelExpr((Node *) stxexprs, relid, GetUserId());
602
603 recordDependencyOnSingleRelExpr(&myself,
604 (Node *) stxexprs,
605 relid,
606 DEPENDENCY_NORMAL,
607 DEPENDENCY_AUTO, false);
608 }
609
610 /*
611 * Also add dependencies on namespace and owner. These are required
612 * because the stats object might have a different namespace and/or owner
613 * than the underlying table(s).
614 */
615 ObjectAddressSet(parentobject, NamespaceRelationId, namespaceId);
616 recordDependencyOn(&myself, &parentobject, DEPENDENCY_NORMAL);
617
618 recordDependencyOnOwner(StatisticExtRelationId, statoid, stxowner);
619
620 /*
621 * XXX probably there should be a recordDependencyOnCurrentExtension call
622 * here too, but we'd have to add support for ALTER EXTENSION ADD/DROP
623 * STATISTICS, which is more work than it seems worth.
624 */
625
626 /* Add any requested comment */
627 if (stmt->stxcomment != NULL)
628 CreateComments(statoid, StatisticExtRelationId, 0,
629 stmt->stxcomment);
630
631 /* Return stats object's address */
632 return myself;
633 }
634
635 /*
636 * ALTER STATISTICS
637 */
638 ObjectAddress
639 AlterStatistics(AlterStatsStmt *stmt)
640 {
641 Relation rel;
642 Oid stxoid;
643 HeapTuple oldtup;
644 HeapTuple newtup;
645 Datum repl_val[Natts_pg_statistic_ext];
646 bool repl_null[Natts_pg_statistic_ext];
647 bool repl_repl[Natts_pg_statistic_ext];
648 ObjectAddress address;
649 int newtarget = 0;
650 bool newtarget_default;
651
652 /* -1 was used in previous versions for the default setting */
653 if (stmt->stxstattarget && intVal(stmt->stxstattarget) != -1)
654 {
655 newtarget = intVal(stmt->stxstattarget);
656 newtarget_default = false;
657 }
658 else
659 newtarget_default = true;
660
661 if (!newtarget_default)
662 {
663 /* Limit statistics target to a sane range */
664 if (newtarget < 0)
665 {
666 ereport(ERROR,
667 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
668 errmsg("statistics target %d is too low",
669 newtarget)));
670 }
671 else if (newtarget > MAX_STATISTICS_TARGET)
672 {
673 newtarget = MAX_STATISTICS_TARGET;
674 ereport(WARNING,
675 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
676 errmsg("lowering statistics target to %d",
677 newtarget)));
678 }
679 }
680
681 /* lookup OID of the statistics object */
682 stxoid = get_statistics_object_oid(stmt->defnames, stmt->missing_ok);
683
684 /*
685 * If we got here and the OID is not valid, it means the statistics object
686 * does not exist, but the command specified IF EXISTS. So report this as
687 * a simple NOTICE and we're done.
688 */
689 if (!OidIsValid(stxoid))
690 {
691 char *schemaname;
692 char *statname;
693
694 Assert(stmt->missing_ok);
695
696 DeconstructQualifiedName(stmt->defnames, &schemaname, &statname);
697
698 if (schemaname)
699 ereport(NOTICE,
700 (errmsg("statistics object \"%s.%s\" does not exist, skipping",
701 schemaname, statname)));
702 else
703 ereport(NOTICE,
704 (errmsg("statistics object \"%s\" does not exist, skipping",
705 statname)));
706
707 return InvalidObjectAddress;
708 }
709
710 /* Search pg_statistic_ext */
711 rel = table_open(StatisticExtRelationId, RowExclusiveLock);
712
713 oldtup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(stxoid));
714 if (!HeapTupleIsValid(oldtup))
715 elog(ERROR, "cache lookup failed for extended statistics object %u", stxoid);
716
717 /* Must be owner of the existing statistics object */
718 if (!object_ownercheck(StatisticExtRelationId, stxoid, GetUserId()))
719 aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_STATISTIC_EXT,
720 NameListToString(stmt->defnames));
721
722 /* Build new tuple. */
723 memset(repl_val, 0, sizeof(repl_val));
724 memset(repl_null, false, sizeof(repl_null));
725 memset(repl_repl, false, sizeof(repl_repl));
726
727 /* replace the stxstattarget column */
728 repl_repl[Anum_pg_statistic_ext_stxstattarget - 1] = true;
729 if (!newtarget_default)
730 repl_val[Anum_pg_statistic_ext_stxstattarget - 1] = Int16GetDatum(newtarget);
731 else
732 repl_null[Anum_pg_statistic_ext_stxstattarget - 1] = true;
733
734 newtup = heap_modify_tuple(oldtup, RelationGetDescr(rel),
735 repl_val, repl_null, repl_repl);
736
737 /* Update system catalog. */
738 CatalogTupleUpdate(rel, &newtup->t_self, newtup);
739
740 InvokeObjectPostAlterHook(StatisticExtRelationId, stxoid, 0);
741
742 ObjectAddressSet(address, StatisticExtRelationId, stxoid);
743
744 /*
745 * NOTE: because we only support altering the statistics target, not the
746 * other fields, there is no need to update dependencies.
747 */
748
749 heap_freetuple(newtup);
750 ReleaseSysCache(oldtup);
751
752 table_close(rel, RowExclusiveLock);
753
754 return address;
755 }
756
757 /*
758 * Delete entry in pg_statistic_ext_data catalog. We don't know if the row
759 * exists, so don't error out.
760 */
761 void
762 RemoveStatisticsDataById(Oid statsOid, bool inh)
763 {
764 Relation relation;
765 HeapTuple tup;
766
767 relation = table_open(StatisticExtDataRelationId, RowExclusiveLock);
768
769 tup = SearchSysCache2(STATEXTDATASTXOID, ObjectIdGetDatum(statsOid),
770 BoolGetDatum(inh));
771
772 /* We don't know if the data row for inh value exists. */
773 if (HeapTupleIsValid(tup))
774 {
775 CatalogTupleDelete(relation, &tup->t_self);
776
777 ReleaseSysCache(tup);
778 }
779
780 table_close(relation, RowExclusiveLock);
781 }
782
783 /*
784 * Guts of statistics object deletion.
785 */
786 void
787 RemoveStatisticsById(Oid statsOid)
788 {
789 Relation relation;
790 Relation rel;
791 HeapTuple tup;
792 Form_pg_statistic_ext statext;
793 Oid relid;
794
795 /*
796 * Delete the pg_statistic_ext tuple. Also send out a cache inval on the
797 * associated table, so that dependent plans will be rebuilt.
798 */
799 relation = table_open(StatisticExtRelationId, RowExclusiveLock);
800
801 tup = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statsOid));
802
803 if (!HeapTupleIsValid(tup)) /* should not happen */
804 elog(ERROR, "cache lookup failed for statistics object %u", statsOid);
805
806 statext = (Form_pg_statistic_ext) GETSTRUCT(tup);
807 relid = statext->stxrelid;
808
809 /*
810 * Delete the pg_statistic_ext_data tuples holding the actual statistical
811 * data. There might be data with/without inheritance, so attempt deleting
812 * both. We lock the user table first, to prevent other processes (e.g.
813 * DROP STATISTICS) from removing the row concurrently.
814 */
815 rel = table_open(relid, ShareUpdateExclusiveLock);
816
817 RemoveStatisticsDataById(statsOid, true);
818 RemoveStatisticsDataById(statsOid, false);
819
820 CacheInvalidateRelcacheByRelid(relid);
821
822 CatalogTupleDelete(relation, &tup->t_self);
823
824 ReleaseSysCache(tup);
825
826 /* Keep lock until the end of the transaction. */
827 table_close(rel, NoLock);
828
829 table_close(relation, RowExclusiveLock);
830 }
831
832 /*
833 * Select a nonconflicting name for a new statistics object.
834 *
835 * name1, name2, and label are used the same way as for makeObjectName(),
836 * except that the label can't be NULL; digits will be appended to the label
837 * if needed to create a name that is unique within the specified namespace.
838 *
839 * Returns a palloc'd string.
840 *
841 * Note: it is theoretically possible to get a collision anyway, if someone
842 * else chooses the same name concurrently. This is fairly unlikely to be
843 * a problem in practice, especially if one is holding a share update
844 * exclusive lock on the relation identified by name1. However, if choosing
845 * multiple names within a single command, you'd better create the new object
846 * and do CommandCounterIncrement before choosing the next one!
847 */
848 static char *
849 ChooseExtendedStatisticName(const char *name1, const char *name2,
850 const char *label, Oid namespaceid)
851 {
852 int pass = 0;
853 char *stxname = NULL;
854 char modlabel[NAMEDATALEN];
855
856 /* try the unmodified label first */
857 strlcpy(modlabel, label, sizeof(modlabel));
858
859 for (;;)
860 {
861 Oid existingstats;
862
863 stxname = makeObjectName(name1, name2, modlabel);
864
865 existingstats = GetSysCacheOid2(STATEXTNAMENSP, Anum_pg_statistic_ext_oid,
866 PointerGetDatum(stxname),
867 ObjectIdGetDatum(namespaceid));
868 if (!OidIsValid(existingstats))
869 break;
870
871 /* found a conflict, so try a new name component */
872 pfree(stxname);
873 snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
874 }
875
876 return stxname;
877 }
878
879 /*
880 * Generate "name2" for a new statistics object given the list of column
881 * names for it. This will be passed to ChooseExtendedStatisticName along
882 * with the parent table name and a suitable label.
883 *
884 * We know that less than NAMEDATALEN characters will actually be used,
885 * so we can truncate the result once we've generated that many.
886 *
887 * XXX see also ChooseForeignKeyConstraintNameAddition and
888 * ChooseIndexNameAddition.
889 */
890 static char *
891 ChooseExtendedStatisticNameAddition(List *exprs)
892 {
893 char buf[NAMEDATALEN * 2];
894 int buflen = 0;
895 ListCell *lc;
896
897 buf[0] = '\0';
898 foreach(lc, exprs)
899 {
900 StatsElem *selem = (StatsElem *) lfirst(lc);
901 const char *name;
902
903 /* It should be one of these, but just skip if it happens not to be */
904 if (!IsA(selem, StatsElem))
905 continue;
906
907 name = selem->name;
908
909 if (buflen > 0)
910 buf[buflen++] = '_'; /* insert _ between names */
911
912 /*
913 * We use fixed 'expr' for expressions, which have empty column names.
914 * For indexes this is handled in ChooseIndexColumnNames, but we have
915 * no such function for stats and it does not seem worth adding. If a
916 * better name is needed, the user can specify it explicitly.
917 */
918 if (!name)
919 name = "expr";
920
921 /*
922 * At this point we have buflen <= NAMEDATALEN. name should be less
923 * than NAMEDATALEN already, but use strlcpy for paranoia.
924 */
925 strlcpy(buf + buflen, name, NAMEDATALEN);
926 buflen += strlen(buf + buflen);
927 if (buflen >= NAMEDATALEN)
928 break;
929 }
930 return pstrdup(buf);
931 }
932
933 /*
934 * StatisticsGetRelation: given a statistics object's OID, get the OID of
935 * the relation it is defined on. Uses the system cache.
936 */
937 Oid
938 StatisticsGetRelation(Oid statId, bool missing_ok)
939 {
940 HeapTuple tuple;
941 Form_pg_statistic_ext stx;
942 Oid result;
943
944 tuple = SearchSysCache1(STATEXTOID, ObjectIdGetDatum(statId));
945 if (!HeapTupleIsValid(tuple))
946 {
947 if (missing_ok)
948 return InvalidOid;
949 elog(ERROR, "cache lookup failed for statistics object %u", statId);
950 }
951 stx = (Form_pg_statistic_ext) GETSTRUCT(tuple);
952 Assert(stx->oid == statId);
953
954 result = stx->stxrelid;
955 ReleaseSysCache(tuple);
956 return result;
957 }