63#include "access/genam.h"
64#include "access/gin.h"
65#include "access/gist.h"
66#include "access/gist_private.h"
67#include "access/gistscan.h"
68#include "access/detoast.h"
69#include "utils/datum.h"
70#include "access/heapam.h"
71#include "catalog/index.h"
72#include "catalog/pg_am.h"
74#include "storage/lmgr.h"
75#include "catalog/namespace.h"
76#include "catalog/indexing.h"
78#include "utils/regproc.h"
79#include "utils/varlena.h"
81#include "utils/builtins.h"
82#include "utils/datum.h"
83#include "utils/snapmgr.h"
84#include "utils/fmgroids.h"
86#include "access/heapam.h"
87#include "catalog/pg_type.h"
88#include "access/relscan.h"
90#include "executor/spi.h"
92#include "commands/vacuum.h"
93#include "nodes/pathnodes.h"
95#include "parser/parsetree.h"
96#include "utils/array.h"
97#include "utils/lsyscache.h"
98#include "utils/builtins.h"
99#include "utils/syscache.h"
100#include "utils/rel.h"
101#include "utils/selfuncs.h"
103#include "../postgis_config.h"
105#include "access/htup_details.h"
110#include "lwgeom_pg.h"
111#include "gserialized_gist.h"
163#define STATISTIC_KIND_ND 102
164#define STATISTIC_KIND_2D 103
174#define STATISTIC_SLOT_ND 3
175#define STATISTIC_SLOT_2D 4
191#define MIN_DIMENSION_WIDTH 0.000000001
197#define MAX_DIMENSION_WIDTH 1.0E+20
202#define DEFAULT_ND_SEL 0.0001
203#define DEFAULT_ND_JOINSEL 0.001
208#define FALLBACK_ND_SEL 0.2
209#define FALLBACK_ND_JOINSEL 0.3
246 if (VARSIZE_ANY_EXHDR(txt) <= 0)
248 modestr = (
char *)VARDATA(txt);
249 if (modestr[0] ==
'N')
260 int ia = *((
const int*)a);
261 int ib = *((
const int*)b);
288 qsort(vals, nvals,
sizeof(
int),
cmp_int);
289 return vals[nvals-1] - vals[0];
301 for (i = 0; i < nvals; i++)
307#if POSTGIS_DEBUG_LEVEL >= 3
313total_int(
const int *vals,
int nvals)
318 for ( i = 0; i < nvals; i++ )
328avg(
const int *vals,
int nvals)
330 int t = total_int(vals, nvals);
331 return (
double)t / (double)nvals;
338stddev(
const int *vals,
int nvals)
342 double mean = avg(vals, nvals);
345 for ( i = 0; i < nvals; i++ )
347 double v = (double)(vals[i]);
348 sigma2 += (mean - v) * (mean - v);
350 return sqrt(sigma2 / nvals);
365 for ( i = 0; i < ndims; i++ )
371 for ( i = 0; i < ndims; i++ )
391 char *json_extent, *
str;
394 int ndims = (int)roundf(nd_stats->
ndims);
401 for ( d = 0; d < ndims; d++ )
437 int sizex = (int)roundf(stats->
size[0]);
438 int sizey = (int)roundf(stats->
size[1]);
441 for ( k = 0; k < sizey; k++ )
443 for ( j = 0; j < sizex; j++ )
461 for ( d = 0; d <
ND_DIMS; d++ )
463 target->
min[d] = Min(target->
min[d], source->
min[d]);
464 target->
max[d] = Max(target->
max[d], source->
max[d]);
473 memset(a, 0,
sizeof(
ND_BOX));
486 for ( d = 0; d <
ND_DIMS; d++ )
489 a->
max[d] = -1 * FLT_MAX;
536 for ( d = 0; d < ndims; d++ )
538 if ( (a->
min[d] > b->
max[d]) || (a->
max[d] < b->
min[d]) )
551 for ( d = 0; d < ndims; d++ )
553 if ( ! ((a->
min[d] < b->
min[d]) && (a->
max[d] > b->
max[d])) )
568 for ( d = 0; d <
ND_DIMS; d++ )
570 size = nd_box->
max[d] - nd_box->
min[d];
574 nd_box->
min[d] -= size * expansion_factor / 2;
575 nd_box->
max[d] += size * expansion_factor / 2;
592 memset(nd_ibox, 0,
sizeof(
ND_IBOX));
595 for ( d = 0; d < nd_stats->
ndims; d++ )
599 double width = smax - smin;
607 int size = (int)roundf(nd_stats->
size[d]);
610 nd_ibox->
min[d] = floor(size * (nd_box->
min[d] - smin) / width);
611 nd_ibox->
max[d] = floor(size * (nd_box->
max[d] - smin) / width);
613 POSTGIS_DEBUGF(5,
" stats: dim %d: min %g: max %g: width %g", d, smin, smax, width);
614 POSTGIS_DEBUGF(5,
" overlap: dim %d: (%d, %d)", d, nd_ibox->
min[d], nd_ibox->
max[d]);
617 nd_ibox->
min[d] = Max(nd_ibox->
min[d], 0);
618 nd_ibox->
max[d] = Min(nd_ibox->
max[d], size - 1);
625#define MAX_NUM_BINS 50
626#define BIN_MIN_SIZE 10
650#if POSTGIS_DEBUG_LEVEL >= 3
651 double average, sdev, sdev_ratio;
657 counts = palloc0(num_bins *
sizeof(
int));
660 for ( d = 0; d < ndims; d++ )
663 memset(counts, 0, num_bins *
sizeof(
int));
666 smin = extent->
min[d];
667 smax = extent->
max[d];
668 swidth = smax - smin;
682 for ( i = 0; i < num_boxes; i++ )
684 double minoffset, maxoffset;
688 if ( ! ndb )
continue;
691 minoffset = ndb->
min[d] - smin;
692 maxoffset = ndb->
max[d] - smin;
695 if ( minoffset < 0 || minoffset > swidth ||
696 maxoffset < 0 || maxoffset > swidth )
702 bmin = floor(num_bins * minoffset / swidth);
703 bmax = floor(num_bins * maxoffset / swidth);
706 if (bmax >= num_bins)
709 POSTGIS_DEBUGF(4,
" dimension %d, feature %d: bin %d to bin %d", d, i, bmin, bmax);
712 for ( k = bmin; k <= bmax; k++ )
723#if POSTGIS_DEBUG_LEVEL >= 3
724 average = avg(counts, num_bins);
725 sdev = stddev(counts, num_bins);
726 sdev_ratio = sdev/average;
728 POSTGIS_DEBUGF(3,
" dimension %d: range = %d", d, range);
729 POSTGIS_DEBUGF(3,
" dimension %d: average = %.6g", d, average);
730 POSTGIS_DEBUGF(3,
" dimension %d: stddev = %.6g", d, sdev);
731 POSTGIS_DEBUGF(3,
" dimension %d: stddev_ratio = %.6g", d, sdev_ratio);
734 distribution[d] = range;
754 if (counter[d] < ibox->
max[d])
759 counter[d] = ibox->
min[d];
783 rv = get_attstatsslot(&sslot, stats_tuple, stats_kind, InvalidOid,
784 ATTSTATSSLOT_NUMBERS);
786 POSTGIS_DEBUGF(2,
"no slot of kind %d in stats tuple", stats_kind);
791 nd_stats = palloc(
sizeof(float4) * sslot.nnumbers);
792 memcpy(nd_stats, sslot.numbers,
sizeof(float4) * sslot.nnumbers);
794 free_attstatsslot(&sslot);
806 HeapTuple stats_tuple = NULL;
812 POSTGIS_DEBUGF(2,
"searching whole tree stats for \"%s\"", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
813 stats_tuple = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(table_oid), Int16GetDatum(att_num), BoolGetDatum(
true));
815 POSTGIS_DEBUGF(2,
"found whole tree stats for \"%s\"", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
818 if ( only_parent || ! stats_tuple )
820 POSTGIS_DEBUGF(2,
"searching parent table stats for \"%s\"", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
821 stats_tuple = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(table_oid), Int16GetDatum(att_num), BoolGetDatum(
false));
823 POSTGIS_DEBUGF(2,
"found parent table stats for \"%s\"", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
827 POSTGIS_DEBUGF(2,
"stats for \"%s\" do not exist", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
832 ReleaseSysCache(stats_tuple);
836 "histogram for attribute %d of table \"%s\" does not exist?",
837 att_num, get_rel_name(table_oid));
854 const char *att_name = text_to_cstring(att_text);
861 att_num = get_attnum(table_oid, att_name);
863 elog(ERROR,
"attribute \"%s\" does not exist", att_name);
869 elog(ERROR,
"attribute name is null");
892 int ncells1, ncells2;
893 int ndims1, ndims2, ndims;
895 double ntuples_not_null1, ntuples_not_null2;
914 if ( ! ( s1 && s2 ) )
916 elog(NOTICE,
" estimate_join_selectivity called with null inputs");
925 if ( ncells1 > ncells2 )
943 ntuples_max = ntuples_not_null1 * ntuples_not_null2;
946 ndims1 = (int)roundf(s1->
ndims);
947 ndims2 = (int)roundf(s2->
ndims);
948 ndims = Max(ndims1, ndims2);
957 POSTGIS_DEBUG(3,
"relation stats do not intersect, returning 0");
958 PG_RETURN_FLOAT8(0.0);
967 POSTGIS_DEBUG(3,
"could not calculate overlap of relations");
972 for ( d = 0; d < ndims1; d++ )
974 at1[d] = ibox1.
min[d];
977 size1[d] = (int)roundf(s1->
size[d]);
978 cellsize1[d] = width1[d] / size1[d];
982 for ( d = 0; d < ndims2; d++ )
986 size2[d] = (int)roundf(s2->
size[d]);
987 cellsize2[d] = width2[d] / size2[d];
997 for ( d = 0; d < ndims1; d++ )
999 nd_cell1.
min[d] = min1[d] + (at1[d]+0) * cellsize1[d];
1000 nd_cell1.
max[d] = min1[d] + (at1[d]+1) * cellsize1[d];
1007 for ( d = 0; d < ndims2; d++ )
1009 at2[d] = ibox2.
min[d];
1012 POSTGIS_DEBUGF(3,
"at1 %d,%d %s", at1[0], at1[1],
nd_box_to_json(&nd_cell1, ndims1));
1026 for ( d = 0; d < ndims2; d++ )
1028 nd_cell2.
min[d] = min2[d] + (at2[d]+0) * cellsize2[d];
1029 nd_cell2.
max[d] = min2[d] + (at2[d]+1) * cellsize2[d];
1032 POSTGIS_DEBUGF(3,
" at2 %d,%d %s", at2[0], at2[1],
nd_box_to_json(&nd_cell2, ndims2));
1035 ratio2 =
nd_box_ratio(&nd_cell1, &nd_cell2, Max(ndims1, ndims2));
1039 POSTGIS_DEBUGF(3,
" val1 %.6g val2 %.6g ratio %.6g", val1, val2, ratio2);
1040 val += val1 * (val2 * ratio2);
1047 POSTGIS_DEBUGF(3,
"val of histogram = %g", val);
1058 POSTGIS_DEBUGF(3,
"val scaled to full table size = %g", val);
1075 selectivity = val / ntuples_max;
1078 if ( isnan(selectivity) || ! isfinite(selectivity) || selectivity < 0.0 )
1082 else if ( selectivity > 1.0 )
1097 PG_RETURN_DATUM(DirectFunctionCall5(
1099 PG_GETARG_DATUM(0), PG_GETARG_DATUM(1),
1100 PG_GETARG_DATUM(2), PG_GETARG_DATUM(3),
1112 PG_RETURN_DATUM(DirectFunctionCall5(
1114 PG_GETARG_DATUM(0), PG_GETARG_DATUM(1),
1115 PG_GETARG_DATUM(2), PG_GETARG_DATUM(3),
1126 Node *arg1 = (Node*) linitial(args);
1127 Node *arg2 = (Node*) lsecond(args);
1128 Var *var1 = (Var*) arg1;
1129 Var *var2 = (Var*) arg2;
1131 POSTGIS_DEBUGF(2,
"%s: entered function", __func__);
1135 if (!IsA(arg1, Var) || !IsA(arg2, Var))
1137 POSTGIS_DEBUGF(1,
"%s called with arguments that are not column references", __func__);
1142 relid1 = rt_fetch(var1->varno, root->parse->rtable)->relid;
1143 relid2 = rt_fetch(var2->varno, root->parse->rtable)->relid;
1152 POSTGIS_DEBUGF(2,
"%s: cannot find stats for \"%s\"", __func__, get_rel_name(relid2) ? get_rel_name(relid2) :
"NULL");
1157 POSTGIS_DEBUGF(2,
"%s: cannot find stats for \"%s\"", __func__, get_rel_name(relid2) ? get_rel_name(relid2) :
"NULL");
1162 POSTGIS_DEBUGF(2,
"got selectivity %g", selectivity);
1179 PlannerInfo *root = (PlannerInfo *)PG_GETARG_POINTER(0);
1181 List *args = (List *)PG_GETARG_POINTER(2);
1182 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
1183 int mode = PG_GETARG_INT32(4);
1185 POSTGIS_DEBUGF(2,
"%s: entered function", __func__);
1188 if (list_length(args) != 2)
1190 POSTGIS_DEBUGF(2,
"%s: got nargs == %d", __func__, list_length(args));
1195 if (jointype != JOIN_INNER)
1197 POSTGIS_DEBUGF(1,
"%s: jointype %d not supported", __func__, jointype);
1224 int sample_rows,
double total_rows,
int mode)
1226 MemoryContext old_context;
1228 int notnull_cnt = 0;
1230 int histogram_features = 0;
1233 size_t nd_stats_size;
1235 double total_width = 0;
1236 double total_cell_count = 0;
1242 const ND_BOX **sample_boxes;
1247 int histo_cells_target;
1249 int histo_cells_new = 1;
1252 int histo_ndims = 0;
1253 double sample_distribution[
ND_DIMS];
1254 double total_distribution;
1272 POSTGIS_DEBUG(2,
"compute_gserialized_stats called");
1273 POSTGIS_DEBUGF(3,
" # sample_rows: %d", sample_rows);
1274 POSTGIS_DEBUGF(3,
" estimate of total_rows: %.6g", total_rows);
1280 sample_boxes = palloc(
sizeof(
ND_BOX*) * sample_rows);
1292 for ( i = 0; i < sample_rows; i++ )
1299 datum = fetchfunc(stats, i, &is_null);
1304 POSTGIS_DEBUGF(4,
" skipped null geometry %d", i);
1313 POSTGIS_DEBUGF(3,
" skipped empty geometry %d", i);
1324 POSTGIS_DEBUGF(3,
" skipped infinite/nan geometry %d", i);
1336 nd_box = palloc(
sizeof(
ND_BOX));
1340 sample_boxes[notnull_cnt] = nd_box;
1343 if ( ! notnull_cnt )
1350 total_width += toast_raw_datum_size(datum);
1353 for ( d = 0; d < ndims; d++ )
1355 sum.
min[d] += nd_box->
min[d];
1356 sum.
max[d] += nd_box->
max[d];
1363#if POSTGIS_PGSQL_VERSION >= 180
1364 vacuum_delay_point(
true);
1366 vacuum_delay_point();
1370#if POSTGIS_PGSQL_VERSION >= 170
1371 POSTGIS_DEBUGF(3,
" stats->attstattarget: %d", stats->attstattarget);
1374 POSTGIS_DEBUGF(3,
" stats->attr->attstattarget: %d", stats->attr->attstattarget);
1377 POSTGIS_DEBUGF(3,
" target # of histogram cells: %d", histo_cells_target);
1380 if ( ! notnull_cnt )
1382 stats->stats_valid =
false;
1386 POSTGIS_DEBUGF(3,
" sample_extent: %s",
nd_box_to_json(&sample_extent, ndims));
1392 for ( d = 0; d < ndims; d++ )
1395 avg.
min[d] = sum.
min[d] / notnull_cnt;
1396 avg.
max[d] = sum.
max[d] / notnull_cnt;
1399 for ( i = 0; i < notnull_cnt; i++ )
1401 const ND_BOX *ndb = sample_boxes[i];
1402 stddev.
min[d] += (ndb->
min[d] - avg.
min[d]) * (ndb->
min[d] - avg.
min[d]);
1403 stddev.
max[d] += (ndb->
max[d] - avg.
max[d]) * (ndb->
max[d] - avg.
max[d]);
1405 stddev.
min[d] = sqrt(stddev.
min[d] / notnull_cnt);
1406 stddev.
max[d] = sqrt(stddev.
max[d] / notnull_cnt);
1419 for ( i = 0; i < notnull_cnt; i++ )
1421 const ND_BOX *ndb = sample_boxes[i];
1425 POSTGIS_DEBUGF(4,
" feature %d is a hard deviant, skipped", i);
1426 sample_boxes[i] = NULL;
1437 histo_extent = histo_extent_new;
1452 sample_distribution);
1468 for ( d = 0; d < ndims; d++ )
1470 if ( sample_distribution[d] > 0 )
1474 if ( histo_ndims == 0 )
1478 POSTGIS_DEBUG(3,
" special case: no axes have variability");
1479 histo_cells_new = 1;
1480 for ( d = 0; d < ndims; d++ )
1482 histo_size[d] = (int)pow((
double)histo_cells_target, 1/(double)ndims);
1483 if ( ! histo_size[d] )
1485 POSTGIS_DEBUGF(3,
" histo_size[d]: %d", histo_size[d]);
1486 histo_cells_new *= histo_size[d];
1488 POSTGIS_DEBUGF(3,
" histo_cells_new: %d", histo_cells_new);
1497 POSTGIS_DEBUG(3,
" allocating histogram axes based on axis variability");
1498 total_distribution =
total_double(sample_distribution, ndims);
1499 POSTGIS_DEBUGF(3,
" total_distribution: %.8g", total_distribution);
1500 histo_cells_new = 1;
1501 for ( d = 0; d < ndims; d++ )
1503 if ( sample_distribution[d] == 0 )
1510 float edge_ratio = (float)sample_distribution[d] / (
float)total_distribution;
1520 histo_cells_new *= histo_size[d];
1522 POSTGIS_DEBUGF(3,
" histo_cells_new: %d", histo_cells_new);
1526 histo_cells = histo_cells_new;
1527 POSTGIS_DEBUGF(3,
" histo_cells: %d", histo_cells);
1532 old_context = MemoryContextSwitchTo(stats->anl_context);
1533 nd_stats_size =
sizeof(
ND_STATS) + ((histo_cells - 1) *
sizeof(float4));
1534 nd_stats = palloc(nd_stats_size);
1535 memset(nd_stats, 0, nd_stats_size);
1536 MemoryContextSwitchTo(old_context);
1539 nd_stats->
ndims = ndims;
1540 nd_stats->
extent = histo_extent;
1545 for ( d = 0; d < ndims; d++ )
1546 nd_stats->
size[d] = histo_size[d];
1561 for ( i = 0; i < notnull_cnt; i++ )
1566 double num_cells = 0;
1567 double min[
ND_DIMS] = {0.0, 0.0, 0.0, 0.0};
1568 double max[
ND_DIMS] = {0.0, 0.0, 0.0, 0.0};
1569 double cellsize[
ND_DIMS] = {0.0, 0.0, 0.0, 0.0};
1571 nd_box = sample_boxes[i];
1572 if ( ! nd_box )
continue;
1575#if POSTGIS_PGSQL_VERSION >= 180
1576 vacuum_delay_point(
true);
1578 vacuum_delay_point();
1583 memset(at, 0,
sizeof(
int)*
ND_DIMS);
1585 POSTGIS_DEBUGF(3,
" feature %d: ibox (%d, %d, %d, %d) (%d, %d, %d, %d)", i,
1586 nd_ibox.
min[0], nd_ibox.
min[1], nd_ibox.
min[2], nd_ibox.
min[3],
1587 nd_ibox.
max[0], nd_ibox.
max[1], nd_ibox.
max[2], nd_ibox.
max[3]);
1589 for ( d = 0; d < nd_stats->
ndims; d++ )
1592 at[d] = nd_ibox.
min[d];
1595 cellsize[d] = (max[d] - min[d])/(nd_stats->
size[d]);
1604 ND_BOX nd_cell = { {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0} };
1607 for ( d = 0; d < nd_stats->
ndims; d++ )
1609 nd_cell.
min[d] = min[d] + (at[d]+0) * cellsize[d];
1610 nd_cell.
max[d] = min[d] + (at[d]+1) * cellsize[d];
1621 POSTGIS_DEBUGF(3,
" ratio (%.8g) num_cells (%.8g)", ratio, num_cells);
1622 POSTGIS_DEBUGF(3,
" at (%d, %d, %d, %d)", at[0], at[1], at[2], at[3]);
1627 total_cell_count += num_cells;
1629 histogram_features++;
1632 POSTGIS_DEBUGF(3,
" histogram_features: %d", histogram_features);
1633 POSTGIS_DEBUGF(3,
" sample_rows: %d", sample_rows);
1634 POSTGIS_DEBUGF(3,
" table_rows: %.6g", total_rows);
1637 if ( ! histogram_features )
1639 POSTGIS_DEBUG(3,
" no stats have been gathered");
1640 elog(NOTICE,
" no features lie in the stats histogram, invalid stats");
1641 stats->stats_valid =
false;
1662 stats->stakind[stats_slot] = stats_kind;
1663 stats->staop[stats_slot] = InvalidOid;
1664 stats->stanumbers[stats_slot] = (float4*)nd_stats;
1665 stats->numnumbers[stats_slot] = nd_stats_size/
sizeof(float4);
1666 stats->stanullfrac = (float4)null_cnt/sample_rows;
1667 stats->stawidth = total_width/notnull_cnt;
1668 stats->stadistinct = -1.0;
1669 stats->stats_valid =
true;
1671 POSTGIS_DEBUGF(3,
" out: slot 0: kind %d (STATISTIC_KIND_ND)", stats->stakind[0]);
1672 POSTGIS_DEBUGF(3,
" out: slot 0: op %d (InvalidOid)", stats->staop[0]);
1673 POSTGIS_DEBUGF(3,
" out: slot 0: numnumbers %d", stats->numnumbers[0]);
1674 POSTGIS_DEBUGF(3,
" out: null fraction: %f=%d/%d", stats->stanullfrac, null_cnt, sample_rows);
1675 POSTGIS_DEBUGF(3,
" out: average width: %d bytes", stats->stawidth);
1676 POSTGIS_DEBUG (3,
" out: distinct values: all (no check done)");
1703 int sample_rows,
double total_rows)
1709 stats->extra_data = extra_data;
1714 if (stats->stats_valid)
1750 VacAttrStats *stats = (VacAttrStats *)PG_GETARG_POINTER(0);
1755 if (!std_typanalyze(stats))
1756 PG_RETURN_BOOL(
false);
1763 stats->extra_data = extra_data;
1766 PG_RETURN_BOOL(
true);
1792 double total_count = 0.0;
1798 elog(NOTICE,
" estimate_selectivity called with null input");
1812 POSTGIS_DEBUGF(3,
" mode: %d", mode);
1815 POSTGIS_DEBUG(3,
" in 2d mode, stripping the computation down to 2d");
1833 POSTGIS_DEBUG(3,
" search box does not overlap histogram, returning 0");
1840 POSTGIS_DEBUG(3,
" search box contains histogram, returning 1");
1847 POSTGIS_DEBUG(3,
" search box overlap with stats histogram failed");
1852 for ( d = 0; d < nd_stats->
ndims; d++ )
1857 cell_size[d] = (max[d] - min[d]) / nd_stats->
size[d];
1858 POSTGIS_DEBUGF(3,
" cell_size[%d] : %.9g", d, cell_size[d]);
1861 at[d] = nd_ibox.
min[d];
1867 float cell_count, ratio;
1868 ND_BOX nd_cell = { {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0} };
1871 for ( d = 0; d < nd_stats->
ndims; d++ )
1873 nd_cell.
min[d] = min[d] + (at[d]+0) * cell_size[d];
1874 nd_cell.
max[d] = min[d] + (at[d]+1) * cell_size[d];
1881 total_count += (double)cell_count * ratio;
1882 POSTGIS_DEBUGF(4,
" cell (%d,%d), cell value %.6f, ratio %.6f", at[0], at[1], cell_count, ratio);
1889 POSTGIS_DEBUGF(3,
" nd_stats->histogram_features = %f", nd_stats->
histogram_features);
1890 POSTGIS_DEBUGF(3,
" nd_stats->histogram_cells = %f", nd_stats->
histogram_cells);
1891 POSTGIS_DEBUGF(3,
" sum(overlapped histogram cells) = %f", total_count);
1892 POSTGIS_DEBUGF(3,
" selectivity = %f", selectivity);
1895 if (selectivity > 1.0) selectivity = 1.0;
1896 else if (selectivity < 0.0) selectivity = 0.0;
1910 Oid table_oid = PG_GETARG_OID(0);
1911 text *att_text = PG_GETARG_TEXT_P(1);
1916 bool only_parent =
false;
1919 if ( ! PG_ARGISNULL(2) )
1925 elog(ERROR,
"stats for \"%s.%s\" do not exist", get_rel_name(table_oid), text_to_cstring(att_text));
1930 json = cstring_to_text(
str);
1934 PG_RETURN_TEXT_P(json);
1945 Oid table_oid = PG_GETARG_OID(0);
1946 text *att_text = PG_GETARG_TEXT_P(1);
1947 Datum geom_datum = PG_GETARG_DATUM(2);
1949 float8 selectivity = 0;
1954 if ( ! PG_ARGISNULL(3) )
1961 elog(ERROR,
"stats for \"%s.%s\" do not exist", get_rel_name(table_oid), text_to_cstring(att_text));
1965 elog(ERROR,
"unable to calculate bounding box from geometry");
1973 PG_RETURN_FLOAT8(selectivity);
1984 Oid table_oid1 = PG_GETARG_OID(0);
1985 text *att_text1 = PG_GETARG_TEXT_P(1);
1986 Oid table_oid2 = PG_GETARG_OID(2);
1987 text *att_text2 = PG_GETARG_TEXT_P(3);
1989 float8 selectivity = 0;
1998 elog(ERROR,
"stats for \"%s.%s\" do not exist", get_rel_name(table_oid1), text_to_cstring(att_text1));
2001 elog(ERROR,
"stats for \"%s.%s\" do not exist", get_rel_name(table_oid2), text_to_cstring(att_text2));
2004 if ( ! PG_ARGISNULL(4) )
2006 text *modetxt = PG_GETARG_TEXT_P(4);
2007 char *modestr = text_to_cstring(modetxt);
2008 if ( modestr[0] ==
'N' )
2017 PG_RETURN_FLOAT8(selectivity);
2027 PG_RETURN_DATUM(DirectFunctionCall5(
2029 PG_GETARG_DATUM(0), PG_GETARG_DATUM(1),
2030 PG_GETARG_DATUM(2), PG_GETARG_DATUM(3),
2042 PG_RETURN_DATUM(DirectFunctionCall5(
2044 PG_GETARG_DATUM(0), PG_GETARG_DATUM(1),
2045 PG_GETARG_DATUM(2), PG_GETARG_DATUM(3),
2068 VariableStatData vardata;
2074 float8 selectivity = 0;
2077 POSTGIS_DEBUGF(2,
"%s: entered function", __func__);
2079 if (!get_restriction_variable(root, args, varRelid, &vardata, &other, &varonleft))
2081 POSTGIS_DEBUGF(2,
"%s: could not find vardata", __func__);
2085 if (!IsA(other, Const))
2087 ReleaseVariableStats(vardata);
2088 POSTGIS_DEBUGF(2,
"%s: no constant argument, returning default selectivity %g", __func__,
DEFAULT_ND_SEL);
2092 otherConst = (Const*)other;
2093 if ((!otherConst) || otherConst->constisnull)
2095 ReleaseVariableStats(vardata);
2096 POSTGIS_DEBUGF(2,
"%s: constant argument is NULL", __func__);
2102 ReleaseVariableStats(vardata);
2103 POSTGIS_DEBUGF(2,
"%s: search box is EMPTY", __func__);
2107 if (!vardata.statsTuple)
2109 POSTGIS_DEBUGF(1,
"%s: no statistics available on table. Empty? Need to ANALYZE?", __func__);
2114 ReleaseVariableStats(vardata);
2125 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2127 List *args = (List *) PG_GETARG_POINTER(2);
2128 int varRelid = PG_GETARG_INT32(3);
2129 int mode = PG_GETARG_INT32(4);
2131 POSTGIS_DEBUGF(2,
"%s: selectivity is %g", __func__, selectivity);
2132 PG_RETURN_FLOAT8(selectivity);
2146 HeapTuple index_tuple;
2147 Form_pg_index index_form;
2148 int16 index_attnum = InvalidAttrNumber;
2151 index_tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(index_oid));
2152 if (!HeapTupleIsValid(index_tuple))
2153 elog(ERROR,
"cache lookup failed for index %u", index_oid);
2155 index_form = (Form_pg_index) GETSTRUCT(index_tuple);
2158 if (index_form->indrelid != table_oid)
2159 elog(ERROR,
"table=%u and index=%u are not related", table_oid, index_oid);
2162 for (int16 i = 0; i < (int16)(index_form->indkey.dim1); i++)
2164 if (index_form->indkey.values[i] == table_attnum)
2170 ReleaseSysCache(index_tuple);
2171 return index_attnum;
2183 Form_pg_class index_rel_form;
2184 HeapTuple index_rel_tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(index_oid));
2186 if (!HeapTupleIsValid(index_rel_tuple))
2187 elog(ERROR,
"cache lookup failed for index %u", index_oid);
2189 index_rel_form = (Form_pg_class) GETSTRUCT(index_rel_tuple);
2190 index_am = index_rel_form->relam;
2191 ReleaseSysCache(index_rel_tuple);
2203 Oid atttypid = InvalidOid;
2204 Form_pg_attribute att_form;
2207 HeapTuple att_tuple = SearchSysCache2(ATTNUM,
2208 ObjectIdGetDatum(index_oid),
2209 Int16GetDatum(index_attnum));
2211 if (!HeapTupleIsValid(att_tuple))
2212 elog(ERROR,
"cache lookup failed for index %u attribute %d", index_oid, index_attnum);
2214 att_form = (Form_pg_attribute) GETSTRUCT(att_tuple);
2215 atttypid = att_form->atttypid;
2216 ReleaseSysCache(att_tuple);
2236 Oid b2d_oid = postgis_oid(BOX2DFOID);
2237 Oid gdx_oid = postgis_oid(GIDXOID);
2239 if (!(b2d_oid && gdx_oid))
2243 table_rel = RelationIdGetRelation(table_oid);
2244 index_list = RelationGetIndexList(table_rel);
2245 RelationClose(table_rel);
2248 foreach(lc, index_list)
2250 Oid index_oid = lfirst_oid(lc);
2257 if (*idx_attnum == InvalidAttrNumber)
2267 if (atttypid == b2d_oid || atttypid == gdx_oid)
2286 BOX2DF *bounds_2df = NULL;
2287 GIDX *bounds_gidx = NULL;
2292 unsigned long offset;
2293 unsigned long offset_max;
2298 idx_rel = index_open(idx_oid, AccessShareLock);
2299 buffer = ReadBuffer(idx_rel, GIST_ROOT_BLKNO);
2300 page = (Page) BufferGetPage(
buffer);
2301 offset = FirstOffsetNumber;
2302 offset_max = PageGetMaxOffsetNumber(page);
2303 while (offset <= offset_max)
2305 ItemId iid = PageGetItemId(page, offset);
2310 index_close(idx_rel, AccessShareLock);
2313 ituple = (IndexTuple) PageGetItem(page, iid);
2314 if (!GistTupleIsInvalid(ituple))
2317 Datum idx_attr = index_getattr(ituple, idx_att_num, idx_rel->rd_att, &isnull);
2322 BOX2DF *b = (BOX2DF*)DatumGetPointer(idx_attr);
2330 GIDX *b = (GIDX*)DatumGetPointer(idx_attr);
2342 index_close(idx_rel, AccessShareLock);
2359 gbox_from_gidx(bounds_gidx, gbox, flags);
2379 int16 att_num, idx_att_num = InvalidAttrNumber;
2380 Oid tbl_oid = PG_GETARG_DATUM(0);
2381 char *col = text_to_cstring(PG_GETARG_TEXT_P(1));
2388 postgis_initialize_cache();
2390 att_num = get_attnum(tbl_oid, col);
2391 if (att_num == InvalidAttrNumber)
2402 PG_RETURN_POINTER(gbox);
2413 HeapTuple att_tuple;
2414 Form_pg_attribute att;
2416 if (!attnum || !atttypid)
2417 elog(ERROR,
"%s got null input parameters", __func__);
2420 att_tuple = SearchSysCache2(ATTNAME,
2421 ObjectIdGetDatum(table_oid),
2422 PointerGetDatum(col));
2424 if (!HeapTupleIsValid(att_tuple))
2427 att = (Form_pg_attribute) GETSTRUCT(att_tuple);
2428 *atttypid = att->atttypid;
2429 *attnum = att->attnum;
2430 ReleaseSysCache(att_tuple);
2443 text *coltxt = NULL;
2445 int16 attnum, idx_attnum;
2446 Oid atttypid = InvalidOid;
2447 char nsp_tbl[2*NAMEDATALEN+6];
2449 Oid tbl_oid, idx_oid = 0;
2452 bool only_parent =
false;
2454 Oid geographyOid = postgis_oid(GEOGRAPHYOID);
2455 Oid geometryOid = postgis_oid(GEOMETRYOID);
2458 postgis_initialize_cache();
2460 if (PG_NARGS() < 2 || PG_NARGS() > 4)
2461 elog(ERROR,
"ST_EstimatedExtent() called with wrong number of arguments");
2463 if ( PG_NARGS() == 4 )
2465 only_parent = PG_GETARG_BOOL(3);
2467 if ( PG_NARGS() >= 3 )
2469 char *nsp = text_to_cstring(PG_GETARG_TEXT_P(0));
2470 tbl = text_to_cstring(PG_GETARG_TEXT_P(1));
2471 coltxt = PG_GETARG_TEXT_P(2);
2472 snprintf(nsp_tbl,
sizeof(nsp_tbl),
"\"%s\".\"%s\"", nsp, tbl);
2474 if ( PG_NARGS() == 2 )
2476 tbl = text_to_cstring(PG_GETARG_TEXT_P(0));
2477 coltxt = PG_GETARG_TEXT_P(1);
2478 snprintf(nsp_tbl,
sizeof(nsp_tbl),
"\"%s\"", tbl);
2482 tbl_oid = DatumGetObjectId(DirectFunctionCall1(regclassin, CStringGetDatum(nsp_tbl)));
2484 elog(ERROR,
"cannot lookup table %s", nsp_tbl);
2487 col = text_to_cstring(coltxt);
2489 elog(ERROR,
"column %s.\"%s\" does not exist", nsp_tbl, col);
2492 if ((atttypid != geographyOid) && (atttypid != geometryOid))
2494 elog(ERROR,
"column %s.\"%s\" must be a geometry or geography", nsp_tbl, col);
2500 if (idx_oid != InvalidOid)
2504 elog(DEBUG3,
"index for %s.\"%s\" exists, reading gbox from there", nsp_tbl, col);
2505 if (!gbox) PG_RETURN_NULL();
2512 elog(DEBUG3,
"index for %s.\"%s\" does not exist", nsp_tbl, col);
2515 if (atttypid == geographyOid)
2524 elog(WARNING,
"stats for \"%s.%s\" do not exist", tbl, col);
2534 if (stats_mode != 2)
2546 if (atttypid == geographyOid)
2550 PG_RETURN_POINTER(gbox_planar);
2553 PG_RETURN_POINTER(gbox);
2562 if ( PG_NARGS() == 3 )
2568 PG_GETARG_DATUM(2)));
2570 else if ( PG_NARGS() == 2 )
2575 PG_GETARG_DATUM(1)));
2578 elog(ERROR,
"geometry_estimated_extent() called with wrong number of arguments");
GBOX * gbox_new(lwflags_t flags)
Create a new gbox with the dimensionality indicated by the flags.
char * gbox_to_string(const GBOX *gbox)
Allocate a string representation of the GBOX, based on dimensionality of flags.
int gbox_is_valid(const GBOX *gbox)
Return false if any of the dimensions is NaN or infinite.
static int nd_box_intersects(const ND_BOX *a, const ND_BOX *b, int ndims)
Return true if ND_BOX a overlaps b, false otherwise.
static int nd_box_init_bounds(ND_BOX *a)
Prepare an ND_BOX for bounds calculation: set the maxes to the smallest thing possible and the mins t...
Datum gserialized_gist_joinsel_2d(PG_FUNCTION_ARGS)
static int index_get_keytype(Oid index_oid, int16 index_attnum)
static int nd_increment(ND_IBOX *ibox, int ndims, int *counter)
Given an n-d index array (counter), and a domain to increment it in (ibox) increment it by one,...
static ND_STATS * pg_get_nd_stats(const Oid table_oid, AttrNumber att_num, int mode, bool only_parent)
Pull the stats object from the PgSQL system catalogs.
#define STATISTIC_SLOT_ND
static int gbox_ndims(const GBOX *gbox)
Given that geodetic boxes are X/Y/Z regardless of the underlying geometry dimensionality and other bo...
static char * nd_box_to_json(const ND_BOX *nd_box, int ndims)
Convert an ND_BOX to a JSON string for printing.
Datum gserialized_gist_joinsel_nd(PG_FUNCTION_ARGS)
static float8 estimate_selectivity(const GBOX *box, const ND_STATS *nd_stats, int mode)
This function returns an estimate of the selectivity of a search GBOX by looking at data in the ND_ST...
static int range_full(int *vals, int nvals)
The difference between the fourth and first quintile values, the "inter-quintile range".
static char * nd_stats_to_json(const ND_STATS *nd_stats)
Convert an ND_STATS to a JSON representation for external use.
#define STATISTIC_KIND_2D
static int nd_box_merge(const ND_BOX *source, ND_BOX *target)
Expand the bounds of target to include source.
#define DEFAULT_ND_JOINSEL
#define STATISTIC_KIND_ND
#define FALLBACK_ND_SEL
More modest fallback selectivity factor.
PG_FUNCTION_INFO_V1(gserialized_gist_joinsel_nd)
For (geometry &&& geometry) and (geography && geography) we call into the N-D mode.
Datum gserialized_estimated_extent(PG_FUNCTION_ARGS)
#define DEFAULT_ND_SEL
Default geometry selectivity factor.
Datum _postgis_gserialized_joinsel(PG_FUNCTION_ARGS)
static double total_double(const double *vals, int nvals)
Given double array, return sum of values.
static bool get_attnum_attypid(Oid table_oid, const char *col, int16 *attnum, Oid *atttypid)
static GBOX * spatial_index_read_extent(Oid idx_oid, int idx_att_num, int key_type)
#define FALLBACK_ND_JOINSEL
static void compute_gserialized_stats_mode(VacAttrStats *stats, AnalyzeAttrFetchFunc fetchfunc, int sample_rows, double total_rows, int mode)
The gserialized_analyze_nd sets this function as a callback on the stats object when called by the AN...
static int cmp_int(const void *a, const void *b)
Integer comparison function for qsort.
static int nd_box_contains(const ND_BOX *a, const ND_BOX *b, int ndims)
Return true if ND_BOX a contains b, false otherwise.
static void compute_gserialized_stats(VacAttrStats *stats, AnalyzeAttrFetchFunc fetchfunc, int sample_rows, double total_rows)
In order to do useful selectivity calculations in both 2-D and N-D modes, we actually have to generat...
static int text_p_get_mode(const text *txt)
Utility function to see if the first letter of the mode argument is 'N'.
static ND_STATS * pg_nd_stats_from_tuple(HeapTuple stats_tuple, int mode)
Datum gserialized_gist_sel(PG_FUNCTION_ARGS)
float8 gserialized_joinsel_internal(PlannerInfo *root, List *args, JoinType jointype, int mode)
static void nd_box_from_gbox(const GBOX *gbox, ND_BOX *nd_box)
Set the values of an ND_BOX from a GBOX.
float8 gserialized_sel_internal(PlannerInfo *root, List *args, int varRelid, int mode)
This function should return an estimation of the number of rows returned by a query involving an over...
Datum _postgis_gserialized_stats(PG_FUNCTION_ARGS)
static int nd_box_init(ND_BOX *a)
Zero out an ND_BOX.
Datum gserialized_gist_sel_nd(PG_FUNCTION_ARGS)
#define MAX_DIMENSION_WIDTH
Maximum width of a dimension that we'll bother trying to compute statistics on.
Datum gserialized_analyze_nd(PG_FUNCTION_ARGS)
static Oid table_get_spatial_index(Oid tbl_oid, int16 attnum, int *key_type, int16 *idx_attnum)
static int index_get_am(Oid index_oid)
Datum _postgis_gserialized_sel(PG_FUNCTION_ARGS)
static ND_STATS * pg_get_nd_stats_by_name(const Oid table_oid, const text *att_text, int mode, bool only_parent)
Pull the stats object from the PgSQL system catalogs.
static int nd_box_expand(ND_BOX *nd_box, double expansion_factor)
Expand an ND_BOX ever so slightly.
static int nd_box_overlap(const ND_STATS *nd_stats, const ND_BOX *nd_box, ND_IBOX *nd_ibox)
What stats cells overlap with this ND_BOX? Put the lowest cell addresses in ND_IBOX->min and the high...
static float8 estimate_join_selectivity(const ND_STATS *s1, const ND_STATS *s2)
Given two statistics histograms, what is the selectivity of a join driven by the && or &&& operator?
Datum gserialized_gist_sel_2d(PG_FUNCTION_ARGS)
Datum _postgis_gserialized_index_extent(PG_FUNCTION_ARGS)
Datum gserialized_gist_joinsel(PG_FUNCTION_ARGS)
#define MIN_DIMENSION_WIDTH
Minimum width of a dimension that we'll bother trying to compute statistics on.
static char * nd_stats_to_grid(const ND_STATS *stats)
Create a printable view of the ND_STATS histogram.
Datum geometry_estimated_extent(PG_FUNCTION_ARGS)
#define STATISTIC_SLOT_2D
static int nd_box_array_distribution(const ND_BOX **nd_boxes, int num_boxes, const ND_BOX *extent, int ndims, double *distribution)
Calculate how much a set of boxes is homogeneously distributed or contentrated within one dimension,...
static int16 index_has_attr(Oid index_oid, Oid table_oid, int16 table_attnum)
struct ND_STATS_T ND_STATS
static int histogram_axis_cells(int histo_cells_target, int histo_ndims, double edge_ratio)
static double nd_box_ratio(const ND_BOX *cover, const ND_BOX *target, int ndims)
static int histogram_cell_budget(double total_rows, int ndims, int attstattarget)
static int nd_stats_value_index(const ND_STATS *stats, const int *indexes)
void box2df_merge(BOX2DF *b_union, BOX2DF *b_new)
bool box2df_is_empty(const BOX2DF *a)
int box2df_to_gbox_p(BOX2DF *a, GBOX *box)
int gserialized_datum_get_gbox_p(Datum gsdatum, GBOX *gbox)
Given a GSERIALIZED datum, as quickly as possible (peaking into the top of the memory) return the gbo...
BOX2DF * box2df_copy(BOX2DF *b)
bool gidx_is_unknown(const GIDX *a)
GIDX * gidx_copy(GIDX *b)
void gidx_merge(GIDX **b_union, GIDX *b_new)
#define FLAGS_GET_Z(flags)
#define FLAGS_GET_M(flags)
#define FLAGS_SET_M(flags, value)
#define FLAGS_SET_Z(flags, value)
#define FLAGS_GET_GEODETIC(flags)
This library is the generic geometry handling section of PostGIS.
int gbox_geocentric_get_gbox_cartesian(const GBOX *gbox_geocentric, GBOX *gbox_planar)
Datum buffer(PG_FUNCTION_ARGS)
stringbuffer_t * stringbuffer_create(void)
Allocate a new stringbuffer_t.
int stringbuffer_aprintf(stringbuffer_t *s, const char *fmt,...)
Appends a formatted string to the current string buffer, using the format and argument list provided.
char * stringbuffer_getstringcopy(stringbuffer_t *s)
Returns a newly allocated string large enough to contain the current state of the string.
void stringbuffer_destroy(stringbuffer_t *s)
Free the stringbuffer_t and all memory managed within it.
static void stringbuffer_append(stringbuffer_t *s, const char *a)
Append the specified string to the stringbuffer_t.
float4 histogram_features