LCOV - differential code coverage report
Current view: top level - src/backend/commands - statscmds.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 93.3 % 300 280 20 5 275 3
Current Date: 2026-11-28 16:48:44 +0900 Functions: 100.0 % 8 8 1 7
Baseline: lcov-20261128-baseline Branches: 73.0 % 256 187 1 68 5 182
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 2 2 2
(30,360] days: 94.9 % 39 37 2 5 32
(360..) days: 93.1 % 259 241 18 241
Function coverage date bins:
(30,360] days: 100.0 % 1 1 1
(360..) days: 100.0 % 7 7 7
Branch coverage date bins:
(30,360] days: 78.8 % 52 41 1 10 5 36
(360..) days: 71.6 % 204 146 58 146

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

Generated by: LCOV version 2.0-1