PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
stat_utils.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 * stat_utils.c
3 *
4 * PostgreSQL statistics manipulation utilities.
5 *
6 * Code supporting the direct manipulation of statistics.
7 *
8 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
10 *
11 * IDENTIFICATION
12 * src/backend/statistics/stat_utils.c
13 *
14 *-------------------------------------------------------------------------
15 */
16
17#include "postgres.h"
18
19#include "access/relation.h"
20#include "catalog/index.h"
21#include "catalog/namespace.h"
22#include "catalog/pg_database.h"
23#include "funcapi.h"
24#include "miscadmin.h"
26#include "storage/lmgr.h"
27#include "utils/acl.h"
28#include "utils/array.h"
29#include "utils/builtins.h"
30#include "utils/lsyscache.h"
31#include "utils/rel.h"
32
33/*
34 * Ensure that a given argument is not null.
35 */
36void
38 struct StatsArgInfo *arginfo,
39 int argnum)
40{
41 if (PG_ARGISNULL(argnum))
43 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
44 errmsg("\"%s\" cannot be NULL",
45 arginfo[argnum].argname)));
46}
47
48/*
49 * Check that argument is either NULL or a one dimensional array with no
50 * NULLs.
51 *
52 * If a problem is found, emit a WARNING, and return false. Otherwise return
53 * true.
54 */
55bool
57 struct StatsArgInfo *arginfo,
58 int argnum)
59{
60 ArrayType *arr;
61
62 if (PG_ARGISNULL(argnum))
63 return true;
64
66
67 if (ARR_NDIM(arr) != 1)
68 {
70 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
71 errmsg("\"%s\" cannot be a multidimensional array",
72 arginfo[argnum].argname)));
73 return false;
74 }
75
76 if (array_contains_nulls(arr))
77 {
79 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
80 errmsg("\"%s\" array cannot contain NULL values",
81 arginfo[argnum].argname)));
82 return false;
83 }
84
85 return true;
86}
87
88/*
89 * Enforce parameter pairs that must be specified together (or not at all) for
90 * a particular stakind, such as most_common_vals and most_common_freqs for
91 * STATISTIC_KIND_MCV.
92 *
93 * If a problem is found, emit a WARNING, and return false. Otherwise return
94 * true.
95 */
96bool
98 struct StatsArgInfo *arginfo,
99 int argnum1, int argnum2)
100{
101 if (PG_ARGISNULL(argnum1) && PG_ARGISNULL(argnum2))
102 return true;
103
104 if (PG_ARGISNULL(argnum1) || PG_ARGISNULL(argnum2))
105 {
106 int nullarg = PG_ARGISNULL(argnum1) ? argnum1 : argnum2;
107 int otherarg = PG_ARGISNULL(argnum1) ? argnum2 : argnum1;
108
110 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
111 errmsg("\"%s\" must be specified when \"%s\" is specified",
112 arginfo[nullarg].argname,
113 arginfo[otherarg].argname)));
114
115 return false;
116 }
117
118 return true;
119}
120
121/*
122 * Lock relation in ShareUpdateExclusive mode, check privileges, and close the
123 * relation (but retain the lock).
124 *
125 * A role has privileges to set statistics on the relation if any of the
126 * following are true:
127 * - the role owns the current database and the relation is not shared
128 * - the role has the MAINTAIN privilege on the relation
129 */
130void
132{
134 Oid table_oid = reloid;
135 Oid index_oid = InvalidOid;
136 LOCKMODE index_lockmode = NoLock;
137
138 /*
139 * For indexes, we follow the locking behavior in do_analyze_rel() and
140 * check_lock_if_inplace_updateable_rel(), which is to lock the table
141 * first in ShareUpdateExclusive mode and then the index in AccessShare
142 * mode.
143 *
144 * Partitioned indexes are treated differently than normal indexes in
145 * check_lock_if_inplace_updateable_rel(), so we take a
146 * ShareUpdateExclusive lock on both the partitioned table and the
147 * partitioned index.
148 */
149 switch (get_rel_relkind(reloid))
150 {
151 case RELKIND_INDEX:
152 index_oid = reloid;
153 table_oid = IndexGetRelation(index_oid, false);
154 index_lockmode = AccessShareLock;
155 break;
156 case RELKIND_PARTITIONED_INDEX:
157 index_oid = reloid;
158 table_oid = IndexGetRelation(index_oid, false);
159 index_lockmode = ShareUpdateExclusiveLock;
160 break;
161 default:
162 break;
163 }
164
166
167 /* the relkinds that can be used with ANALYZE */
168 switch (table->rd_rel->relkind)
169 {
170 case RELKIND_RELATION:
171 case RELKIND_MATVIEW:
172 case RELKIND_FOREIGN_TABLE:
173 case RELKIND_PARTITIONED_TABLE:
174 break;
175 default:
177 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
178 errmsg("cannot modify statistics for relation \"%s\"",
180 errdetail_relkind_not_supported(table->rd_rel->relkind)));
181 }
182
183 if (OidIsValid(index_oid))
184 {
186
187 Assert(index_lockmode != NoLock);
188 index = relation_open(index_oid, index_lockmode);
189
190 Assert(index->rd_index && index->rd_index->indrelid == table_oid);
191
192 /* retain lock on index */
194 }
195
196 if (table->rd_rel->relisshared)
198 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
199 errmsg("cannot modify statistics for shared relation")));
200
201 if (!object_ownercheck(DatabaseRelationId, MyDatabaseId, GetUserId()))
202 {
204 GetUserId(),
206
207 if (aclresult != ACLCHECK_OK)
208 aclcheck_error(aclresult,
209 get_relkind_objtype(table->rd_rel->relkind),
210 NameStr(table->rd_rel->relname));
211 }
212
213 /* retain lock on table */
215}
216
217/*
218 * Lookup relation oid from schema and relation name.
219 */
220Oid
221stats_lookup_relid(const char *nspname, const char *relname)
222{
223 Oid nspoid;
224 Oid reloid;
225
226 nspoid = LookupExplicitNamespace(nspname, false);
227 reloid = get_relname_relid(relname, nspoid);
228 if (!OidIsValid(reloid))
231 errmsg("relation \"%s.%s\" does not exist",
232 nspname, relname)));
233
234 return reloid;
235}
236
237
238/*
239 * Find the argument number for the given argument name, returning -1 if not
240 * found.
241 */
242static int
243get_arg_by_name(const char *argname, struct StatsArgInfo *arginfo)
244{
245 int argnum;
246
247 for (argnum = 0; arginfo[argnum].argname != NULL; argnum++)
248 if (pg_strcasecmp(argname, arginfo[argnum].argname) == 0)
249 return argnum;
250
252 (errmsg("unrecognized argument name: \"%s\"", argname)));
253
254 return -1;
255}
256
257/*
258 * Ensure that a given argument matched the expected type.
259 */
260static bool
261stats_check_arg_type(const char *argname, Oid argtype, Oid expectedtype)
262{
263 if (argtype != expectedtype)
264 {
266 (errmsg("argument \"%s\" has type \"%s\", expected type \"%s\"",
267 argname, format_type_be(argtype),
268 format_type_be(expectedtype))));
269 return false;
270 }
271
272 return true;
273}
274
275/*
276 * Translate variadic argument pairs from 'pairs_fcinfo' into a
277 * 'positional_fcinfo' appropriate for calling relation_statistics_update() or
278 * attribute_statistics_update() with positional arguments.
279 *
280 * Caller should have already initialized positional_fcinfo with a size
281 * appropriate for calling the intended positional function, and arginfo
282 * should also match the intended positional function.
283 */
284bool
286 FunctionCallInfo positional_fcinfo,
287 struct StatsArgInfo *arginfo)
288{
289 Datum *args;
290 bool *argnulls;
291 Oid *types;
292 int nargs;
293 bool result = true;
294
295 /* clear positional args */
296 for (int i = 0; arginfo[i].argname != NULL; i++)
297 {
298 positional_fcinfo->args[i].value = (Datum) 0;
299 positional_fcinfo->args[i].isnull = true;
300 }
301
302 nargs = extract_variadic_args(pairs_fcinfo, 0, true,
303 &args, &types, &argnulls);
304
305 if (nargs % 2 != 0)
307 errmsg("variadic arguments must be name/value pairs"),
308 errhint("Provide an even number of variadic arguments that can be divided into pairs."));
309
310 /*
311 * For each argument name/value pair, find corresponding positional
312 * argument for the argument name, and assign the argument value to
313 * positional_fcinfo.
314 */
315 for (int i = 0; i < nargs; i += 2)
316 {
317 int argnum;
318 char *argname;
319
320 if (argnulls[i])
322 (errmsg("name at variadic position %d is NULL", i + 1)));
323
324 if (types[i] != TEXTOID)
326 (errmsg("name at variadic position %d has type \"%s\", expected type \"%s\"",
327 i + 1, format_type_be(types[i]),
328 format_type_be(TEXTOID))));
329
330 if (argnulls[i + 1])
331 continue;
332
333 argname = TextDatumGetCString(args[i]);
334
335 /*
336 * The 'version' argument is a special case, not handled by arginfo
337 * because it's not a valid positional argument.
338 *
339 * For now, 'version' is accepted but ignored. In the future it can be
340 * used to interpret older statistics properly.
341 */
342 if (pg_strcasecmp(argname, "version") == 0)
343 continue;
344
345 argnum = get_arg_by_name(argname, arginfo);
346
347 if (argnum < 0 || !stats_check_arg_type(argname, types[i + 1],
348 arginfo[argnum].argtype))
349 {
350 result = false;
351 continue;
352 }
353
354 positional_fcinfo->args[argnum].value = args[i + 1];
355 positional_fcinfo->args[argnum].isnull = false;
356 }
357
358 return result;
359}
AclResult
Definition: acl.h:182
@ ACLCHECK_OK
Definition: acl.h:183
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2639
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:4075
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4024
#define ARR_NDIM(a)
Definition: array.h:290
#define DatumGetArrayTypeP(X)
Definition: array.h:261
bool array_contains_nulls(ArrayType *array)
Definition: arrayfuncs.c:3767
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define NameStr(name)
Definition: c.h:717
#define OidIsValid(objectId)
Definition: c.h:746
struct typedefs * types
Definition: ecpg.c:30
int errhint(const char *fmt,...)
Definition: elog.c:1318
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define WARNING
Definition: elog.h:36
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
#define PG_GETARG_DATUM(n)
Definition: fmgr.h:268
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
int extract_variadic_args(FunctionCallInfo fcinfo, int variadic_start, bool convert_unknown, Datum **args, Oid **types, bool **nulls)
Definition: funcapi.c:2005
Oid MyDatabaseId
Definition: globals.c:95
Assert(PointerIsAligned(start, uint64))
Oid IndexGetRelation(Oid indexId, bool missing_ok)
Definition: index.c:3583
int i
Definition: isn.c:77
int LOCKMODE
Definition: lockdefs.h:26
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
#define ShareUpdateExclusiveLock
Definition: lockdefs.h:39
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2143
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition: lsyscache.c:2025
Oid GetUserId(void)
Definition: miscinit.c:520
Oid LookupExplicitNamespace(const char *nspname, bool missing_ok)
Definition: namespace.c:3385
ObjectType get_relkind_objtype(char relkind)
#define ACL_MAINTAIN
Definition: parsenodes.h:90
int errdetail_relkind_not_supported(char relkind)
Definition: pg_class.c:24
NameData relname
Definition: pg_class.h:38
static const struct lconv_member_info table[]
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:79
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
uintptr_t Datum
Definition: postgres.h:69
#define InvalidOid
Definition: postgres_ext.h:35
unsigned int Oid
Definition: postgres_ext.h:30
#define RelationGetRelid(relation)
Definition: rel.h:516
#define RelationGetRelationName(relation)
Definition: rel.h:550
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
bool stats_fill_fcinfo_from_arg_pairs(FunctionCallInfo pairs_fcinfo, FunctionCallInfo positional_fcinfo, struct StatsArgInfo *arginfo)
Definition: stat_utils.c:285
static int get_arg_by_name(const char *argname, struct StatsArgInfo *arginfo)
Definition: stat_utils.c:243
static bool stats_check_arg_type(const char *argname, Oid argtype, Oid expectedtype)
Definition: stat_utils.c:261
bool stats_check_arg_array(FunctionCallInfo fcinfo, struct StatsArgInfo *arginfo, int argnum)
Definition: stat_utils.c:56
void stats_check_required_arg(FunctionCallInfo fcinfo, struct StatsArgInfo *arginfo, int argnum)
Definition: stat_utils.c:37
void stats_lock_check_privileges(Oid reloid)
Definition: stat_utils.c:131
Oid stats_lookup_relid(const char *nspname, const char *relname)
Definition: stat_utils.c:221
bool stats_check_arg_pair(FunctionCallInfo fcinfo, struct StatsArgInfo *arginfo, int argnum1, int argnum2)
Definition: stat_utils.c:97
NullableDatum args[FLEXIBLE_ARRAY_MEMBER]
Definition: fmgr.h:95
Datum value
Definition: postgres.h:80
bool isnull
Definition: postgres.h:82
const char * argname
Definition: stat_utils.h:20
Definition: type.h:96