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