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