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