Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * extended_stats.c
4 : : * POSTGRES extended statistics
5 : : *
6 : : * Generic code supporting statistics objects created via CREATE STATISTICS.
7 : : *
8 : : *
9 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
10 : : * Portions Copyright (c) 1994, Regents of the University of California
11 : : *
12 : : * IDENTIFICATION
13 : : * src/backend/statistics/extended_stats.c
14 : : *
15 : : *-------------------------------------------------------------------------
16 : : */
17 : : #include "postgres.h"
18 : :
19 : : #include "access/detoast.h"
20 : : #include "access/genam.h"
21 : : #include "access/htup_details.h"
22 : : #include "access/table.h"
23 : : #include "catalog/indexing.h"
24 : : #include "catalog/pg_statistic_ext.h"
25 : : #include "catalog/pg_statistic_ext_data.h"
26 : : #include "commands/defrem.h"
27 : : #include "commands/progress.h"
28 : : #include "executor/executor.h"
29 : : #include "miscadmin.h"
30 : : #include "nodes/nodeFuncs.h"
31 : : #include "optimizer/optimizer.h"
32 : : #include "parser/parsetree.h"
33 : : #include "pgstat.h"
34 : : #include "postmaster/autovacuum.h"
35 : : #include "statistics/extended_stats_internal.h"
36 : : #include "statistics/statistics.h"
37 : : #include "utils/acl.h"
38 : : #include "utils/array.h"
39 : : #include "utils/attoptcache.h"
40 : : #include "utils/builtins.h"
41 : : #include "utils/datum.h"
42 : : #include "utils/fmgroids.h"
43 : : #include "utils/lsyscache.h"
44 : : #include "utils/memutils.h"
45 : : #include "utils/rel.h"
46 : : #include "utils/selfuncs.h"
47 : : #include "utils/syscache.h"
48 : :
49 : : /*
50 : : * To avoid consuming too much memory during analysis and/or too much space
51 : : * in the resulting pg_statistic rows, we ignore varlena datums that are wider
52 : : * than WIDTH_THRESHOLD (after detoasting!). This is legitimate for MCV
53 : : * and distinct-value calculations since a wide value is unlikely to be
54 : : * duplicated at all, much less be a most-common value. For the same reason,
55 : : * ignoring wide values will not affect our estimates of histogram bin
56 : : * boundaries very much.
57 : : */
58 : : #define WIDTH_THRESHOLD 1024
59 : :
60 : : /*
61 : : * Used internally to refer to an individual statistics object, i.e.,
62 : : * a pg_statistic_ext entry.
63 : : */
64 : : typedef struct StatExtEntry
65 : : {
66 : : Oid statOid; /* OID of pg_statistic_ext entry */
67 : : char *schema; /* statistics object's schema */
68 : : char *name; /* statistics object's name */
69 : : Bitmapset *columns; /* attribute numbers covered by the object */
70 : : List *types; /* 'char' list of enabled statistics kinds */
71 : : int stattarget; /* statistics target (-1 for default) */
72 : : List *exprs; /* expressions */
73 : : } StatExtEntry;
74 : :
75 : :
76 : : static List *fetch_statentries_for_relation(Relation pg_statext, Oid relid);
77 : : static VacAttrStats **lookup_var_attr_stats(Bitmapset *attrs, List *exprs,
78 : : int nvacatts, VacAttrStats **vacatts);
79 : : static void statext_store(Oid statOid, bool inh,
80 : : MVNDistinct *ndistinct, MVDependencies *dependencies,
81 : : MCVList *mcv, Datum exprs, VacAttrStats **stats);
82 : : static int statext_compute_stattarget(int stattarget,
83 : : int nattrs, VacAttrStats **stats);
84 : :
85 : : /* Information needed to analyze a single simple expression. */
86 : : typedef struct AnlExprData
87 : : {
88 : : Node *expr; /* expression to analyze */
89 : : VacAttrStats *vacattrstat; /* statistics attrs to analyze */
90 : : } AnlExprData;
91 : :
92 : : static void compute_expr_stats(Relation onerel, AnlExprData *exprdata,
93 : : int nexprs, HeapTuple *rows, int numrows);
94 : : static Datum serialize_expr_stats(AnlExprData *exprdata, int nexprs);
95 : : static Datum expr_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
96 : : static AnlExprData *build_expr_data(List *exprs, int stattarget);
97 : :
98 : : static StatsBuildData *make_build_data(Relation rel, StatExtEntry *stat,
99 : : int numrows, HeapTuple *rows,
100 : : VacAttrStats **stats, int stattarget);
101 : :
102 : :
103 : : /*
104 : : * Compute requested extended stats, using the rows sampled for the plain
105 : : * (single-column) stats.
106 : : *
107 : : * This fetches a list of stats types from pg_statistic_ext, computes the
108 : : * requested stats, and serializes them back into the catalog.
109 : : */
110 : : void
1519 tomas.vondra@postgre 111 :CBC 5791 : BuildRelationExtStatistics(Relation onerel, bool inh, double totalrows,
112 : : int numrows, HeapTuple *rows,
113 : : int natts, VacAttrStats **vacattrstats)
114 : : {
115 : : Relation pg_stext;
116 : : ListCell *lc;
117 : : List *statslist;
118 : : MemoryContext cxt;
119 : : MemoryContext oldcxt;
120 : : int64 ext_cnt;
121 : :
122 : : /* Do nothing if there are no columns to analyze. */
1815 123 [ + + ]: 5791 : if (!natts)
124 : 9 : return;
125 : :
126 : : /* the list of stats has to be allocated outside the memory context */
1636 127 : 5782 : pg_stext = table_open(StatisticExtRelationId, RowExclusiveLock);
128 : 5782 : statslist = fetch_statentries_for_relation(pg_stext, RelationGetRelid(onerel));
129 : :
130 : : /* memory context for building each statistics object */
2910 tgl@sss.pgh.pa.us 131 : 5782 : cxt = AllocSetContextCreate(CurrentMemoryContext,
132 : : "BuildRelationExtStatistics",
133 : : ALLOCSET_DEFAULT_SIZES);
3254 alvherre@alvh.no-ip. 134 : 5782 : oldcxt = MemoryContextSwitchTo(cxt);
135 : :
136 : : /* report this phase */
1815 tomas.vondra@postgre 137 [ + + ]: 5782 : if (statslist != NIL)
138 : : {
2251 alvherre@alvh.no-ip. 139 : 183 : const int index[] = {
140 : : PROGRESS_ANALYZE_PHASE,
141 : : PROGRESS_ANALYZE_EXT_STATS_TOTAL
142 : : };
143 : 366 : const int64 val[] = {
144 : : PROGRESS_ANALYZE_PHASE_COMPUTE_EXT_STATS,
1815 tomas.vondra@postgre 145 : 183 : list_length(statslist)
146 : : };
147 : :
2251 alvherre@alvh.no-ip. 148 : 183 : pgstat_progress_update_multi_param(2, index, val);
149 : : }
150 : :
151 : 5782 : ext_cnt = 0;
1815 tomas.vondra@postgre 152 [ + + + + : 6064 : foreach(lc, statslist)
+ + ]
153 : : {
3224 bruce@momjian.us 154 : 282 : StatExtEntry *stat = (StatExtEntry *) lfirst(lc);
155 : 282 : MVNDistinct *ndistinct = NULL;
3266 simon@2ndQuadrant.co 156 : 282 : MVDependencies *dependencies = NULL;
2545 tomas.vondra@postgre 157 : 282 : MCVList *mcv = NULL;
1815 158 : 282 : Datum exprstats = (Datum) 0;
159 : : VacAttrStats **stats;
160 : : ListCell *lc2;
161 : : int stattarget;
162 : : StatsBuildData *data;
163 : :
164 : : /*
165 : : * Check if we can build these stats based on the column analyzed. If
166 : : * not, report this fact (except in autovacuum) and move on.
167 : : */
432 rguo@postgresql.org 168 : 282 : stats = lookup_var_attr_stats(stat->columns, stat->exprs,
169 : : natts, vacattrstats);
3029 alvherre@alvh.no-ip. 170 [ + + ]: 282 : if (!stats)
171 : : {
741 heikki.linnakangas@i 172 [ + - ]: 8 : if (!AmAutoVacuumWorkerProcess())
3029 alvherre@alvh.no-ip. 173 [ + - ]: 8 : ereport(WARNING,
174 : : (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
175 : : errmsg("statistics object \"%s.%s\" could not be computed for relation \"%s.%s\"",
176 : : stat->schema, stat->name,
177 : : get_namespace_name(onerel->rd_rel->relnamespace),
178 : : RelationGetRelationName(onerel)),
179 : : errtable(onerel)));
3254 180 : 8 : continue;
181 : : }
182 : :
183 : : /* compute statistics target for this statistics object */
2378 tomas.vondra@postgre 184 : 274 : stattarget = statext_compute_stattarget(stat->stattarget,
185 : 274 : bms_num_members(stat->columns),
186 : : stats);
187 : :
188 : : /*
189 : : * Don't rebuild statistics objects with statistics target set to 0
190 : : * (we just leave the existing values around, just like we do for
191 : : * regular per-column statistics).
192 : : */
193 [ + + ]: 274 : if (stattarget == 0)
194 : 3 : continue;
195 : :
196 : : /* evaluate expressions (if the statistics object has any) */
1815 197 : 271 : data = make_build_data(onerel, stat, numrows, rows, stats, stattarget);
198 : :
199 : : /* compute statistic of each requested type */
3278 alvherre@alvh.no-ip. 200 [ + - + + : 799 : foreach(lc2, stat->types)
+ + ]
201 : : {
3224 bruce@momjian.us 202 : 528 : char t = (char) lfirst_int(lc2);
203 : :
3278 alvherre@alvh.no-ip. 204 [ + + ]: 528 : if (t == STATS_EXT_NDISTINCT)
1815 tomas.vondra@postgre 205 : 139 : ndistinct = statext_ndistinct_build(totalrows, data);
3266 simon@2ndQuadrant.co 206 [ + + ]: 389 : else if (t == STATS_EXT_DEPENDENCIES)
1815 tomas.vondra@postgre 207 : 112 : dependencies = statext_dependencies_build(data);
2545 208 [ + + ]: 277 : else if (t == STATS_EXT_MCV)
1815 209 : 151 : mcv = statext_mcv_build(data, totalrows, stattarget);
210 [ + - ]: 126 : else if (t == STATS_EXT_EXPRESSIONS)
211 : : {
212 : : AnlExprData *exprdata;
213 : : int nexprs;
214 : :
215 : : /* should not happen, thanks to checks when defining stats */
216 [ - + ]: 126 : if (!stat->exprs)
1815 tomas.vondra@postgre 217 [ # # ]:UBC 0 : elog(ERROR, "requested expression stats, but there are no expressions");
218 : :
1815 tomas.vondra@postgre 219 :CBC 126 : exprdata = build_expr_data(stat->exprs, stattarget);
220 : 126 : nexprs = list_length(stat->exprs);
221 : :
443 drowley@postgresql.o 222 : 126 : compute_expr_stats(onerel, exprdata, nexprs, rows, numrows);
223 : :
1815 tomas.vondra@postgre 224 : 126 : exprstats = serialize_expr_stats(exprdata, nexprs);
225 : : }
226 : : }
227 : :
228 : : /* store the statistics in the catalog */
1519 229 : 271 : statext_store(stat->statOid, inh,
230 : : ndistinct, dependencies, mcv, exprstats, stats);
231 : :
232 : : /* for reporting progress */
2251 alvherre@alvh.no-ip. 233 : 271 : pgstat_progress_update_param(PROGRESS_ANALYZE_EXT_STATS_COMPUTED,
234 : : ++ext_cnt);
235 : :
236 : : /* free the data used for building this statistics object */
1636 tomas.vondra@postgre 237 : 271 : MemoryContextReset(cxt);
238 : : }
239 : :
3254 alvherre@alvh.no-ip. 240 : 5782 : MemoryContextSwitchTo(oldcxt);
241 : 5782 : MemoryContextDelete(cxt);
242 : :
1636 tomas.vondra@postgre 243 : 5782 : list_free(statslist);
244 : :
245 : 5782 : table_close(pg_stext, RowExclusiveLock);
246 : : }
247 : :
248 : : /*
249 : : * ComputeExtStatisticsRows
250 : : * Compute number of rows required by extended statistics on a table.
251 : : *
252 : : * Computes number of rows we need to sample to build extended statistics on a
253 : : * table. This only looks at statistics we can actually build - for example
254 : : * when analyzing only some of the columns, this will skip statistics objects
255 : : * that would require additional columns.
256 : : *
257 : : * See statext_compute_stattarget for details about how we compute the
258 : : * statistics target for a statistics object (from the object target,
259 : : * attribute targets and default statistics target).
260 : : */
261 : : int
2378 262 : 8488 : ComputeExtStatisticsRows(Relation onerel,
263 : : int natts, VacAttrStats **vacattrstats)
264 : : {
265 : : Relation pg_stext;
266 : : ListCell *lc;
267 : : List *lstats;
268 : : MemoryContext cxt;
269 : : MemoryContext oldcxt;
270 : 8488 : int result = 0;
271 : :
272 : : /* If there are no columns to analyze, just return 0. */
1815 273 [ + + ]: 8488 : if (!natts)
274 : 36 : return 0;
275 : :
2378 276 : 8452 : cxt = AllocSetContextCreate(CurrentMemoryContext,
277 : : "ComputeExtStatisticsRows",
278 : : ALLOCSET_DEFAULT_SIZES);
279 : 8452 : oldcxt = MemoryContextSwitchTo(cxt);
280 : :
281 : 8452 : pg_stext = table_open(StatisticExtRelationId, RowExclusiveLock);
282 : 8452 : lstats = fetch_statentries_for_relation(pg_stext, RelationGetRelid(onerel));
283 : :
284 [ + + + + : 8734 : foreach(lc, lstats)
+ + ]
285 : : {
2131 tgl@sss.pgh.pa.us 286 : 282 : StatExtEntry *stat = (StatExtEntry *) lfirst(lc);
287 : : int stattarget;
288 : : VacAttrStats **stats;
289 : 282 : int nattrs = bms_num_members(stat->columns);
290 : :
291 : : /*
292 : : * Check if we can build this statistics object based on the columns
293 : : * analyzed. If not, ignore it (don't report anything, we'll do that
294 : : * during the actual build BuildRelationExtStatistics).
295 : : */
432 rguo@postgresql.org 296 : 282 : stats = lookup_var_attr_stats(stat->columns, stat->exprs,
297 : : natts, vacattrstats);
298 : :
2378 tomas.vondra@postgre 299 [ + + ]: 282 : if (!stats)
300 : 8 : continue;
301 : :
302 : : /*
303 : : * Compute statistics target, based on what's set for the statistic
304 : : * object itself, and for its attributes.
305 : : */
306 : 274 : stattarget = statext_compute_stattarget(stat->stattarget,
307 : : nattrs, stats);
308 : :
309 : : /* Use the largest value for all statistics objects. */
310 [ + + ]: 274 : if (stattarget > result)
311 : 172 : result = stattarget;
312 : : }
313 : :
314 : 8452 : table_close(pg_stext, RowExclusiveLock);
315 : :
316 : 8452 : MemoryContextSwitchTo(oldcxt);
317 : 8452 : MemoryContextDelete(cxt);
318 : :
319 : : /* compute sample size based on the statistics target */
320 : 8452 : return (300 * result);
321 : : }
322 : :
323 : : /*
324 : : * statext_compute_stattarget
325 : : * compute statistics target for an extended statistic
326 : : *
327 : : * When computing target for extended statistics objects, we consider three
328 : : * places where the target may be set - the statistics object itself,
329 : : * attributes the statistics object is defined on, and then the default
330 : : * statistics target.
331 : : *
332 : : * First we look at what's set for the statistics object itself, using the
333 : : * ALTER STATISTICS ... SET STATISTICS command. If we find a valid value
334 : : * there (i.e. not -1) we're done. Otherwise we look at targets set for any
335 : : * of the attributes the statistic is defined on, and if there are columns
336 : : * with defined target, we use the maximum value. We do this mostly for
337 : : * backwards compatibility, because this is what we did before having
338 : : * statistics target for extended statistics.
339 : : *
340 : : * And finally, if we still don't have a statistics target, we use the value
341 : : * set in default_statistics_target.
342 : : */
343 : : static int
344 : 548 : statext_compute_stattarget(int stattarget, int nattrs, VacAttrStats **stats)
345 : : {
346 : : int i;
347 : :
348 : : /*
349 : : * If there's statistics target set for the statistics object, use it. It
350 : : * may be set to 0 which disables building of that statistic.
351 : : */
352 [ + + ]: 548 : if (stattarget >= 0)
353 : 6 : return stattarget;
354 : :
355 : : /*
356 : : * The target for the statistics object is set to -1, in which case we
357 : : * look at the maximum target set for any of the attributes the object is
358 : : * defined on.
359 : : */
360 [ + + ]: 1416 : for (i = 0; i < nattrs; i++)
361 : : {
362 : : /* keep the maximum statistics target */
986 peter@eisentraut.org 363 [ + + ]: 874 : if (stats[i]->attstattarget > stattarget)
364 : 404 : stattarget = stats[i]->attstattarget;
365 : : }
366 : :
367 : : /*
368 : : * If the value is still negative (so neither the statistics object nor
369 : : * any of the columns have custom statistics target set), use the global
370 : : * default target.
371 : : */
2378 tomas.vondra@postgre 372 [ + + ]: 542 : if (stattarget < 0)
373 : 138 : stattarget = default_statistics_target;
374 : :
375 : : /* As this point we should have a valid statistics target. */
986 peter@eisentraut.org 376 [ + - - + ]: 542 : Assert((stattarget >= 0) && (stattarget <= MAX_STATISTICS_TARGET));
377 : :
2378 tomas.vondra@postgre 378 : 542 : return stattarget;
379 : : }
380 : :
381 : : /*
382 : : * statext_is_kind_built
383 : : * Is this stat kind built in the given pg_statistic_ext_data tuple?
384 : : */
385 : : bool
3278 alvherre@alvh.no-ip. 386 : 4044 : statext_is_kind_built(HeapTuple htup, char type)
387 : : {
388 : : AttrNumber attnum;
389 : :
390 [ + + + + : 4044 : switch (type)
- ]
391 : : {
392 : 1011 : case STATS_EXT_NDISTINCT:
2467 tomas.vondra@postgre 393 : 1011 : attnum = Anum_pg_statistic_ext_data_stxdndistinct;
3278 alvherre@alvh.no-ip. 394 : 1011 : break;
395 : :
3266 simon@2ndQuadrant.co 396 : 1011 : case STATS_EXT_DEPENDENCIES:
2467 tomas.vondra@postgre 397 : 1011 : attnum = Anum_pg_statistic_ext_data_stxddependencies;
3266 simon@2ndQuadrant.co 398 : 1011 : break;
399 : :
2545 tomas.vondra@postgre 400 : 1011 : case STATS_EXT_MCV:
2467 401 : 1011 : attnum = Anum_pg_statistic_ext_data_stxdmcv;
2545 402 : 1011 : break;
403 : :
1815 404 : 1011 : case STATS_EXT_EXPRESSIONS:
405 : 1011 : attnum = Anum_pg_statistic_ext_data_stxdexpr;
406 : 1011 : break;
407 : :
3278 alvherre@alvh.no-ip. 408 :UBC 0 : default:
409 [ # # ]: 0 : elog(ERROR, "unexpected statistics type requested: %d", type);
410 : : }
411 : :
2909 andrew@dunslane.net 412 :CBC 4044 : return !heap_attisnull(htup, attnum, NULL);
413 : : }
414 : :
415 : : /*
416 : : * Return a list (of StatExtEntry) of statistics objects for the given relation.
417 : : */
418 : : static List *
3278 alvherre@alvh.no-ip. 419 : 14234 : fetch_statentries_for_relation(Relation pg_statext, Oid relid)
420 : : {
421 : : SysScanDesc scan;
422 : : ScanKeyData skey;
423 : : HeapTuple htup;
3224 bruce@momjian.us 424 : 14234 : List *result = NIL;
425 : :
426 : : /*
427 : : * Prepare to scan pg_statistic_ext for entries having stxrelid = this
428 : : * rel.
429 : : */
3278 alvherre@alvh.no-ip. 430 : 14234 : ScanKeyInit(&skey,
431 : : Anum_pg_statistic_ext_stxrelid,
432 : : BTEqualStrategyNumber, F_OIDEQ,
433 : : ObjectIdGetDatum(relid));
434 : :
435 : 14234 : scan = systable_beginscan(pg_statext, StatisticExtRelidIndexId, true,
436 : : NULL, 1, &skey);
437 : :
438 [ + + ]: 14798 : while (HeapTupleIsValid(htup = systable_getnext(scan)))
439 : : {
440 : : StatExtEntry *entry;
441 : : Datum datum;
442 : : bool isnull;
443 : : int i;
444 : : ArrayType *arr;
445 : : char *enabled;
446 : : Form_pg_statistic_ext staForm;
1815 tomas.vondra@postgre 447 : 564 : List *exprs = NIL;
448 : :
95 michael@paquier.xyz 449 :GNC 564 : entry = palloc0_object(StatExtEntry);
3278 alvherre@alvh.no-ip. 450 :CBC 564 : staForm = (Form_pg_statistic_ext) GETSTRUCT(htup);
2672 andres@anarazel.de 451 : 564 : entry->statOid = staForm->oid;
3254 alvherre@alvh.no-ip. 452 : 564 : entry->schema = get_namespace_name(staForm->stxnamespace);
453 : 564 : entry->name = pstrdup(NameStr(staForm->stxname));
454 [ + + ]: 1480 : for (i = 0; i < staForm->stxkeys.dim1; i++)
455 : : {
3278 456 : 916 : entry->columns = bms_add_member(entry->columns,
3254 457 : 916 : staForm->stxkeys.values[i]);
458 : : }
459 : :
728 peter@eisentraut.org 460 : 564 : datum = SysCacheGetAttr(STATEXTOID, htup, Anum_pg_statistic_ext_stxstattarget, &isnull);
461 [ + + ]: 564 : entry->stattarget = isnull ? -1 : DatumGetInt16(datum);
462 : :
463 : : /* decode the stxkind char array into a list of chars */
1086 dgustafsson@postgres 464 : 564 : datum = SysCacheGetAttrNotNull(STATEXTOID, htup,
465 : : Anum_pg_statistic_ext_stxkind);
3278 alvherre@alvh.no-ip. 466 : 564 : arr = DatumGetArrayTypeP(datum);
467 [ + - ]: 564 : if (ARR_NDIM(arr) != 1 ||
468 [ + - ]: 564 : ARR_HASNULL(arr) ||
469 [ - + ]: 564 : ARR_ELEMTYPE(arr) != CHAROID)
3254 alvherre@alvh.no-ip. 470 [ # # ]:UBC 0 : elog(ERROR, "stxkind is not a 1-D char array");
3278 alvherre@alvh.no-ip. 471 [ - + ]:CBC 564 : enabled = (char *) ARR_DATA_PTR(arr);
472 [ + + ]: 1688 : for (i = 0; i < ARR_DIMS(arr)[0]; i++)
473 : : {
3266 simon@2ndQuadrant.co 474 [ + + + + : 1124 : Assert((enabled[i] == STATS_EXT_NDISTINCT) ||
+ + - + ]
475 : : (enabled[i] == STATS_EXT_DEPENDENCIES) ||
476 : : (enabled[i] == STATS_EXT_MCV) ||
477 : : (enabled[i] == STATS_EXT_EXPRESSIONS));
3278 alvherre@alvh.no-ip. 478 : 1124 : entry->types = lappend_int(entry->types, (int) enabled[i]);
479 : : }
480 : :
481 : : /* decode expression (if any) */
1815 tomas.vondra@postgre 482 : 564 : datum = SysCacheGetAttr(STATEXTOID, htup,
483 : : Anum_pg_statistic_ext_stxexprs, &isnull);
484 : :
485 [ + + ]: 564 : if (!isnull)
486 : : {
487 : : char *exprsString;
488 : :
489 : 254 : exprsString = TextDatumGetCString(datum);
490 : 254 : exprs = (List *) stringToNode(exprsString);
491 : :
492 : 254 : pfree(exprsString);
493 : :
494 : : /*
495 : : * Run the expressions through eval_const_expressions. This is not
496 : : * just an optimization, but is necessary, because the planner
497 : : * will be comparing them to similarly-processed qual clauses, and
498 : : * may fail to detect valid matches without this. We must not use
499 : : * canonicalize_qual, however, since these aren't qual
500 : : * expressions.
501 : : */
502 : 254 : exprs = (List *) eval_const_expressions(NULL, (Node *) exprs);
503 : :
504 : : /* May as well fix opfuncids too */
505 : 254 : fix_opfuncids((Node *) exprs);
506 : : }
507 : :
508 : 564 : entry->exprs = exprs;
509 : :
3278 alvherre@alvh.no-ip. 510 : 564 : result = lappend(result, entry);
511 : : }
512 : :
513 : 14234 : systable_endscan(scan);
514 : :
515 : 14234 : return result;
516 : : }
517 : :
518 : : /*
519 : : * examine_attribute -- pre-analysis of a single column
520 : : *
521 : : * Determine whether the column is analyzable; if so, create and initialize
522 : : * a VacAttrStats struct for it. If not, return NULL.
523 : : */
524 : : static VacAttrStats *
1815 tomas.vondra@postgre 525 : 452 : examine_attribute(Node *expr)
526 : : {
527 : : HeapTuple typtuple;
528 : : VacAttrStats *stats;
529 : : int i;
530 : : bool ok;
531 : :
532 : : /*
533 : : * Create the VacAttrStats struct.
534 : : */
95 michael@paquier.xyz 535 :GNC 452 : stats = palloc0_object(VacAttrStats);
986 peter@eisentraut.org 536 :CBC 452 : stats->attstattarget = -1;
537 : :
538 : : /*
539 : : * When analyzing an expression, believe the expression tree's type not
540 : : * the column datatype --- the latter might be the opckeytype storage type
541 : : * of the opclass, which is not interesting for our purposes. (Note: if
542 : : * we did anything with non-expression statistics columns, we'd need to
543 : : * figure out where to get the correct type info from, but for now that's
544 : : * not a problem.) It's not clear whether anyone will care about the
545 : : * typmod, but we store that too just in case.
546 : : */
1815 tomas.vondra@postgre 547 : 452 : stats->attrtypid = exprType(expr);
548 : 452 : stats->attrtypmod = exprTypmod(expr);
549 : 452 : stats->attrcollid = exprCollation(expr);
550 : :
551 : 452 : typtuple = SearchSysCacheCopy1(TYPEOID,
552 : : ObjectIdGetDatum(stats->attrtypid));
553 [ - + ]: 452 : if (!HeapTupleIsValid(typtuple))
1815 tomas.vondra@postgre 554 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
1815 tomas.vondra@postgre 555 :CBC 452 : stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
556 : :
557 : : /*
558 : : * We don't actually analyze individual attributes, so no need to set the
559 : : * memory context.
560 : : */
561 : 452 : stats->anl_context = NULL;
562 : 452 : stats->tupattnum = InvalidAttrNumber;
563 : :
564 : : /*
565 : : * The fields describing the stats->stavalues[n] element types default to
566 : : * the type of the data being analyzed, but the type-specific typanalyze
567 : : * function can change them if it wants to store something else.
568 : : */
569 [ + + ]: 2712 : for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
570 : : {
571 : 2260 : stats->statypid[i] = stats->attrtypid;
572 : 2260 : stats->statyplen[i] = stats->attrtype->typlen;
573 : 2260 : stats->statypbyval[i] = stats->attrtype->typbyval;
574 : 2260 : stats->statypalign[i] = stats->attrtype->typalign;
575 : : }
576 : :
577 : : /*
578 : : * Call the type-specific typanalyze function. If none is specified, use
579 : : * std_typanalyze().
580 : : */
581 [ + + ]: 452 : if (OidIsValid(stats->attrtype->typanalyze))
582 : 34 : ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
583 : : PointerGetDatum(stats)));
584 : : else
585 : 418 : ok = std_typanalyze(stats);
586 : :
587 [ + + + - : 452 : if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
- + ]
588 : : {
589 : 2 : heap_freetuple(typtuple);
590 : 2 : pfree(stats);
591 : 2 : return NULL;
592 : : }
593 : :
594 : 450 : return stats;
595 : : }
596 : :
597 : : /*
598 : : * examine_expression -- pre-analysis of a single expression
599 : : *
600 : : * Determine whether the expression is analyzable; if so, create and initialize
601 : : * a VacAttrStats struct for it. If not, return NULL.
602 : : */
603 : : static VacAttrStats *
604 : 450 : examine_expression(Node *expr, int stattarget)
605 : : {
606 : : HeapTuple typtuple;
607 : : VacAttrStats *stats;
608 : : int i;
609 : : bool ok;
610 : :
611 [ - + ]: 450 : Assert(expr != NULL);
612 : :
613 : : /*
614 : : * Create the VacAttrStats struct.
615 : : */
95 michael@paquier.xyz 616 :GNC 450 : stats = palloc0_object(VacAttrStats);
617 : :
618 : : /*
619 : : * We can't have statistics target specified for the expression, so we
620 : : * could use either the default_statistics_target, or the target computed
621 : : * for the extended statistics. The second option seems more reasonable.
622 : : */
986 peter@eisentraut.org 623 :CBC 450 : stats->attstattarget = stattarget;
624 : :
625 : : /*
626 : : * When analyzing an expression, believe the expression tree's type.
627 : : */
1815 tomas.vondra@postgre 628 : 450 : stats->attrtypid = exprType(expr);
629 : 450 : stats->attrtypmod = exprTypmod(expr);
630 : :
631 : : /*
632 : : * We don't allow collation to be specified in CREATE STATISTICS, so we
633 : : * have to use the collation specified for the expression. It's possible
634 : : * to specify the collation in the expression "(col COLLATE "en_US")" in
635 : : * which case exprCollation() does the right thing.
636 : : */
637 : 450 : stats->attrcollid = exprCollation(expr);
638 : :
639 : 450 : typtuple = SearchSysCacheCopy1(TYPEOID,
640 : : ObjectIdGetDatum(stats->attrtypid));
641 [ - + ]: 450 : if (!HeapTupleIsValid(typtuple))
1815 tomas.vondra@postgre 642 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
643 : :
1815 tomas.vondra@postgre 644 :CBC 450 : stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
645 : 450 : stats->anl_context = CurrentMemoryContext; /* XXX should be using
646 : : * something else? */
647 : 450 : stats->tupattnum = InvalidAttrNumber;
648 : :
649 : : /*
650 : : * The fields describing the stats->stavalues[n] element types default to
651 : : * the type of the data being analyzed, but the type-specific typanalyze
652 : : * function can change them if it wants to store something else.
653 : : */
654 [ + + ]: 2700 : for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
655 : : {
656 : 2250 : stats->statypid[i] = stats->attrtypid;
657 : 2250 : stats->statyplen[i] = stats->attrtype->typlen;
658 : 2250 : stats->statypbyval[i] = stats->attrtype->typbyval;
659 : 2250 : stats->statypalign[i] = stats->attrtype->typalign;
660 : : }
661 : :
662 : : /*
663 : : * Call the type-specific typanalyze function. If none is specified, use
664 : : * std_typanalyze().
665 : : */
666 [ + + ]: 450 : if (OidIsValid(stats->attrtype->typanalyze))
667 : 32 : ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
668 : : PointerGetDatum(stats)));
669 : : else
670 : 418 : ok = std_typanalyze(stats);
671 : :
672 [ + - + - : 450 : if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
- + ]
673 : : {
1815 tomas.vondra@postgre 674 :UBC 0 : heap_freetuple(typtuple);
675 : 0 : pfree(stats);
676 : 0 : return NULL;
677 : : }
678 : :
1815 tomas.vondra@postgre 679 :CBC 450 : return stats;
680 : : }
681 : :
682 : : /*
683 : : * Using 'vacatts' of size 'nvacatts' as input data, return a newly-built
684 : : * VacAttrStats array which includes only the items corresponding to
685 : : * attributes indicated by 'attrs'. If we don't have all of the per-column
686 : : * stats available to compute the extended stats, then we return NULL to
687 : : * indicate to the caller that the stats should not be built.
688 : : */
689 : : static VacAttrStats **
432 rguo@postgresql.org 690 : 564 : lookup_var_attr_stats(Bitmapset *attrs, List *exprs,
691 : : int nvacatts, VacAttrStats **vacatts)
692 : : {
3278 alvherre@alvh.no-ip. 693 : 564 : int i = 0;
694 : 564 : int x = -1;
695 : : int natts;
696 : : VacAttrStats **stats;
697 : : ListCell *lc;
698 : :
1815 tomas.vondra@postgre 699 : 564 : natts = bms_num_members(attrs) + list_length(exprs);
700 : :
701 : 564 : stats = (VacAttrStats **) palloc(natts * sizeof(VacAttrStats *));
702 : :
703 : : /* lookup VacAttrStats info for the requested columns (same attnum) */
3278 alvherre@alvh.no-ip. 704 [ + + ]: 1460 : while ((x = bms_next_member(attrs, x)) >= 0)
705 : : {
706 : : int j;
707 : :
708 : 910 : stats[i] = NULL;
3254 709 [ + + ]: 2582 : for (j = 0; j < nvacatts; j++)
710 : : {
711 [ + + ]: 2568 : if (x == vacatts[j]->tupattnum)
712 : : {
713 : 896 : stats[i] = vacatts[j];
3278 714 : 896 : break;
715 : : }
716 : : }
717 : :
718 [ + + ]: 910 : if (!stats[i])
719 : : {
720 : : /*
721 : : * Looks like stats were not gathered for one of the columns
722 : : * required. We'll be unable to build the extended stats without
723 : : * this column.
724 : : */
3254 725 : 14 : pfree(stats);
726 : 14 : return NULL;
727 : : }
728 : :
3278 729 : 896 : i++;
730 : : }
731 : :
732 : : /* also add info for expressions */
1815 tomas.vondra@postgre 733 [ + + + + : 1000 : foreach(lc, exprs)
+ + ]
734 : : {
735 : 452 : Node *expr = (Node *) lfirst(lc);
736 : :
737 : 452 : stats[i] = examine_attribute(expr);
738 : :
739 : : /*
740 : : * If the expression has been found as non-analyzable, give up. We
741 : : * will not be able to build extended stats with it.
742 : : */
13 michael@paquier.xyz 743 [ + + ]: 452 : if (stats[i] == NULL)
744 : : {
745 : 2 : pfree(stats);
746 : 2 : return NULL;
747 : : }
748 : :
749 : : /*
750 : : * XXX We need tuple descriptor later, and we just grab it from
751 : : * stats[0]->tupDesc (see e.g. statext_mcv_build). But as coded
752 : : * examine_attribute does not set that, so just grab it from the first
753 : : * vacatts element.
754 : : */
1815 tomas.vondra@postgre 755 : 450 : stats[i]->tupDesc = vacatts[0]->tupDesc;
756 : :
757 : 450 : i++;
758 : : }
759 : :
3278 alvherre@alvh.no-ip. 760 : 548 : return stats;
761 : : }
762 : :
763 : : /*
764 : : * statext_store
765 : : * Serializes the statistics and stores them into the pg_statistic_ext_data
766 : : * tuple.
767 : : */
768 : : static void
1519 tomas.vondra@postgre 769 : 271 : statext_store(Oid statOid, bool inh,
770 : : MVNDistinct *ndistinct, MVDependencies *dependencies,
771 : : MCVList *mcv, Datum exprs, VacAttrStats **stats)
772 : : {
773 : : Relation pg_stextdata;
774 : : HeapTuple stup;
775 : : Datum values[Natts_pg_statistic_ext_data];
776 : : bool nulls[Natts_pg_statistic_ext_data];
777 : :
2175 tgl@sss.pgh.pa.us 778 : 271 : pg_stextdata = table_open(StatisticExtDataRelationId, RowExclusiveLock);
779 : :
3028 alvherre@alvh.no-ip. 780 : 271 : memset(nulls, true, sizeof(nulls));
781 : 271 : memset(values, 0, sizeof(values));
782 : :
783 : : /* basic info */
1519 tomas.vondra@postgre 784 : 271 : values[Anum_pg_statistic_ext_data_stxoid - 1] = ObjectIdGetDatum(statOid);
785 : 271 : nulls[Anum_pg_statistic_ext_data_stxoid - 1] = false;
786 : :
787 : 271 : values[Anum_pg_statistic_ext_data_stxdinherit - 1] = BoolGetDatum(inh);
788 : 271 : nulls[Anum_pg_statistic_ext_data_stxdinherit - 1] = false;
789 : :
790 : : /*
791 : : * Construct a new pg_statistic_ext_data tuple, replacing the calculated
792 : : * stats.
793 : : */
3278 alvherre@alvh.no-ip. 794 [ + + ]: 271 : if (ndistinct != NULL)
795 : : {
796 : 139 : bytea *data = statext_ndistinct_serialize(ndistinct);
797 : :
2467 tomas.vondra@postgre 798 : 139 : nulls[Anum_pg_statistic_ext_data_stxdndistinct - 1] = (data == NULL);
799 : 139 : values[Anum_pg_statistic_ext_data_stxdndistinct - 1] = PointerGetDatum(data);
800 : : }
801 : :
3266 simon@2ndQuadrant.co 802 [ + + ]: 271 : if (dependencies != NULL)
803 : : {
804 : 103 : bytea *data = statext_dependencies_serialize(dependencies);
805 : :
2467 tomas.vondra@postgre 806 : 103 : nulls[Anum_pg_statistic_ext_data_stxddependencies - 1] = (data == NULL);
807 : 103 : values[Anum_pg_statistic_ext_data_stxddependencies - 1] = PointerGetDatum(data);
808 : : }
2545 809 [ + + ]: 271 : if (mcv != NULL)
810 : : {
811 : 151 : bytea *data = statext_mcv_serialize(mcv, stats);
812 : :
2467 813 : 151 : nulls[Anum_pg_statistic_ext_data_stxdmcv - 1] = (data == NULL);
814 : 151 : values[Anum_pg_statistic_ext_data_stxdmcv - 1] = PointerGetDatum(data);
815 : : }
1815 816 [ + + ]: 271 : if (exprs != (Datum) 0)
817 : : {
818 : 126 : nulls[Anum_pg_statistic_ext_data_stxdexpr - 1] = false;
819 : 126 : values[Anum_pg_statistic_ext_data_stxdexpr - 1] = exprs;
820 : : }
821 : :
822 : : /*
823 : : * Delete the old tuple if it exists, and insert a new one. It's easier
824 : : * than trying to update or insert, based on various conditions.
825 : : */
1519 826 : 271 : RemoveStatisticsDataById(statOid, inh);
827 : :
828 : : /* form and insert a new tuple */
829 : 271 : stup = heap_form_tuple(RelationGetDescr(pg_stextdata), values, nulls);
830 : 271 : CatalogTupleInsert(pg_stextdata, stup);
831 : :
3278 alvherre@alvh.no-ip. 832 : 271 : heap_freetuple(stup);
833 : :
2467 tomas.vondra@postgre 834 : 271 : table_close(pg_stextdata, RowExclusiveLock);
3278 alvherre@alvh.no-ip. 835 : 271 : }
836 : :
837 : : /* initialize multi-dimensional sort */
838 : : MultiSortSupport
839 : 1120 : multi_sort_init(int ndims)
840 : : {
841 : : MultiSortSupport mss;
842 : :
843 [ - + ]: 1120 : Assert(ndims >= 2);
844 : :
845 : 1120 : mss = (MultiSortSupport) palloc0(offsetof(MultiSortSupportData, ssup)
3189 tgl@sss.pgh.pa.us 846 : 1120 : + sizeof(SortSupportData) * ndims);
847 : :
3278 alvherre@alvh.no-ip. 848 : 1120 : mss->ndims = ndims;
849 : :
850 : 1120 : return mss;
851 : : }
852 : :
853 : : /*
854 : : * Prepare sort support info using the given sort operator and collation
855 : : * at the position 'sortdim'
856 : : */
857 : : void
2648 tgl@sss.pgh.pa.us 858 : 2666 : multi_sort_add_dimension(MultiSortSupport mss, int sortdim,
859 : : Oid oper, Oid collation)
860 : : {
3224 bruce@momjian.us 861 : 2666 : SortSupport ssup = &mss->ssup[sortdim];
862 : :
3278 alvherre@alvh.no-ip. 863 : 2666 : ssup->ssup_cxt = CurrentMemoryContext;
2648 tgl@sss.pgh.pa.us 864 : 2666 : ssup->ssup_collation = collation;
3278 alvherre@alvh.no-ip. 865 : 2666 : ssup->ssup_nulls_first = false;
866 : :
867 : 2666 : PrepareSortSupportFromOrderingOp(oper, ssup);
868 : 2666 : }
869 : :
870 : : /* compare all the dimensions in the selected order */
871 : : int
872 : 11574263 : multi_sort_compare(const void *a, const void *b, void *arg)
873 : : {
874 : 11574263 : MultiSortSupport mss = (MultiSortSupport) arg;
62 peter@eisentraut.org 875 :GNC 11574263 : const SortItem *ia = a;
876 : 11574263 : const SortItem *ib = b;
877 : : int i;
878 : :
3278 alvherre@alvh.no-ip. 879 [ + + ]:CBC 21359562 : for (i = 0; i < mss->ndims; i++)
880 : : {
881 : : int compare;
882 : :
883 : 18890107 : compare = ApplySortComparator(ia->values[i], ia->isnull[i],
884 : 18890107 : ib->values[i], ib->isnull[i],
885 : 18890107 : &mss->ssup[i]);
886 : :
887 [ + + ]: 18890107 : if (compare != 0)
888 : 9104808 : return compare;
889 : : }
890 : :
891 : : /* equal by default */
892 : 2469455 : return 0;
893 : : }
894 : :
895 : : /* compare selected dimension */
896 : : int
897 : 736980 : multi_sort_compare_dim(int dim, const SortItem *a, const SortItem *b,
898 : : MultiSortSupport mss)
899 : : {
900 : 1473960 : return ApplySortComparator(a->values[dim], a->isnull[dim],
901 : 736980 : b->values[dim], b->isnull[dim],
902 : 736980 : &mss->ssup[dim]);
903 : : }
904 : :
905 : : int
906 : 754021 : multi_sort_compare_dims(int start, int end,
907 : : const SortItem *a, const SortItem *b,
908 : : MultiSortSupport mss)
909 : : {
910 : : int dim;
911 : :
912 [ + + ]: 1704292 : for (dim = start; dim <= end; dim++)
913 : : {
914 : 967312 : int r = ApplySortComparator(a->values[dim], a->isnull[dim],
915 : 967312 : b->values[dim], b->isnull[dim],
916 : 967312 : &mss->ssup[dim]);
917 : :
918 [ + + ]: 967312 : if (r != 0)
919 : 17041 : return r;
920 : : }
921 : :
922 : 736980 : return 0;
923 : : }
924 : :
925 : : int
2545 tomas.vondra@postgre 926 : 108788 : compare_scalars_simple(const void *a, const void *b, void *arg)
927 : : {
48 peter@eisentraut.org 928 :GNC 108788 : return compare_datums_simple(*(const Datum *) a,
929 : : *(const Datum *) b,
930 : : (SortSupport) arg);
931 : : }
932 : :
933 : : int
2545 tomas.vondra@postgre 934 :CBC 137784 : compare_datums_simple(Datum a, Datum b, SortSupport ssup)
935 : : {
936 : 137784 : return ApplySortComparator(a, false, b, false, ssup);
937 : : }
938 : :
939 : : /*
940 : : * build_attnums_array
941 : : * Transforms a bitmap into an array of AttrNumber values.
942 : : *
943 : : * This is used for extended statistics only, so all the attributes must be
944 : : * user-defined. That means offsetting by FirstLowInvalidHeapAttributeNumber
945 : : * is not necessary here (and when querying the bitmap).
946 : : */
947 : : AttrNumber *
1815 tomas.vondra@postgre 948 :UBC 0 : build_attnums_array(Bitmapset *attrs, int nexprs, int *numattrs)
949 : : {
950 : : int i,
951 : : j;
952 : : AttrNumber *attnums;
2545 953 : 0 : int num = bms_num_members(attrs);
954 : :
955 [ # # ]: 0 : if (numattrs)
956 : 0 : *numattrs = num;
957 : :
958 : : /* build attnums from the bitmapset */
95 michael@paquier.xyz 959 :UNC 0 : attnums = palloc_array(AttrNumber, num);
2545 tomas.vondra@postgre 960 :UBC 0 : i = 0;
961 : 0 : j = -1;
962 [ # # ]: 0 : while ((j = bms_next_member(attrs, j)) >= 0)
963 : : {
1810 tgl@sss.pgh.pa.us 964 : 0 : int attnum = (j - nexprs);
965 : :
966 : : /*
967 : : * Make sure the bitmap contains only user-defined attributes. As
968 : : * bitmaps can't contain negative values, this can be violated in two
969 : : * ways. Firstly, the bitmap might contain 0 as a member, and secondly
970 : : * the integer value might be larger than MaxAttrNumber.
971 : : */
1815 tomas.vondra@postgre 972 [ # # ]: 0 : Assert(AttributeNumberIsValid(attnum));
973 [ # # ]: 0 : Assert(attnum <= MaxAttrNumber);
974 [ # # ]: 0 : Assert(attnum >= (-nexprs));
975 : :
976 : 0 : attnums[i++] = (AttrNumber) attnum;
977 : :
978 : : /* protect against overflows */
2545 979 [ # # ]: 0 : Assert(i <= num);
980 : : }
981 : :
982 : 0 : return attnums;
983 : : }
984 : :
985 : : /*
986 : : * build_sorted_items
987 : : * build a sorted array of SortItem with values from rows
988 : : *
989 : : * Note: All the memory is allocated in a single chunk, so that the caller
990 : : * can simply pfree the return value to release all of it.
991 : : */
992 : : SortItem *
1815 tomas.vondra@postgre 993 :CBC 720 : build_sorted_items(StatsBuildData *data, int *nitems,
994 : : MultiSortSupport mss,
995 : : int numattrs, AttrNumber *attnums)
996 : : {
997 : : int i,
998 : : j,
999 : : nrows;
1000 : 720 : int nvalues = data->numrows * numattrs;
1001 : : Size len;
1002 : : SortItem *items;
1003 : : Datum *values;
1004 : : bool *isnull;
1005 : : char *ptr;
1006 : : int *typlen;
1007 : :
1008 : : /* Compute the total amount of memory we need (both items and values). */
186 tgl@sss.pgh.pa.us 1009 :GNC 720 : len = MAXALIGN(data->numrows * sizeof(SortItem)) +
1010 : 720 : nvalues * (sizeof(Datum) + sizeof(bool));
1011 : :
1012 : : /* Allocate the memory and split it into the pieces. */
2545 tomas.vondra@postgre 1013 :CBC 720 : ptr = palloc0(len);
1014 : :
1015 : : /* items to sort */
1016 : 720 : items = (SortItem *) ptr;
1017 : : /* MAXALIGN ensures that the following Datums are suitably aligned */
186 tgl@sss.pgh.pa.us 1018 :GNC 720 : ptr += MAXALIGN(data->numrows * sizeof(SortItem));
1019 : :
1020 : : /* values and null flags */
2545 tomas.vondra@postgre 1021 :CBC 720 : values = (Datum *) ptr;
1022 : 720 : ptr += nvalues * sizeof(Datum);
1023 : :
1024 : 720 : isnull = (bool *) ptr;
1025 : 720 : ptr += nvalues * sizeof(bool);
1026 : :
1027 : : /* make sure we consumed the whole buffer exactly */
1028 [ - + ]: 720 : Assert((ptr - (char *) items) == len);
1029 : :
1030 : : /* fix the pointers to Datum and bool arrays */
1815 1031 : 720 : nrows = 0;
1032 [ + + ]: 997581 : for (i = 0; i < data->numrows; i++)
1033 : : {
1034 : 996861 : items[nrows].values = &values[nrows * numattrs];
1035 : 996861 : items[nrows].isnull = &isnull[nrows * numattrs];
1036 : :
1037 : 996861 : nrows++;
1038 : : }
1039 : :
1040 : : /* build a local cache of typlen for all attributes */
95 michael@paquier.xyz 1041 :GNC 720 : typlen = palloc_array(int, data->nattnums);
1815 tomas.vondra@postgre 1042 [ + + ]:CBC 2829 : for (i = 0; i < data->nattnums; i++)
1043 : 2109 : typlen[i] = get_typlen(data->stats[i]->attrtypid);
1044 : :
1045 : 720 : nrows = 0;
1046 [ + + ]: 997581 : for (i = 0; i < data->numrows; i++)
1047 : : {
1048 : 996861 : bool toowide = false;
1049 : :
1050 : : /* load the values/null flags from sample rows */
2545 1051 [ + + ]: 3429435 : for (j = 0; j < numattrs; j++)
1052 : : {
1053 : : Datum value;
1054 : : bool isnull;
1055 : : int attlen;
1815 1056 : 2432574 : AttrNumber attnum = attnums[j];
1057 : :
1058 : : int idx;
1059 : :
1060 : : /* match attnum to the pre-calculated data */
1061 [ + - ]: 4794303 : for (idx = 0; idx < data->nattnums; idx++)
1062 : : {
1063 [ + + ]: 4794303 : if (attnum == data->attnums[idx])
1064 : 2432574 : break;
1065 : : }
1066 : :
1067 [ - + ]: 2432574 : Assert(idx < data->nattnums);
1068 : :
1069 : 2432574 : value = data->values[idx][i];
1070 : 2432574 : isnull = data->nulls[idx][i];
1071 : 2432574 : attlen = typlen[idx];
1072 : :
1073 : : /*
1074 : : * If this is a varlena value, check if it's too wide and if yes
1075 : : * then skip the whole item. Otherwise detoast the value.
1076 : : *
1077 : : * XXX It may happen that we've already detoasted some preceding
1078 : : * values for the current item. We don't bother to cleanup those
1079 : : * on the assumption that those are small (below WIDTH_THRESHOLD)
1080 : : * and will be discarded at the end of analyze.
1081 : : */
1082 [ + + + + ]: 2432574 : if ((!isnull) && (attlen == -1))
1083 : : {
2545 1084 [ - + ]: 743406 : if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
1085 : : {
2545 tomas.vondra@postgre 1086 :UBC 0 : toowide = true;
1087 : 0 : break;
1088 : : }
1089 : :
2545 tomas.vondra@postgre 1090 :CBC 743406 : value = PointerGetDatum(PG_DETOAST_DATUM(value));
1091 : : }
1092 : :
1815 1093 : 2432574 : items[nrows].values[j] = value;
1094 : 2432574 : items[nrows].isnull[j] = isnull;
1095 : : }
1096 : :
2545 1097 [ - + ]: 996861 : if (toowide)
2545 tomas.vondra@postgre 1098 :UBC 0 : continue;
1099 : :
1815 tomas.vondra@postgre 1100 :CBC 996861 : nrows++;
1101 : : }
1102 : :
1103 : : /* store the actual number of items (ignoring the too-wide ones) */
1104 : 720 : *nitems = nrows;
1105 : :
1106 : : /* all items were too wide */
1107 [ - + ]: 720 : if (nrows == 0)
1108 : : {
1109 : : /* everything is allocated as a single chunk */
2545 tomas.vondra@postgre 1110 :UBC 0 : pfree(items);
1111 : 0 : return NULL;
1112 : : }
1113 : :
1114 : : /* do the sort, using the multi-sort */
1132 peter@eisentraut.org 1115 :CBC 720 : qsort_interruptible(items, nrows, sizeof(SortItem),
1116 : : multi_sort_compare, mss);
1117 : :
2545 tomas.vondra@postgre 1118 : 720 : return items;
1119 : : }
1120 : :
1121 : : /*
1122 : : * has_stats_of_kind
1123 : : * Check whether the list contains statistic of a given kind
1124 : : */
1125 : : bool
3266 simon@2ndQuadrant.co 1126 : 2514 : has_stats_of_kind(List *stats, char requiredkind)
1127 : : {
1128 : : ListCell *l;
1129 : :
1130 [ + - + + : 4143 : foreach(l, stats)
+ + ]
1131 : : {
1132 : 2895 : StatisticExtInfo *stat = (StatisticExtInfo *) lfirst(l);
1133 : :
1134 [ + + ]: 2895 : if (stat->kind == requiredkind)
1135 : 1266 : return true;
1136 : : }
1137 : :
1138 : 1248 : return false;
1139 : : }
1140 : :
1141 : : /*
1142 : : * stat_find_expression
1143 : : * Search for an expression in statistics object's list of expressions.
1144 : : *
1145 : : * Returns the index of the expression in the statistics object's list of
1146 : : * expressions, or -1 if not found.
1147 : : */
1148 : : static int
1815 tomas.vondra@postgre 1149 : 297 : stat_find_expression(StatisticExtInfo *stat, Node *expr)
1150 : : {
1151 : : ListCell *lc;
1152 : : int idx;
1153 : :
1154 : 297 : idx = 0;
1155 [ + + + + : 537 : foreach(lc, stat->exprs)
+ + ]
1156 : : {
1157 : 486 : Node *stat_expr = (Node *) lfirst(lc);
1158 : :
1159 [ + + ]: 486 : if (equal(stat_expr, expr))
1160 : 246 : return idx;
1161 : 240 : idx++;
1162 : : }
1163 : :
1164 : : /* Expression not found */
1165 : 51 : return -1;
1166 : : }
1167 : :
1168 : : /*
1169 : : * stat_covers_expressions
1170 : : * Test whether a statistics object covers all expressions in a list.
1171 : : *
1172 : : * Returns true if all expressions are covered. If expr_idxs is non-NULL, it
1173 : : * is populated with the indexes of the expressions found.
1174 : : */
1175 : : static bool
1176 : 1557 : stat_covers_expressions(StatisticExtInfo *stat, List *exprs,
1177 : : Bitmapset **expr_idxs)
1178 : : {
1179 : : ListCell *lc;
1180 : :
1181 [ + + + + : 1803 : foreach(lc, exprs)
+ + ]
1182 : : {
1183 : 297 : Node *expr = (Node *) lfirst(lc);
1184 : : int expr_idx;
1185 : :
1186 : 297 : expr_idx = stat_find_expression(stat, expr);
1187 [ + + ]: 297 : if (expr_idx == -1)
1188 : 51 : return false;
1189 : :
1190 [ + + ]: 246 : if (expr_idxs != NULL)
1191 : 123 : *expr_idxs = bms_add_member(*expr_idxs, expr_idx);
1192 : : }
1193 : :
1194 : : /* If we reach here, all expressions are covered */
1195 : 1506 : return true;
1196 : : }
1197 : :
1198 : : /*
1199 : : * choose_best_statistics
1200 : : * Look for and return statistics with the specified 'requiredkind' which
1201 : : * have keys that match at least two of the given attnums. Return NULL if
1202 : : * there's no match.
1203 : : *
1204 : : * The current selection criteria is very simple - we choose the statistics
1205 : : * object referencing the most attributes in covered (and still unestimated
1206 : : * clauses), breaking ties in favor of objects with fewer keys overall.
1207 : : *
1208 : : * The clause_attnums is an array of bitmaps, storing attnums for individual
1209 : : * clauses. A NULL element means the clause is either incompatible or already
1210 : : * estimated.
1211 : : *
1212 : : * XXX If multiple statistics objects tie on both criteria, then which object
1213 : : * is chosen depends on the order that they appear in the stats list. Perhaps
1214 : : * further tiebreakers are needed.
1215 : : */
1216 : : StatisticExtInfo *
1519 1217 : 675 : choose_best_statistics(List *stats, char requiredkind, bool inh,
1218 : : Bitmapset **clause_attnums, List **clause_exprs,
1219 : : int nclauses)
1220 : : {
1221 : : ListCell *lc;
3266 simon@2ndQuadrant.co 1222 : 675 : StatisticExtInfo *best_match = NULL;
1223 : 675 : int best_num_matched = 2; /* goal #1: maximize */
1224 : 675 : int best_match_keys = (STATS_MAX_DIMENSIONS + 1); /* goal #2: minimize */
1225 : :
1226 [ + - + + : 1773 : foreach(lc, stats)
+ + ]
1227 : : {
1228 : : int i;
1229 : 1098 : StatisticExtInfo *info = (StatisticExtInfo *) lfirst(lc);
1815 tomas.vondra@postgre 1230 : 1098 : Bitmapset *matched_attnums = NULL;
1231 : 1098 : Bitmapset *matched_exprs = NULL;
1232 : : int num_matched;
1233 : : int numkeys;
1234 : :
1235 : : /* skip statistics that are not of the correct type */
3266 simon@2ndQuadrant.co 1236 [ + + ]: 1098 : if (info->kind != requiredkind)
1237 : 234 : continue;
1238 : :
1239 : : /* skip statistics with mismatching inheritance flag */
1519 tomas.vondra@postgre 1240 [ + + ]: 864 : if (info->inherit != inh)
1241 : 12 : continue;
1242 : :
1243 : : /*
1244 : : * Collect attributes and expressions in remaining (unestimated)
1245 : : * clauses fully covered by this statistic object.
1246 : : *
1247 : : * We know already estimated clauses have both clause_attnums and
1248 : : * clause_exprs set to NULL. We leave the pointers NULL if already
1249 : : * estimated, or we reset them to NULL after estimating the clause.
1250 : : */
2299 1251 [ + + ]: 2898 : for (i = 0; i < nclauses; i++)
1252 : : {
1815 1253 : 2046 : Bitmapset *expr_idxs = NULL;
1254 : :
1255 : : /* ignore incompatible/estimated clauses */
1256 [ + + + + ]: 2046 : if (!clause_attnums[i] && !clause_exprs[i])
2299 1257 : 1242 : continue;
1258 : :
1259 : : /* ignore clauses that are not covered by this object */
1815 1260 [ + + ]: 1017 : if (!bms_is_subset(clause_attnums[i], info->keys) ||
1261 [ + + ]: 852 : !stat_covers_expressions(info, clause_exprs[i], &expr_idxs))
2299 1262 : 213 : continue;
1263 : :
1264 : : /* record attnums and indexes of expressions covered */
1815 1265 : 804 : matched_attnums = bms_add_members(matched_attnums, clause_attnums[i]);
1266 : 804 : matched_exprs = bms_add_members(matched_exprs, expr_idxs);
1267 : : }
1268 : :
1269 : 852 : num_matched = bms_num_members(matched_attnums) + bms_num_members(matched_exprs);
1270 : :
1271 : 852 : bms_free(matched_attnums);
1272 : 852 : bms_free(matched_exprs);
1273 : :
1274 : : /*
1275 : : * save the actual number of keys in the stats so that we can choose
1276 : : * the narrowest stats with the most matching keys.
1277 : : */
1278 : 852 : numkeys = bms_num_members(info->keys) + list_length(info->exprs);
1279 : :
1280 : : /*
1281 : : * Use this object when it increases the number of matched attributes
1282 : : * and expressions or when it matches the same number of attributes
1283 : : * and expressions but these stats have fewer keys than any previous
1284 : : * match.
1285 : : */
3266 simon@2ndQuadrant.co 1286 [ + + + + ]: 852 : if (num_matched > best_num_matched ||
1287 [ + + ]: 207 : (num_matched == best_num_matched && numkeys < best_match_keys))
1288 : : {
1289 : 303 : best_match = info;
1290 : 303 : best_num_matched = num_matched;
1291 : 303 : best_match_keys = numkeys;
1292 : : }
1293 : : }
1294 : :
1295 : 675 : return best_match;
1296 : : }
1297 : :
1298 : : /*
1299 : : * statext_is_compatible_clause_internal
1300 : : * Determines if the clause is compatible with MCV lists.
1301 : : *
1302 : : * To be compatible, the given clause must be a combination of supported
1303 : : * clauses built from Vars or sub-expressions (where a sub-expression is
1304 : : * something that exactly matches an expression found in statistics objects).
1305 : : * This function recursively examines the clause and extracts any
1306 : : * sub-expressions that will need to be matched against statistics.
1307 : : *
1308 : : * Currently, we only support the following types of clauses:
1309 : : *
1310 : : * (a) OpExprs of the form (Var/Expr op Const), or (Const op Var/Expr), where
1311 : : * the op is one of ("=", "<", ">", ">=", "<=")
1312 : : *
1313 : : * (b) (Var/Expr IS [NOT] NULL)
1314 : : *
1315 : : * (c) combinations using AND/OR/NOT
1316 : : *
1317 : : * (d) ScalarArrayOpExprs of the form (Var/Expr op ANY (Const)) or
1318 : : * (Var/Expr op ALL (Const))
1319 : : *
1320 : : * In the future, the range of supported clauses may be expanded to more
1321 : : * complex cases, for example (Var op Var).
1322 : : *
1323 : : * Arguments:
1324 : : * clause: (sub)clause to be inspected (bare clause, not a RestrictInfo)
1325 : : * relid: rel that all Vars in clause must belong to
1326 : : * *attnums: input/output parameter collecting attribute numbers of all
1327 : : * mentioned Vars. Note that we do not offset the attribute numbers,
1328 : : * so we can't cope with system columns.
1329 : : * *exprs: input/output parameter collecting primitive subclauses within
1330 : : * the clause tree
1331 : : * *leakproof: input/output parameter recording the leakproofness of the
1332 : : * clause tree. This should be true initially, and will be set to false
1333 : : * if any operator function used in an OpExpr is not leakproof.
1334 : : *
1335 : : * Returns false if there is something we definitively can't handle.
1336 : : * On true return, we can proceed to match the *exprs against statistics.
1337 : : */
1338 : : static bool
2457 dean.a.rasheed@gmail 1339 : 1731 : statext_is_compatible_clause_internal(PlannerInfo *root, Node *clause,
1340 : : Index relid, Bitmapset **attnums,
1341 : : List **exprs, bool *leakproof)
1342 : : {
1343 : : /* Look inside any binary-compatible relabeling (as in examine_variable) */
2545 tomas.vondra@postgre 1344 [ - + ]: 1731 : if (IsA(clause, RelabelType))
2545 tomas.vondra@postgre 1345 :UBC 0 : clause = (Node *) ((RelabelType *) clause)->arg;
1346 : :
1347 : : /* plain Var references (boolean Vars or recursive checks) */
2545 tomas.vondra@postgre 1348 [ + + ]:CBC 1731 : if (IsA(clause, Var))
1349 : : {
1350 : 774 : Var *var = (Var *) clause;
1351 : :
1352 : : /* Ensure var is from the correct relation */
1353 [ - + ]: 774 : if (var->varno != relid)
2545 tomas.vondra@postgre 1354 :UBC 0 : return false;
1355 : :
1356 : : /* we also better ensure the Var is from the current level */
2545 tomas.vondra@postgre 1357 [ - + ]:CBC 774 : if (var->varlevelsup > 0)
2545 tomas.vondra@postgre 1358 :UBC 0 : return false;
1359 : :
1360 : : /*
1361 : : * Also reject system attributes and whole-row Vars (we don't allow
1362 : : * stats on those).
1363 : : */
2545 tomas.vondra@postgre 1364 [ - + ]:CBC 774 : if (!AttrNumberIsForUserDefinedAttr(var->varattno))
2545 tomas.vondra@postgre 1365 :UBC 0 : return false;
1366 : :
1367 : : /* OK, record the attnum for later permissions checks. */
2545 tomas.vondra@postgre 1368 :CBC 774 : *attnums = bms_add_member(*attnums, var->varattno);
1369 : :
1370 : 774 : return true;
1371 : : }
1372 : :
1373 : : /* (Var/Expr op Const) or (Const op Var/Expr) */
1374 [ + + ]: 957 : if (is_opclause(clause))
1375 : : {
1376 : 696 : OpExpr *expr = (OpExpr *) clause;
1377 : : Node *clause_expr;
1378 : :
1379 : : /* Only expressions with two arguments are considered compatible. */
1380 [ - + ]: 696 : if (list_length(expr->args) != 2)
2545 tomas.vondra@postgre 1381 :UBC 0 : return false;
1382 : :
1383 : : /* Check if the expression has the right shape */
1815 tomas.vondra@postgre 1384 [ - + ]:CBC 696 : if (!examine_opclause_args(expr->args, &clause_expr, NULL, NULL))
2192 tomas.vondra@postgre 1385 :UBC 0 : return false;
1386 : :
1387 : : /*
1388 : : * If it's not one of the supported operators ("=", "<", ">", etc.),
1389 : : * just ignore the clause, as it's not compatible with MCV lists.
1390 : : *
1391 : : * This uses the function for estimating selectivity, not the operator
1392 : : * directly (a bit awkward, but well ...).
1393 : : */
2192 tomas.vondra@postgre 1394 [ + - ]:CBC 696 : switch (get_oprrest(expr->opno))
1395 : : {
1396 : 696 : case F_EQSEL:
1397 : : case F_NEQSEL:
1398 : : case F_SCALARLTSEL:
1399 : : case F_SCALARLESEL:
1400 : : case F_SCALARGTSEL:
1401 : : case F_SCALARGESEL:
1402 : : /* supported, will continue with inspection of the Var/Expr */
1403 : 696 : break;
1404 : :
2192 tomas.vondra@postgre 1405 :UBC 0 : default:
1406 : : /* other estimators are considered unknown/unsupported */
1407 : 0 : return false;
1408 : : }
1409 : :
1410 : : /* Check if the operator is leakproof */
216 dean.a.rasheed@gmail 1411 [ + + ]:CBC 696 : if (*leakproof)
1412 : 690 : *leakproof = get_func_leakproof(get_opcode(expr->opno));
1413 : :
1414 : : /* Check (Var op Const) or (Const op Var) clauses by recursing. */
1815 tomas.vondra@postgre 1415 [ + + ]: 696 : if (IsA(clause_expr, Var))
1416 : 576 : return statext_is_compatible_clause_internal(root, clause_expr,
1417 : : relid, attnums,
1418 : : exprs, leakproof);
1419 : :
1420 : : /* Otherwise we have (Expr op Const) or (Const op Expr). */
1421 : 120 : *exprs = lappend(*exprs, clause_expr);
1422 : 120 : return true;
1423 : : }
1424 : :
1425 : : /* Var/Expr IN Array */
2192 1426 [ + + ]: 261 : if (IsA(clause, ScalarArrayOpExpr))
1427 : : {
2131 tgl@sss.pgh.pa.us 1428 : 144 : ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) clause;
1429 : : Node *clause_expr;
1430 : : bool expronleft;
1431 : :
1432 : : /* Only expressions with two arguments are considered compatible. */
2192 tomas.vondra@postgre 1433 [ - + ]: 144 : if (list_length(expr->args) != 2)
2192 tomas.vondra@postgre 1434 :UBC 0 : return false;
1435 : :
1436 : : /* Check if the expression has the right shape (one Var, one Const) */
1318 tgl@sss.pgh.pa.us 1437 [ - + ]:CBC 144 : if (!examine_opclause_args(expr->args, &clause_expr, NULL, &expronleft))
1318 tgl@sss.pgh.pa.us 1438 :UBC 0 : return false;
1439 : :
1440 : : /* We only support Var on left, Const on right */
1318 tgl@sss.pgh.pa.us 1441 [ + + ]:CBC 144 : if (!expronleft)
2545 tomas.vondra@postgre 1442 : 3 : return false;
1443 : :
1444 : : /*
1445 : : * If it's not one of the supported operators ("=", "<", ">", etc.),
1446 : : * just ignore the clause, as it's not compatible with MCV lists.
1447 : : *
1448 : : * This uses the function for estimating selectivity, not the operator
1449 : : * directly (a bit awkward, but well ...).
1450 : : */
1451 [ + - ]: 141 : switch (get_oprrest(expr->opno))
1452 : : {
1453 : 141 : case F_EQSEL:
1454 : : case F_NEQSEL:
1455 : : case F_SCALARLTSEL:
1456 : : case F_SCALARLESEL:
1457 : : case F_SCALARGTSEL:
1458 : : case F_SCALARGESEL:
1459 : : /* supported, will continue with inspection of the Var/Expr */
1460 : 141 : break;
1461 : :
2545 tomas.vondra@postgre 1462 :UBC 0 : default:
1463 : : /* other estimators are considered unknown/unsupported */
1464 : 0 : return false;
1465 : : }
1466 : :
1467 : : /* Check if the operator is leakproof */
216 dean.a.rasheed@gmail 1468 [ + - ]:CBC 141 : if (*leakproof)
1469 : 141 : *leakproof = get_func_leakproof(get_opcode(expr->opno));
1470 : :
1471 : : /* Check Var IN Array clauses by recursing. */
1815 tomas.vondra@postgre 1472 [ + + ]: 141 : if (IsA(clause_expr, Var))
1473 : 114 : return statext_is_compatible_clause_internal(root, clause_expr,
1474 : : relid, attnums,
1475 : : exprs, leakproof);
1476 : :
1477 : : /* Otherwise we have Expr IN Array. */
1478 : 27 : *exprs = lappend(*exprs, clause_expr);
1479 : 27 : return true;
1480 : : }
1481 : :
1482 : : /* AND/OR/NOT clause */
2545 1483 [ + - + + ]: 234 : if (is_andclause(clause) ||
1484 [ + + ]: 207 : is_orclause(clause) ||
1485 : 90 : is_notclause(clause))
1486 : : {
1487 : : /*
1488 : : * AND/OR/NOT-clauses are supported if all sub-clauses are supported
1489 : : *
1490 : : * Perhaps we could improve this by handling mixed cases, when some of
1491 : : * the clauses are supported and some are not. Selectivity for the
1492 : : * supported subclauses would be computed using extended statistics,
1493 : : * and the remaining clauses would be estimated using the traditional
1494 : : * algorithm (product of selectivities).
1495 : : *
1496 : : * It however seems overly complex, and in a way we already do that
1497 : : * because if we reject the whole clause as unsupported here, it will
1498 : : * be eventually passed to clauselist_selectivity() which does exactly
1499 : : * this (split into supported/unsupported clauses etc).
1500 : : */
1501 : 42 : BoolExpr *expr = (BoolExpr *) clause;
1502 : : ListCell *lc;
1503 : :
1504 [ + - + + : 111 : foreach(lc, expr->args)
+ + ]
1505 : : {
1506 : : /*
1507 : : * If we find an incompatible clause in the arguments, treat the
1508 : : * whole clause as incompatible.
1509 : : */
2457 dean.a.rasheed@gmail 1510 [ - + ]: 69 : if (!statext_is_compatible_clause_internal(root,
1511 : 69 : (Node *) lfirst(lc),
1512 : : relid, attnums, exprs,
1513 : : leakproof))
2545 tomas.vondra@postgre 1514 :UBC 0 : return false;
1515 : : }
1516 : :
2545 tomas.vondra@postgre 1517 :CBC 42 : return true;
1518 : : }
1519 : :
1520 : : /* Var/Expr IS NULL */
1521 [ + + ]: 75 : if (IsA(clause, NullTest))
1522 : : {
1523 : 72 : NullTest *nt = (NullTest *) clause;
1524 : :
1525 : : /* Check Var IS NULL clauses by recursing. */
1815 1526 [ + + ]: 72 : if (IsA(nt->arg, Var))
216 dean.a.rasheed@gmail 1527 : 45 : return statext_is_compatible_clause_internal(root,
1528 : 45 : (Node *) (nt->arg),
1529 : : relid, attnums,
1530 : : exprs, leakproof);
1531 : :
1532 : : /* Otherwise we have Expr IS NULL. */
1815 tomas.vondra@postgre 1533 : 27 : *exprs = lappend(*exprs, nt->arg);
1534 : 27 : return true;
1535 : : }
1536 : :
1537 : : /*
1538 : : * Treat any other expressions as bare expressions to be matched against
1539 : : * expressions in statistics objects.
1540 : : */
1541 : 3 : *exprs = lappend(*exprs, clause);
1542 : 3 : return true;
1543 : : }
1544 : :
1545 : : /*
1546 : : * statext_is_compatible_clause
1547 : : * Determines if the clause is compatible with MCV lists.
1548 : : *
1549 : : * See statext_is_compatible_clause_internal, above, for the basic rules.
1550 : : * This layer deals with RestrictInfo superstructure and applies permissions
1551 : : * checks to verify that it's okay to examine all mentioned Vars.
1552 : : *
1553 : : * Arguments:
1554 : : * clause: clause to be inspected (in RestrictInfo form)
1555 : : * relid: rel that all Vars in clause must belong to
1556 : : * *attnums: input/output parameter collecting attribute numbers of all
1557 : : * mentioned Vars. Note that we do not offset the attribute numbers,
1558 : : * so we can't cope with system columns.
1559 : : * *exprs: input/output parameter collecting primitive subclauses within
1560 : : * the clause tree
1561 : : *
1562 : : * Returns false if there is something we definitively can't handle.
1563 : : * On true return, we can proceed to match the *exprs against statistics.
1564 : : */
1565 : : static bool
2457 dean.a.rasheed@gmail 1566 : 954 : statext_is_compatible_clause(PlannerInfo *root, Node *clause, Index relid,
1567 : : Bitmapset **attnums, List **exprs)
1568 : : {
1569 : : RestrictInfo *rinfo;
1570 : : int clause_relid;
1571 : : bool leakproof;
1572 : :
1573 : : /*
1574 : : * Special-case handling for bare BoolExpr AND clauses, because the
1575 : : * restrictinfo machinery doesn't build RestrictInfos on top of AND
1576 : : * clauses.
1577 : : */
1923 1578 [ + + ]: 954 : if (is_andclause(clause))
1579 : : {
1580 : 24 : BoolExpr *expr = (BoolExpr *) clause;
1581 : : ListCell *lc;
1582 : :
1583 : : /*
1584 : : * Check that each sub-clause is compatible. We expect these to be
1585 : : * RestrictInfos.
1586 : : */
1587 [ + - + + : 81 : foreach(lc, expr->args)
+ + ]
1588 : : {
1589 [ - + ]: 57 : if (!statext_is_compatible_clause(root, (Node *) lfirst(lc),
1590 : : relid, attnums, exprs))
1923 dean.a.rasheed@gmail 1591 :UBC 0 : return false;
1592 : : }
1593 : :
1923 dean.a.rasheed@gmail 1594 :CBC 24 : return true;
1595 : : }
1596 : :
1597 : : /* Otherwise it must be a RestrictInfo. */
1318 tgl@sss.pgh.pa.us 1598 [ - + ]: 930 : if (!IsA(clause, RestrictInfo))
2545 tomas.vondra@postgre 1599 :UBC 0 : return false;
1318 tgl@sss.pgh.pa.us 1600 :CBC 930 : rinfo = (RestrictInfo *) clause;
1601 : :
1602 : : /* Pseudoconstants are not really interesting here. */
2545 tomas.vondra@postgre 1603 [ + + ]: 930 : if (rinfo->pseudoconstant)
1604 : 3 : return false;
1605 : :
1606 : : /* Clauses referencing other varnos are incompatible. */
1815 1607 [ + - ]: 927 : if (!bms_get_singleton_member(rinfo->clause_relids, &clause_relid) ||
1608 [ - + ]: 927 : clause_relid != relid)
2545 tomas.vondra@postgre 1609 :UBC 0 : return false;
1610 : :
1611 : : /*
1612 : : * Check the clause, determine what attributes it references, and whether
1613 : : * it includes any non-leakproof operators.
1614 : : */
216 dean.a.rasheed@gmail 1615 :CBC 927 : leakproof = true;
2457 1616 [ + + ]: 927 : if (!statext_is_compatible_clause_internal(root, (Node *) rinfo->clause,
1617 : : relid, attnums, exprs,
1618 : : &leakproof))
1619 : 3 : return false;
1620 : :
1621 : : /*
1622 : : * If the clause includes any non-leakproof operators, check that the user
1623 : : * has permission to read all required attributes, otherwise the operators
1624 : : * might reveal values from the MCV list that the user doesn't have
1625 : : * permission to see. We require all rows to be selectable --- there must
1626 : : * be no securityQuals from security barrier views or RLS policies. See
1627 : : * similar code in examine_variable(), examine_simple_variable(), and
1628 : : * statistic_proc_security_check().
1629 : : *
1630 : : * Note that for an inheritance child, the permission checks are performed
1631 : : * on the inheritance root parent, and whole-table select privilege on the
1632 : : * parent doesn't guarantee that the user could read all columns of the
1633 : : * child. Therefore we must check all referenced columns.
1634 : : */
216 1635 [ + + ]: 924 : if (!leakproof)
1636 : : {
1799 tgl@sss.pgh.pa.us 1637 : 126 : Bitmapset *clause_attnums = NULL;
1318 1638 : 126 : int attnum = -1;
1639 : :
1640 : : /*
1641 : : * We have to check per-column privileges. *attnums has the attnums
1642 : : * for individual Vars we saw, but there may also be Vars within
1643 : : * subexpressions in *exprs. We can use pull_varattnos() to extract
1644 : : * those, but there's an impedance mismatch: attnums returned by
1645 : : * pull_varattnos() are offset by FirstLowInvalidHeapAttributeNumber,
1646 : : * while attnums within *attnums aren't. Convert *attnums to the
1647 : : * offset style so we can combine the results.
1648 : : */
1649 [ + + ]: 246 : while ((attnum = bms_next_member(*attnums, attnum)) >= 0)
1650 : : {
1651 : 120 : clause_attnums =
1652 : 120 : bms_add_member(clause_attnums,
1653 : : attnum - FirstLowInvalidHeapAttributeNumber);
1654 : : }
1655 : :
1656 : : /* Now merge attnums from *exprs into clause_attnums */
1657 [ + + ]: 126 : if (*exprs != NIL)
1658 : 24 : pull_varattnos((Node *) *exprs, relid, &clause_attnums);
1659 : :
1660 : : /* Must have permission to read all rows from these columns */
216 dean.a.rasheed@gmail 1661 [ + + ]: 126 : if (!all_rows_selectable(root, relid, clause_attnums))
1662 : 114 : return false;
1663 : : }
1664 : :
1665 : : /* If we reach here, the clause is OK */
2457 1666 : 810 : return true;
1667 : : }
1668 : :
1669 : : /*
1670 : : * statext_mcv_clauselist_selectivity
1671 : : * Estimate clauses using the best multi-column statistics.
1672 : : *
1673 : : * Applies available extended (multi-column) statistics on a table. There may
1674 : : * be multiple applicable statistics (with respect to the clauses), in which
1675 : : * case we use greedy approach. In each round we select the best statistic on
1676 : : * a table (measured by the number of attributes extracted from the clauses
1677 : : * and covered by it), and compute the selectivity for the supplied clauses.
1678 : : * We repeat this process with the remaining clauses (if any), until none of
1679 : : * the available statistics can be used.
1680 : : *
1681 : : * One of the main challenges with using MCV lists is how to extrapolate the
1682 : : * estimate to the data not covered by the MCV list. To do that, we compute
1683 : : * not only the "MCV selectivity" (selectivities for MCV items matching the
1684 : : * supplied clauses), but also the following related selectivities:
1685 : : *
1686 : : * - simple selectivity: Computed without extended statistics, i.e. as if the
1687 : : * columns/clauses were independent.
1688 : : *
1689 : : * - base selectivity: Similar to simple selectivity, but is computed using
1690 : : * the extended statistic by adding up the base frequencies (that we compute
1691 : : * and store for each MCV item) of matching MCV items.
1692 : : *
1693 : : * - total selectivity: Selectivity covered by the whole MCV list.
1694 : : *
1695 : : * These are passed to mcv_combine_selectivities() which combines them to
1696 : : * produce a selectivity estimate that makes use of both per-column statistics
1697 : : * and the multi-column MCV statistics.
1698 : : *
1699 : : * 'estimatedclauses' is an input/output parameter. We set bits for the
1700 : : * 0-based 'clauses' indexes we estimate for and also skip clause items that
1701 : : * already have a bit set.
1702 : : */
1703 : : static Selectivity
2545 tomas.vondra@postgre 1704 : 1296 : statext_mcv_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid,
1705 : : JoinType jointype, SpecialJoinInfo *sjinfo,
1706 : : RelOptInfo *rel, Bitmapset **estimatedclauses,
1707 : : bool is_or)
1708 : : {
1709 : : ListCell *l;
1710 : : Bitmapset **list_attnums; /* attnums extracted from the clause */
1711 : : List **list_exprs; /* expressions matched to any statistic */
1712 : : int listidx;
1928 dean.a.rasheed@gmail 1713 [ + + ]: 1296 : Selectivity sel = (is_or) ? 0.0 : 1.0;
1520 tomas.vondra@postgre 1714 [ + - ]: 1296 : RangeTblEntry *rte = planner_rt_fetch(rel->relid, root);
1715 : :
1716 : : /* check if there's any stats that might be useful for us. */
2545 1717 [ + + ]: 1296 : if (!has_stats_of_kind(rel->statlist, STATS_EXT_MCV))
1928 dean.a.rasheed@gmail 1718 : 924 : return sel;
1719 : :
95 michael@paquier.xyz 1720 :GNC 372 : list_attnums = palloc_array(Bitmapset *, list_length(clauses));
1721 : :
1722 : : /* expressions extracted from complex expressions */
1723 : 372 : list_exprs = palloc_array(List *, list_length(clauses));
1724 : :
1725 : : /*
1726 : : * Pre-process the clauses list to extract the attnums and expressions
1727 : : * seen in each item. We need to determine if there are any clauses which
1728 : : * will be useful for selectivity estimations with extended stats. Along
1729 : : * the way we'll record all of the attnums and expressions for each clause
1730 : : * in lists which we'll reference later so we don't need to repeat the
1731 : : * same work again.
1732 : : *
1733 : : * We also skip clauses that we already estimated using different types of
1734 : : * statistics (we treat them as incompatible).
1735 : : */
2545 tomas.vondra@postgre 1736 :CBC 372 : listidx = 0;
1737 [ + - + + : 1269 : foreach(l, clauses)
+ + ]
1738 : : {
1739 : 897 : Node *clause = (Node *) lfirst(l);
1740 : 897 : Bitmapset *attnums = NULL;
1815 1741 : 897 : List *exprs = NIL;
1742 : :
2545 1743 [ + - + + ]: 1794 : if (!bms_is_member(listidx, *estimatedclauses) &&
1815 1744 : 897 : statext_is_compatible_clause(root, clause, rel->relid, &attnums, &exprs))
1745 : : {
2545 1746 : 777 : list_attnums[listidx] = attnums;
1815 1747 : 777 : list_exprs[listidx] = exprs;
1748 : : }
1749 : : else
1750 : : {
2545 1751 : 120 : list_attnums[listidx] = NULL;
1815 1752 : 120 : list_exprs[listidx] = NIL;
1753 : : }
1754 : :
2545 1755 : 897 : listidx++;
1756 : : }
1757 : :
1758 : : /* apply as many extended statistics as possible */
1759 : : while (true)
2253 1760 : 303 : {
1761 : : StatisticExtInfo *stat;
1762 : : List *stat_clauses;
1763 : : Bitmapset *simple_clauses;
1764 : :
1765 : : /* find the best suited statistics object for these attnums */
1519 1766 : 675 : stat = choose_best_statistics(rel->statlist, STATS_EXT_MCV, rte->inh,
1767 : : list_attnums, list_exprs,
1768 : : list_length(clauses));
1769 : :
1770 : : /*
1771 : : * if no (additional) matching stats could be found then we've nothing
1772 : : * to do
1773 : : */
2253 1774 [ + + ]: 675 : if (!stat)
1775 : 372 : break;
1776 : :
1777 : : /* Ensure choose_best_statistics produced an expected stats type. */
1778 [ - + ]: 303 : Assert(stat->kind == STATS_EXT_MCV);
1779 : :
1780 : : /* now filter the clauses to be estimated using the selected MCV */
1781 : 303 : stat_clauses = NIL;
1782 : :
1783 : : /* record which clauses are simple (single column or expression) */
1928 dean.a.rasheed@gmail 1784 : 303 : simple_clauses = NULL;
1785 : :
1804 tomas.vondra@postgre 1786 : 303 : listidx = -1;
2253 1787 [ + - + + : 1056 : foreach(l, clauses)
+ + ]
1788 : : {
1789 : : /* Increment the index before we decide if to skip the clause. */
1804 1790 : 753 : listidx++;
1791 : :
1792 : : /*
1793 : : * Ignore clauses from which we did not extract any attnums or
1794 : : * expressions (this needs to be consistent with what we do in
1795 : : * choose_best_statistics).
1796 : : *
1797 : : * This also eliminates already estimated clauses - both those
1798 : : * estimated before and during applying extended statistics.
1799 : : *
1800 : : * XXX This check is needed because both bms_is_subset and
1801 : : * stat_covers_expressions return true for empty attnums and
1802 : : * expressions.
1803 : : */
1804 [ + + + + ]: 753 : if (!list_attnums[listidx] && !list_exprs[listidx])
1805 : 18 : continue;
1806 : :
1807 : : /*
1808 : : * The clause was not estimated yet, and we've extracted either
1809 : : * attnums or expressions from it. Ignore it if it's not fully
1810 : : * covered by the chosen statistics object.
1811 : : *
1812 : : * We need to check both attributes and expressions, and reject if
1813 : : * either is not covered.
1814 : : */
1815 [ + + ]: 735 : if (!bms_is_subset(list_attnums[listidx], stat->keys) ||
1816 [ + + ]: 705 : !stat_covers_expressions(stat, list_exprs[listidx], NULL))
1817 : 33 : continue;
1818 : :
1819 : : /*
1820 : : * Now we know the clause is compatible (we have either attnums or
1821 : : * expressions extracted from it), and was not estimated yet.
1822 : : */
1823 : :
1824 : : /* record simple clauses (single column or expression) */
1825 [ + + - + ]: 825 : if ((list_attnums[listidx] == NULL &&
1826 : 123 : list_length(list_exprs[listidx]) == 1) ||
1827 [ + - + + ]: 1158 : (list_exprs[listidx] == NIL &&
1828 : 579 : bms_membership(list_attnums[listidx]) == BMS_SINGLETON))
1829 : 672 : simple_clauses = bms_add_member(simple_clauses,
1830 : : list_length(stat_clauses));
1831 : :
1832 : : /* add clause to list and mark it as estimated */
1833 : 702 : stat_clauses = lappend(stat_clauses, (Node *) lfirst(l));
1834 : 702 : *estimatedclauses = bms_add_member(*estimatedclauses, listidx);
1835 : :
1836 : : /*
1837 : : * Reset the pointers, so that choose_best_statistics knows this
1838 : : * clause was estimated and does not consider it again.
1839 : : */
1840 : 702 : bms_free(list_attnums[listidx]);
1841 : 702 : list_attnums[listidx] = NULL;
1842 : :
1843 : 702 : list_free(list_exprs[listidx]);
1844 : 702 : list_exprs[listidx] = NULL;
1845 : : }
1846 : :
1928 dean.a.rasheed@gmail 1847 [ + + ]: 303 : if (is_or)
1848 : : {
1849 : 48 : bool *or_matches = NULL;
1923 1850 : 48 : Selectivity simple_or_sel = 0.0,
1851 : 48 : stat_sel = 0.0;
1852 : : MCVList *mcv_list;
1853 : :
1854 : : /* Load the MCV list stored in the statistics object */
1519 tomas.vondra@postgre 1855 : 48 : mcv_list = statext_mcv_load(stat->statOid, rte->inh);
1856 : :
1857 : : /*
1858 : : * Compute the selectivity of the ORed list of clauses covered by
1859 : : * this statistics object by estimating each in turn and combining
1860 : : * them using the formula P(A OR B) = P(A) + P(B) - P(A AND B).
1861 : : * This allows us to use the multivariate MCV stats to better
1862 : : * estimate the individual terms and their overlap.
1863 : : *
1864 : : * Each time we iterate this formula, the clause "A" above is
1865 : : * equal to all the clauses processed so far, combined with "OR".
1866 : : */
1928 dean.a.rasheed@gmail 1867 : 48 : listidx = 0;
1868 [ + - + + : 168 : foreach(l, stat_clauses)
+ + ]
1869 : : {
1870 : 120 : Node *clause = (Node *) lfirst(l);
1871 : : Selectivity simple_sel,
1872 : : overlap_simple_sel,
1873 : : mcv_sel,
1874 : : mcv_basesel,
1875 : : overlap_mcvsel,
1876 : : overlap_basesel,
1877 : : mcv_totalsel,
1878 : : clause_sel,
1879 : : overlap_sel;
1880 : :
1881 : : /*
1882 : : * "Simple" selectivity of the next clause and its overlap
1883 : : * with any of the previous clauses. These are our initial
1884 : : * estimates of P(B) and P(A AND B), assuming independence of
1885 : : * columns/clauses.
1886 : : */
1887 : 120 : simple_sel = clause_selectivity_ext(root, clause, varRelid,
1888 : : jointype, sjinfo, false);
1889 : :
1890 : 120 : overlap_simple_sel = simple_or_sel * simple_sel;
1891 : :
1892 : : /*
1893 : : * New "simple" selectivity of all clauses seen so far,
1894 : : * assuming independence.
1895 : : */
1896 : 120 : simple_or_sel += simple_sel - overlap_simple_sel;
1897 [ - + - + ]: 120 : CLAMP_PROBABILITY(simple_or_sel);
1898 : :
1899 : : /*
1900 : : * Multi-column estimate of this clause using MCV statistics,
1901 : : * along with base and total selectivities, and corresponding
1902 : : * selectivities for the overlap term P(A AND B).
1903 : : */
1904 : 120 : mcv_sel = mcv_clause_selectivity_or(root, stat, mcv_list,
1905 : : clause, &or_matches,
1906 : : &mcv_basesel,
1907 : : &overlap_mcvsel,
1908 : : &overlap_basesel,
1909 : : &mcv_totalsel);
1910 : :
1911 : : /*
1912 : : * Combine the simple and multi-column estimates.
1913 : : *
1914 : : * If this clause is a simple single-column clause, then we
1915 : : * just use the simple selectivity estimate for it, since the
1916 : : * multi-column statistics are unlikely to improve on that
1917 : : * (and in fact could make it worse). For the overlap, we
1918 : : * always make use of the multi-column statistics.
1919 : : */
1920 [ + + ]: 120 : if (bms_is_member(listidx, simple_clauses))
1921 : 96 : clause_sel = simple_sel;
1922 : : else
1923 : 24 : clause_sel = mcv_combine_selectivities(simple_sel,
1924 : : mcv_sel,
1925 : : mcv_basesel,
1926 : : mcv_totalsel);
1927 : :
1928 : 120 : overlap_sel = mcv_combine_selectivities(overlap_simple_sel,
1929 : : overlap_mcvsel,
1930 : : overlap_basesel,
1931 : : mcv_totalsel);
1932 : :
1933 : : /* Factor these into the result for this statistics object */
1923 1934 : 120 : stat_sel += clause_sel - overlap_sel;
1935 [ - + - + ]: 120 : CLAMP_PROBABILITY(stat_sel);
1936 : :
1928 1937 : 120 : listidx++;
1938 : : }
1939 : :
1940 : : /*
1941 : : * Factor the result for this statistics object into the overall
1942 : : * result. We treat the results from each separate statistics
1943 : : * object as independent of one another.
1944 : : */
1923 1945 : 48 : sel = sel + stat_sel - sel * stat_sel;
1946 : : }
1947 : : else /* Implicitly-ANDed list of clauses */
1948 : : {
1949 : : Selectivity simple_sel,
1950 : : mcv_sel,
1951 : : mcv_basesel,
1952 : : mcv_totalsel,
1953 : : stat_sel;
1954 : :
1955 : : /*
1956 : : * "Simple" selectivity, i.e. without any extended statistics,
1957 : : * essentially assuming independence of the columns/clauses.
1958 : : */
1928 1959 : 255 : simple_sel = clauselist_selectivity_ext(root, stat_clauses,
1960 : : varRelid, jointype,
1961 : : sjinfo, false);
1962 : :
1963 : : /*
1964 : : * Multi-column estimate using MCV statistics, along with base and
1965 : : * total selectivities.
1966 : : */
1967 : 255 : mcv_sel = mcv_clauselist_selectivity(root, stat, stat_clauses,
1968 : : varRelid, jointype, sjinfo,
1969 : : rel, &mcv_basesel,
1970 : : &mcv_totalsel);
1971 : :
1972 : : /* Combine the simple and multi-column estimates. */
1973 : 255 : stat_sel = mcv_combine_selectivities(simple_sel,
1974 : : mcv_sel,
1975 : : mcv_basesel,
1976 : : mcv_totalsel);
1977 : :
1978 : : /* Factor this into the overall result */
1979 : 255 : sel *= stat_sel;
1980 : : }
1981 : : }
1982 : :
2545 tomas.vondra@postgre 1983 : 372 : return sel;
1984 : : }
1985 : :
1986 : : /*
1987 : : * statext_clauselist_selectivity
1988 : : * Estimate clauses using the best multi-column statistics.
1989 : : */
1990 : : Selectivity
1991 : 1296 : statext_clauselist_selectivity(PlannerInfo *root, List *clauses, int varRelid,
1992 : : JoinType jointype, SpecialJoinInfo *sjinfo,
1993 : : RelOptInfo *rel, Bitmapset **estimatedclauses,
1994 : : bool is_or)
1995 : : {
1996 : : Selectivity sel;
1997 : :
1998 : : /* First, try estimating clauses using a multivariate MCV list. */
1999 : 1296 : sel = statext_mcv_clauselist_selectivity(root, clauses, varRelid, jointype,
2000 : : sjinfo, rel, estimatedclauses, is_or);
2001 : :
2002 : : /*
2003 : : * Functional dependencies only work for clauses connected by AND, so for
2004 : : * OR clauses we're done.
2005 : : */
1928 dean.a.rasheed@gmail 2006 [ + + ]: 1296 : if (is_or)
2007 : 78 : return sel;
2008 : :
2009 : : /*
2010 : : * Then, apply functional dependencies on the remaining clauses by calling
2011 : : * dependencies_clauselist_selectivity. Pass 'estimatedclauses' so the
2012 : : * function can properly skip clauses already estimated above.
2013 : : *
2014 : : * The reasoning for applying dependencies last is that the more complex
2015 : : * stats can track more complex correlations between the attributes, and
2016 : : * so may be considered more reliable.
2017 : : *
2018 : : * For example, MCV list can give us an exact selectivity for values in
2019 : : * two columns, while functional dependencies can only provide information
2020 : : * about the overall strength of the dependency.
2021 : : */
2545 tomas.vondra@postgre 2022 : 1218 : sel *= dependencies_clauselist_selectivity(root, clauses, varRelid,
2023 : : jointype, sjinfo, rel,
2024 : : estimatedclauses);
2025 : :
2026 : 1218 : return sel;
2027 : : }
2028 : :
2029 : : /*
2030 : : * examine_opclause_args
2031 : : * Split an operator expression's arguments into Expr and Const parts.
2032 : : *
2033 : : * Attempts to match the arguments to either (Expr op Const) or (Const op
2034 : : * Expr), possibly with a RelabelType on top. When the expression matches this
2035 : : * form, returns true, otherwise returns false.
2036 : : *
2037 : : * Optionally returns pointers to the extracted Expr/Const nodes, when passed
2038 : : * non-null pointers (exprp, cstp and expronleftp). The expronleftp flag
2039 : : * specifies on which side of the operator we found the expression node.
2040 : : */
2041 : : bool
1815 2042 : 1509 : examine_opclause_args(List *args, Node **exprp, Const **cstp,
2043 : : bool *expronleftp)
2044 : : {
2045 : : Node *expr;
2046 : : Const *cst;
2047 : : bool expronleft;
2048 : : Node *leftop,
2049 : : *rightop;
2050 : :
2051 : : /* enforced by statext_is_compatible_clause_internal */
2192 2052 [ - + ]: 1509 : Assert(list_length(args) == 2);
2053 : :
2054 : 1509 : leftop = linitial(args);
2055 : 1509 : rightop = lsecond(args);
2056 : :
2057 : : /* strip RelabelType from either side of the expression */
2437 2058 [ + + ]: 1509 : if (IsA(leftop, RelabelType))
2059 : 162 : leftop = (Node *) ((RelabelType *) leftop)->arg;
2060 : :
2061 [ + + ]: 1509 : if (IsA(rightop, RelabelType))
2062 : 30 : rightop = (Node *) ((RelabelType *) rightop)->arg;
2063 : :
1815 2064 [ + + ]: 1509 : if (IsA(rightop, Const))
2065 : : {
103 peter@eisentraut.org 2066 :GNC 1428 : expr = leftop;
2437 tomas.vondra@postgre 2067 :CBC 1428 : cst = (Const *) rightop;
1815 2068 : 1428 : expronleft = true;
2069 : : }
2070 [ + - ]: 81 : else if (IsA(leftop, Const))
2071 : : {
103 peter@eisentraut.org 2072 :GNC 81 : expr = rightop;
2437 tomas.vondra@postgre 2073 :CBC 81 : cst = (Const *) leftop;
1815 2074 : 81 : expronleft = false;
2075 : : }
2076 : : else
2437 tomas.vondra@postgre 2077 :UBC 0 : return false;
2078 : :
2079 : : /* return pointers to the extracted parts if requested */
1815 tomas.vondra@postgre 2080 [ + - ]:CBC 1509 : if (exprp)
2081 : 1509 : *exprp = expr;
2082 : :
2437 2083 [ + + ]: 1509 : if (cstp)
2084 : 669 : *cstp = cst;
2085 : :
1815 2086 [ + + ]: 1509 : if (expronleftp)
2087 : 813 : *expronleftp = expronleft;
2088 : :
2437 2089 : 1509 : return true;
2090 : : }
2091 : :
2092 : :
2093 : : /*
2094 : : * Compute statistics about expressions of a relation.
2095 : : */
2096 : : static void
443 drowley@postgresql.o 2097 : 126 : compute_expr_stats(Relation onerel, AnlExprData *exprdata, int nexprs,
2098 : : HeapTuple *rows, int numrows)
2099 : : {
2100 : : MemoryContext expr_context,
2101 : : old_context;
2102 : : int ind,
2103 : : i;
2104 : :
1815 tomas.vondra@postgre 2105 : 126 : expr_context = AllocSetContextCreate(CurrentMemoryContext,
2106 : : "Analyze Expression",
2107 : : ALLOCSET_DEFAULT_SIZES);
2108 : 126 : old_context = MemoryContextSwitchTo(expr_context);
2109 : :
2110 [ + + ]: 351 : for (ind = 0; ind < nexprs; ind++)
2111 : : {
2112 : 225 : AnlExprData *thisdata = &exprdata[ind];
2113 : 225 : VacAttrStats *stats = thisdata->vacattrstat;
2114 : 225 : Node *expr = thisdata->expr;
2115 : : TupleTableSlot *slot;
2116 : : EState *estate;
2117 : : ExprContext *econtext;
2118 : : Datum *exprvals;
2119 : : bool *exprnulls;
2120 : : ExprState *exprstate;
2121 : : int tcnt;
2122 : :
2123 : : /* Are we still in the main context? */
2124 [ - + ]: 225 : Assert(CurrentMemoryContext == expr_context);
2125 : :
2126 : : /*
2127 : : * Need an EState for evaluation of expressions. Create it in the
2128 : : * per-expression context to be sure it gets cleaned up at the bottom
2129 : : * of the loop.
2130 : : */
2131 : 225 : estate = CreateExecutorState();
2132 [ - + ]: 225 : econtext = GetPerTupleExprContext(estate);
2133 : :
2134 : : /* Set up expression evaluation state */
2135 : 225 : exprstate = ExecPrepareExpr((Expr *) expr, estate);
2136 : :
2137 : : /* Need a slot to hold the current heap tuple, too */
2138 : 225 : slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel),
2139 : : &TTSOpsHeapTuple);
2140 : :
2141 : : /* Arrange for econtext's scan tuple to be the tuple under test */
2142 : 225 : econtext->ecxt_scantuple = slot;
2143 : :
2144 : : /* Compute and save expression values */
2145 : 225 : exprvals = (Datum *) palloc(numrows * sizeof(Datum));
2146 : 225 : exprnulls = (bool *) palloc(numrows * sizeof(bool));
2147 : :
2148 : 225 : tcnt = 0;
2149 [ + + ]: 230819 : for (i = 0; i < numrows; i++)
2150 : : {
2151 : : Datum datum;
2152 : : bool isnull;
2153 : :
2154 : : /*
2155 : : * Reset the per-tuple context each time, to reclaim any cruft
2156 : : * left behind by evaluating the statistics expressions.
2157 : : */
2158 : 230594 : ResetExprContext(econtext);
2159 : :
2160 : : /* Set up for expression evaluation */
2161 : 230594 : ExecStoreHeapTuple(rows[i], slot, false);
2162 : :
2163 : : /*
2164 : : * Evaluate the expression. We do this in the per-tuple context so
2165 : : * as not to leak memory, and then copy the result into the
2166 : : * context created at the beginning of this function.
2167 : : */
2168 : 230594 : datum = ExecEvalExprSwitchContext(exprstate,
2169 [ + - ]: 230594 : GetPerTupleExprContext(estate),
2170 : : &isnull);
2171 [ + + ]: 230594 : if (isnull)
2172 : : {
1815 tomas.vondra@postgre 2173 :GBC 6 : exprvals[tcnt] = (Datum) 0;
2174 : 6 : exprnulls[tcnt] = true;
2175 : : }
2176 : : else
2177 : : {
2178 : : /* Make sure we copy the data into the context. */
1815 tomas.vondra@postgre 2179 [ - + ]:CBC 230588 : Assert(CurrentMemoryContext == expr_context);
2180 : :
2181 : 461176 : exprvals[tcnt] = datumCopy(datum,
2182 : 230588 : stats->attrtype->typbyval,
2183 : 230588 : stats->attrtype->typlen);
2184 : 230588 : exprnulls[tcnt] = false;
2185 : : }
2186 : :
2187 : 230594 : tcnt++;
2188 : : }
2189 : :
2190 : : /*
2191 : : * Now we can compute the statistics for the expression columns.
2192 : : *
2193 : : * XXX Unlike compute_index_stats we don't need to switch and reset
2194 : : * memory contexts here, because we're only computing stats for a
2195 : : * single expression (and not iterating over many indexes), so we just
2196 : : * do it in expr_context. Note that compute_stats copies the result
2197 : : * into stats->anl_context, so it does not disappear.
2198 : : */
2199 [ + - ]: 225 : if (tcnt > 0)
2200 : : {
2201 : : AttributeOpts *aopt =
986 peter@eisentraut.org 2202 : 225 : get_attribute_options(onerel->rd_id, stats->tupattnum);
2203 : :
1815 tomas.vondra@postgre 2204 : 225 : stats->exprvals = exprvals;
2205 : 225 : stats->exprnulls = exprnulls;
2206 : 225 : stats->rowstride = 1;
2207 : 225 : stats->compute_stats(stats,
2208 : : expr_fetch_func,
2209 : : tcnt,
2210 : : tcnt);
2211 : :
2212 : : /*
2213 : : * If the n_distinct option is specified, it overrides the above
2214 : : * computation.
2215 : : */
2216 [ - + - - ]: 225 : if (aopt != NULL && aopt->n_distinct != 0.0)
1815 tomas.vondra@postgre 2217 :UBC 0 : stats->stadistinct = aopt->n_distinct;
2218 : : }
2219 : :
2220 : : /* And clean up */
1815 tomas.vondra@postgre 2221 :CBC 225 : MemoryContextSwitchTo(expr_context);
2222 : :
2223 : 225 : ExecDropSingleTupleTableSlot(slot);
2224 : 225 : FreeExecutorState(estate);
851 nathan@postgresql.or 2225 : 225 : MemoryContextReset(expr_context);
2226 : : }
2227 : :
1815 tomas.vondra@postgre 2228 : 126 : MemoryContextSwitchTo(old_context);
2229 : 126 : MemoryContextDelete(expr_context);
2230 : 126 : }
2231 : :
2232 : :
2233 : : /*
2234 : : * Fetch function for analyzing statistics object expressions.
2235 : : *
2236 : : * We have not bothered to construct tuples from the data, instead the data
2237 : : * is just in Datum arrays.
2238 : : */
2239 : : static Datum
2240 : 230603 : expr_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
2241 : : {
2242 : : int i;
2243 : :
2244 : : /* exprvals and exprnulls are already offset for proper column */
2245 : 230603 : i = rownum * stats->rowstride;
2246 : 230603 : *isNull = stats->exprnulls[i];
2247 : 230603 : return stats->exprvals[i];
2248 : : }
2249 : :
2250 : : /*
2251 : : * Build analyze data for a list of expressions. As this is not tied
2252 : : * directly to a relation (table or index), we have to fake some of
2253 : : * the fields in examine_expression().
2254 : : */
2255 : : static AnlExprData *
2256 : 126 : build_expr_data(List *exprs, int stattarget)
2257 : : {
2258 : : int idx;
2259 : 126 : int nexprs = list_length(exprs);
2260 : : AnlExprData *exprdata;
2261 : : ListCell *lc;
2262 : :
2263 : 126 : exprdata = (AnlExprData *) palloc0(nexprs * sizeof(AnlExprData));
2264 : :
2265 : 126 : idx = 0;
2266 [ + - + + : 351 : foreach(lc, exprs)
+ + ]
2267 : : {
2268 : 225 : Node *expr = (Node *) lfirst(lc);
2269 : 225 : AnlExprData *thisdata = &exprdata[idx];
2270 : :
2271 : 225 : thisdata->expr = expr;
2272 : 225 : thisdata->vacattrstat = examine_expression(expr, stattarget);
2273 : 225 : idx++;
2274 : : }
2275 : :
2276 : 126 : return exprdata;
2277 : : }
2278 : :
2279 : : /* form an array of pg_statistic rows (per update_attstats) */
2280 : : static Datum
2281 : 126 : serialize_expr_stats(AnlExprData *exprdata, int nexprs)
2282 : : {
2283 : : int exprno;
2284 : : Oid typOid;
2285 : : Relation sd;
2286 : :
2287 : 126 : ArrayBuildState *astate = NULL;
2288 : :
2289 : 126 : sd = table_open(StatisticRelationId, RowExclusiveLock);
2290 : :
2291 : : /* lookup OID of composite type for pg_statistic */
2292 : 126 : typOid = get_rel_type_id(StatisticRelationId);
2293 [ - + ]: 126 : if (!OidIsValid(typOid))
1815 tomas.vondra@postgre 2294 [ # # ]:UBC 0 : ereport(ERROR,
2295 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2296 : : errmsg("relation \"%s\" does not have a composite type",
2297 : : "pg_statistic")));
2298 : :
1815 tomas.vondra@postgre 2299 [ + + ]:CBC 351 : for (exprno = 0; exprno < nexprs; exprno++)
2300 : : {
2301 : : int i,
2302 : : k;
2303 : 225 : VacAttrStats *stats = exprdata[exprno].vacattrstat;
2304 : :
2305 : : Datum values[Natts_pg_statistic];
2306 : : bool nulls[Natts_pg_statistic];
2307 : : HeapTuple stup;
2308 : :
2309 [ + + ]: 225 : if (!stats->stats_valid)
2310 : : {
2311 : 1 : astate = accumArrayResult(astate,
2312 : : (Datum) 0,
2313 : : true,
2314 : : typOid,
2315 : : CurrentMemoryContext);
2316 : 1 : continue;
2317 : : }
2318 : :
2319 : : /*
2320 : : * Construct a new pg_statistic tuple
2321 : : */
2322 [ + + ]: 7168 : for (i = 0; i < Natts_pg_statistic; ++i)
2323 : : {
2324 : 6944 : nulls[i] = false;
2325 : : }
2326 : :
2327 : 224 : values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(InvalidOid);
2328 : 224 : values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(InvalidAttrNumber);
2329 : 224 : values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(false);
2330 : 224 : values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
2331 : 224 : values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
2332 : 224 : values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
2333 : 224 : i = Anum_pg_statistic_stakind1 - 1;
2334 [ + + ]: 1344 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2335 : : {
2336 : 1120 : values[i++] = Int16GetDatum(stats->stakind[k]); /* stakindN */
2337 : : }
2338 : 224 : i = Anum_pg_statistic_staop1 - 1;
2339 [ + + ]: 1344 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2340 : : {
2341 : 1120 : values[i++] = ObjectIdGetDatum(stats->staop[k]); /* staopN */
2342 : : }
2343 : 224 : i = Anum_pg_statistic_stacoll1 - 1;
2344 [ + + ]: 1344 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2345 : : {
2346 : 1120 : values[i++] = ObjectIdGetDatum(stats->stacoll[k]); /* stacollN */
2347 : : }
2348 : 224 : i = Anum_pg_statistic_stanumbers1 - 1;
2349 [ + + ]: 1344 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2350 : : {
2351 : 1120 : int nnum = stats->numnumbers[k];
2352 : :
2353 [ + + ]: 1120 : if (nnum > 0)
2354 : : {
2355 : : int n;
2356 : 397 : Datum *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
2357 : : ArrayType *arry;
2358 : :
2359 [ + + ]: 3043 : for (n = 0; n < nnum; n++)
2360 : 2646 : numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
1353 peter@eisentraut.org 2361 : 397 : arry = construct_array_builtin(numdatums, nnum, FLOAT4OID);
1815 tomas.vondra@postgre 2362 : 397 : values[i++] = PointerGetDatum(arry); /* stanumbersN */
2363 : : }
2364 : : else
2365 : : {
2366 : 723 : nulls[i] = true;
2367 : 723 : values[i++] = (Datum) 0;
2368 : : }
2369 : : }
2370 : 224 : i = Anum_pg_statistic_stavalues1 - 1;
2371 [ + + ]: 1344 : for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
2372 : : {
2373 [ + + ]: 1120 : if (stats->numvalues[k] > 0)
2374 : : {
2375 : : ArrayType *arry;
2376 : :
2377 : 251 : arry = construct_array(stats->stavalues[k],
2378 : : stats->numvalues[k],
2379 : : stats->statypid[k],
2380 : 251 : stats->statyplen[k],
2381 : 251 : stats->statypbyval[k],
2382 : 251 : stats->statypalign[k]);
2383 : 251 : values[i++] = PointerGetDatum(arry); /* stavaluesN */
2384 : : }
2385 : : else
2386 : : {
2387 : 869 : nulls[i] = true;
2388 : 869 : values[i++] = (Datum) 0;
2389 : : }
2390 : : }
2391 : :
2392 : 224 : stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
2393 : :
2394 : 224 : astate = accumArrayResult(astate,
2395 : : heap_copy_tuple_as_datum(stup, RelationGetDescr(sd)),
2396 : : false,
2397 : : typOid,
2398 : : CurrentMemoryContext);
2399 : : }
2400 : :
2401 : 126 : table_close(sd, RowExclusiveLock);
2402 : :
2403 : 126 : return makeArrayResult(astate, CurrentMemoryContext);
2404 : : }
2405 : :
2406 : : /*
2407 : : * Loads pg_statistic record from expression statistics for expression
2408 : : * identified by the supplied index.
2409 : : *
2410 : : * Returns the pg_statistic record found, or NULL if there is no statistics
2411 : : * data to use.
2412 : : */
2413 : : HeapTuple
1519 2414 : 832 : statext_expressions_load(Oid stxoid, bool inh, int idx)
2415 : : {
2416 : : bool isnull;
2417 : : Datum value;
2418 : : HeapTuple htup;
2419 : : ExpandedArrayHeader *eah;
2420 : : HeapTupleHeader td;
2421 : : HeapTupleData tmptup;
2422 : : HeapTuple tup;
2423 : :
2424 : 832 : htup = SearchSysCache2(STATEXTDATASTXOID,
2425 : : ObjectIdGetDatum(stxoid), BoolGetDatum(inh));
1815 2426 [ - + ]: 832 : if (!HeapTupleIsValid(htup))
1815 tomas.vondra@postgre 2427 [ # # ]:UBC 0 : elog(ERROR, "cache lookup failed for statistics object %u", stxoid);
2428 : :
1815 tomas.vondra@postgre 2429 :CBC 832 : value = SysCacheGetAttr(STATEXTDATASTXOID, htup,
2430 : : Anum_pg_statistic_ext_data_stxdexpr, &isnull);
2431 [ - + ]: 832 : if (isnull)
1815 tomas.vondra@postgre 2432 [ # # ]:UBC 0 : elog(ERROR,
2433 : : "requested statistics kind \"%c\" is not yet built for statistics object %u",
2434 : : STATS_EXT_EXPRESSIONS, stxoid);
2435 : :
1815 tomas.vondra@postgre 2436 :CBC 832 : eah = DatumGetExpandedArray(value);
2437 : :
2438 : 832 : deconstruct_expanded_array(eah);
2439 : :
13 michael@paquier.xyz 2440 [ + + + - ]: 832 : if (eah->dnulls && eah->dnulls[idx])
2441 : : {
2442 : : /* No data found for this expression, give up. */
2443 : 1 : ReleaseSysCache(htup);
2444 : 1 : return NULL;
2445 : : }
2446 : :
1815 tomas.vondra@postgre 2447 : 831 : td = DatumGetHeapTupleHeader(eah->dvalues[idx]);
2448 : :
2449 : : /* Build a temporary HeapTuple control structure */
2450 : 831 : tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1796 2451 : 831 : ItemPointerSetInvalid(&(tmptup.t_self));
2452 : 831 : tmptup.t_tableOid = InvalidOid;
1815 2453 : 831 : tmptup.t_data = td;
2454 : :
2455 : 831 : tup = heap_copytuple(&tmptup);
2456 : :
2457 : 831 : ReleaseSysCache(htup);
2458 : :
2459 : 831 : return tup;
2460 : : }
2461 : :
2462 : : /*
2463 : : * Evaluate the expressions, so that we can use the results to build
2464 : : * all the requested statistics types. This matters especially for
2465 : : * expensive expressions, of course.
2466 : : */
2467 : : static StatsBuildData *
2468 : 271 : make_build_data(Relation rel, StatExtEntry *stat, int numrows, HeapTuple *rows,
2469 : : VacAttrStats **stats, int stattarget)
2470 : : {
2471 : : /* evaluated expressions */
2472 : : StatsBuildData *result;
2473 : : char *ptr;
2474 : : Size len;
2475 : :
2476 : : int i;
2477 : : int k;
2478 : : int idx;
2479 : : TupleTableSlot *slot;
2480 : : EState *estate;
2481 : : ExprContext *econtext;
2482 : 271 : List *exprstates = NIL;
2483 : 271 : int nkeys = bms_num_members(stat->columns) + list_length(stat->exprs);
2484 : : ListCell *lc;
2485 : :
2486 : : /* allocate everything as a single chunk, so we can free it easily */
2487 : 271 : len = MAXALIGN(sizeof(StatsBuildData));
2488 : 271 : len += MAXALIGN(sizeof(AttrNumber) * nkeys); /* attnums */
2489 : 271 : len += MAXALIGN(sizeof(VacAttrStats *) * nkeys); /* stats */
2490 : :
2491 : : /* values */
2492 : 271 : len += MAXALIGN(sizeof(Datum *) * nkeys);
2493 : 271 : len += nkeys * MAXALIGN(sizeof(Datum) * numrows);
2494 : :
2495 : : /* nulls */
2496 : 271 : len += MAXALIGN(sizeof(bool *) * nkeys);
2497 : 271 : len += nkeys * MAXALIGN(sizeof(bool) * numrows);
2498 : :
2499 : 271 : ptr = palloc(len);
2500 : :
2501 : : /* set the pointers */
2502 : 271 : result = (StatsBuildData *) ptr;
2503 : 271 : ptr += MAXALIGN(sizeof(StatsBuildData));
2504 : :
2505 : : /* attnums */
2506 : 271 : result->attnums = (AttrNumber *) ptr;
2507 : 271 : ptr += MAXALIGN(sizeof(AttrNumber) * nkeys);
2508 : :
2509 : : /* stats */
2510 : 271 : result->stats = (VacAttrStats **) ptr;
2511 : 271 : ptr += MAXALIGN(sizeof(VacAttrStats *) * nkeys);
2512 : :
2513 : : /* values */
2514 : 271 : result->values = (Datum **) ptr;
2515 : 271 : ptr += MAXALIGN(sizeof(Datum *) * nkeys);
2516 : :
2517 : : /* nulls */
2518 : 271 : result->nulls = (bool **) ptr;
2519 : 271 : ptr += MAXALIGN(sizeof(bool *) * nkeys);
2520 : :
2521 [ + + ]: 933 : for (i = 0; i < nkeys; i++)
2522 : : {
2523 : 662 : result->values[i] = (Datum *) ptr;
2524 : 662 : ptr += MAXALIGN(sizeof(Datum) * numrows);
2525 : :
2526 : 662 : result->nulls[i] = (bool *) ptr;
2527 : 662 : ptr += MAXALIGN(sizeof(bool) * numrows);
2528 : : }
2529 : :
2530 [ - + ]: 271 : Assert((ptr - (char *) result) == len);
2531 : :
2532 : : /* we have it allocated, so let's fill the values */
2533 : 271 : result->nattnums = nkeys;
2534 : 271 : result->numrows = numrows;
2535 : :
2536 : : /* fill the attribute info - first attributes, then expressions */
2537 : 271 : idx = 0;
2538 : 271 : k = -1;
2539 [ + + ]: 708 : while ((k = bms_next_member(stat->columns, k)) >= 0)
2540 : : {
2541 : 437 : result->attnums[idx] = k;
2542 : 437 : result->stats[idx] = stats[idx];
2543 : :
2544 : 437 : idx++;
2545 : : }
2546 : :
2547 : 271 : k = -1;
2548 [ + + + + : 496 : foreach(lc, stat->exprs)
+ + ]
2549 : : {
2550 : 225 : Node *expr = (Node *) lfirst(lc);
2551 : :
2552 : 225 : result->attnums[idx] = k;
2553 : 225 : result->stats[idx] = examine_expression(expr, stattarget);
2554 : :
2555 : 225 : idx++;
2556 : 225 : k--;
2557 : : }
2558 : :
2559 : : /* first extract values for all the regular attributes */
2560 [ + + ]: 472441 : for (i = 0; i < numrows; i++)
2561 : : {
2562 : 472170 : idx = 0;
2563 : 472170 : k = -1;
2564 [ + + ]: 1524070 : while ((k = bms_next_member(stat->columns, k)) >= 0)
2565 : : {
2566 : 2103800 : result->values[idx][i] = heap_getattr(rows[i], k,
2567 : 1051900 : result->stats[idx]->tupDesc,
2568 : 1051900 : &result->nulls[idx][i]);
2569 : :
2570 : 1051900 : idx++;
2571 : : }
2572 : : }
2573 : :
2574 : : /* Need an EState for evaluation expressions. */
2575 : 271 : estate = CreateExecutorState();
2576 [ - + ]: 271 : econtext = GetPerTupleExprContext(estate);
2577 : :
2578 : : /* Need a slot to hold the current heap tuple, too */
2579 : 271 : slot = MakeSingleTupleTableSlot(RelationGetDescr(rel),
2580 : : &TTSOpsHeapTuple);
2581 : :
2582 : : /* Arrange for econtext's scan tuple to be the tuple under test */
2583 : 271 : econtext->ecxt_scantuple = slot;
2584 : :
2585 : : /* Set up expression evaluation state */
2586 : 271 : exprstates = ExecPrepareExprList(stat->exprs, estate);
2587 : :
2588 [ + + ]: 472441 : for (i = 0; i < numrows; i++)
2589 : : {
2590 : : /*
2591 : : * Reset the per-tuple context each time, to reclaim any cruft left
2592 : : * behind by evaluating the statistics object expressions.
2593 : : */
2594 : 472170 : ResetExprContext(econtext);
2595 : :
2596 : : /* Set up for expression evaluation */
2597 : 472170 : ExecStoreHeapTuple(rows[i], slot, false);
2598 : :
2599 : 472170 : idx = bms_num_members(stat->columns);
2600 [ + + + + : 702764 : foreach(lc, exprstates)
+ + ]
2601 : : {
2602 : : Datum datum;
2603 : : bool isnull;
2604 : 230594 : ExprState *exprstate = (ExprState *) lfirst(lc);
2605 : :
2606 : : /*
2607 : : * XXX This probably leaks memory. Maybe we should use
2608 : : * ExecEvalExprSwitchContext but then we need to copy the result
2609 : : * somewhere else.
2610 : : */
2611 : 230594 : datum = ExecEvalExpr(exprstate,
2612 [ + - ]: 230594 : GetPerTupleExprContext(estate),
2613 : : &isnull);
2614 [ + + ]: 230594 : if (isnull)
2615 : : {
1815 tomas.vondra@postgre 2616 :GBC 6 : result->values[idx][i] = (Datum) 0;
2617 : 6 : result->nulls[idx][i] = true;
2618 : : }
2619 : : else
2620 : : {
219 peter@eisentraut.org 2621 :GNC 230588 : result->values[idx][i] = datum;
1815 tomas.vondra@postgre 2622 :CBC 230588 : result->nulls[idx][i] = false;
2623 : : }
2624 : :
2625 : 230594 : idx++;
2626 : : }
2627 : : }
2628 : :
2629 : 271 : ExecDropSingleTupleTableSlot(slot);
2630 : 271 : FreeExecutorState(estate);
2631 : :
2632 : 271 : return result;
2633 : : }
|