64 #include "access/genam.h"
65 #include "access/gin.h"
66 #include "access/gist.h"
67 #include "access/gist_private.h"
68 #include "access/gistscan.h"
69 #include "utils/datum.h"
70 #include "access/heapam.h"
71 #include "catalog/index.h"
72 #include "catalog/pg_am.h"
73 #include "miscadmin.h"
74 #include "storage/lmgr.h"
75 #include "catalog/namespace.h"
76 #include "catalog/indexing.h"
77 #if PG_VERSION_NUM >= 100000
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 #if PG_VERSION_NUM < 120000
94 #include "nodes/relation.h"
96 #include "nodes/pathnodes.h"
98 #include "parser/parsetree.h"
99 #include "utils/array.h"
100 #include "utils/lsyscache.h"
101 #include "utils/builtins.h"
102 #include "utils/syscache.h"
103 #include "utils/rel.h"
104 #include "utils/selfuncs.h"
106 #include "../postgis_config.h"
108 #if POSTGIS_PGSQL_VERSION >= 93
109 #include "access/htup_details.h"
114 #include "lwgeom_pg.h"
115 #include "gserialized_gist.h"
132 #ifndef HAVE_ISFINITE
133 # ifdef HAVE_GNU_ISFINITE
136 # define isfinite finite
173 #define STATISTIC_KIND_ND 102
174 #define STATISTIC_KIND_2D 103
175 #define STATISTIC_SLOT_ND 0
176 #define STATISTIC_SLOT_2D 1
184 #define SDFACTOR 3.25
199 #define MIN_DIMENSION_WIDTH 0.000000001
205 #define MAX_DIMENSION_WIDTH 1.0E+20
210 #define DEFAULT_ND_SEL 0.0001
211 #define DEFAULT_ND_JOINSEL 0.001
216 #define FALLBACK_ND_SEL 0.2
217 #define FALLBACK_ND_JOINSEL 0.3
313 if (VARSIZE(txt) - VARHDRSZ <= 0)
315 modestr = (
char*)VARDATA(txt);
316 if ( modestr[0] ==
'N' )
328 int ia = *((
const int*)a);
329 int ib = *((
const int*)b);
346 qsort(vals, nvals,
sizeof(
int),
cmp_int);
347 return vals[4*nvals/5] - vals[nvals/5];
359 for ( i = 0; i < nvals; i++ )
365 #if POSTGIS_DEBUG_LEVEL >= 3
371 total_int(
const int *vals,
int nvals)
376 for ( i = 0; i < nvals; i++ )
386 avg(
const int *vals,
int nvals)
388 int t = total_int(vals, nvals);
389 return (
double)t / (double)nvals;
396 stddev(
const int *vals,
int nvals)
400 double mean = avg(vals, nvals);
403 for ( i = 0; i < nvals; i++ )
405 double v = (double)(vals[i]);
406 sigma2 += (mean - v) * (mean - v);
408 return sqrt(sigma2 / nvals);
420 int accum = 1, vdx = 0;
425 for ( d = 0; d < (int)(stats->
ndims); d++ )
427 int size = (int)(stats->
size[d]);
428 if ( indexes[d] < 0 || indexes[d] >= size )
430 POSTGIS_DEBUGF(3,
" bad index at (%d, %d)", indexes[0], indexes[1]);
433 vdx += indexes[d] * accum;
450 for ( i = 0; i < ndims; i++ )
456 for ( i = 0; i < ndims; i++ )
476 char *json_extent, *str;
479 int ndims = (int)roundf(nd_stats->
ndims);
486 for ( d = 0; d < ndims; d++ )
546 for ( d = 0; d <
ND_DIMS; d++ )
548 target->
min[d] = Min(target->
min[d], source->
min[d]);
549 target->
max[d] = Max(target->
max[d], source->
max[d]);
558 memset(a, 0,
sizeof(
ND_BOX));
571 for ( d = 0; d <
ND_DIMS; d++ )
574 a->
max[d] = -1 * FLT_MAX;
621 for ( d = 0; d < ndims; d++ )
623 if ( (a->
min[d] > b->
max[d]) || (a->
max[d] < b->
min[d]) )
636 for ( d = 0; d < ndims; d++ )
638 if ( ! ((a->
min[d] < b->
min[d]) && (a->
max[d] > b->
max[d])) )
653 for ( d = 0; d <
ND_DIMS; d++ )
655 size = nd_box->
max[d] - nd_box->
min[d];
659 nd_box->
min[d] -= size * expansion_factor / 2;
660 nd_box->
max[d] += size * expansion_factor / 2;
677 memset(nd_ibox, 0,
sizeof(
ND_IBOX));
680 for ( d = 0; d < nd_stats->
ndims; d++ )
684 double width = smax - smin;
692 int size = (int)roundf(nd_stats->
size[d]);
695 nd_ibox->
min[d] = floor(size * (nd_box->
min[d] - smin) / width);
696 nd_ibox->
max[d] = floor(size * (nd_box->
max[d] - smin) / width);
698 POSTGIS_DEBUGF(5,
" stats: dim %d: min %g: max %g: width %g", d, smin, smax, width);
699 POSTGIS_DEBUGF(5,
" overlap: dim %d: (%d, %d)", d, nd_ibox->
min[d], nd_ibox->
max[d]);
702 nd_ibox->
min[d] = Max(nd_ibox->
min[d], 0);
703 nd_ibox->
max[d] = Min(nd_ibox->
max[d], size - 1);
721 for ( d = 0 ; d < ndims; d++ )
723 if ( b1->
max[d] <= b2->
min[d] || b1->
min[d] >= b2->
max[d] )
726 if ( b1->
min[d] > b2->
min[d] || b1->
max[d] < b2->
max[d] )
733 for ( d = 0; d < ndims; d++ )
735 double width1 = b1->
max[d] - b1->
min[d];
736 double width2 = b2->
max[d] - b2->
min[d];
737 double imin, imax, iwidth;
742 imin = Max(b1->
min[d], b2->
min[d]);
743 imax = Min(b1->
max[d], b2->
max[d]);
744 iwidth = imax - imin;
745 iwidth = Max(0.0, iwidth);
781 #if POSTGIS_DEBUG_LEVEL >= 3
782 double average, sdev, sdev_ratio;
788 for ( d = 0; d < ndims; d++ )
791 memset(counts, 0,
sizeof(counts));
793 smin = extent->
min[d];
794 smax = extent->
max[d];
795 swidth = smax - smin;
809 for ( i = 0; i < num_boxes; i++ )
811 double minoffset, maxoffset;
815 if ( ! ndb )
continue;
818 minoffset = ndb->
min[d] - smin;
819 maxoffset = ndb->
max[d] - smin;
822 if ( minoffset < 0 || minoffset > swidth ||
823 maxoffset < 0 || maxoffset > swidth )
829 bmin = floor(
NUM_BINS * minoffset / swidth);
830 bmax = floor(
NUM_BINS * maxoffset / swidth);
835 POSTGIS_DEBUGF(4,
" dimension %d, feature %d: bin %d to bin %d", d, i, bmin, bmax);
838 for ( k = bmin; k <= bmax; k++ )
848 #if POSTGIS_DEBUG_LEVEL >= 3
851 sdev_ratio = sdev/average;
853 POSTGIS_DEBUGF(3,
" dimension %d: range = %d", d, range);
854 POSTGIS_DEBUGF(3,
" dimension %d: average = %.6g", d, average);
855 POSTGIS_DEBUGF(3,
" dimension %d: stddev = %.6g", d, sdev);
856 POSTGIS_DEBUGF(3,
" dimension %d: stddev_ratio = %.6g", d, sdev_ratio);
859 distribution[d] = range;
877 if ( counter[d] < ibox->
max[d] )
882 counter[d] = ibox->
min[d];
905 #if POSTGIS_PGSQL_VERSION < 100
910 rv = get_attstatsslot(stats_tuple, 0, 0, stats_kind, InvalidOid,
911 NULL, NULL, NULL, &floatptr, &nvalues);
914 POSTGIS_DEBUGF(2,
"no slot of kind %d in stats tuple", stats_kind);
919 nd_stats = palloc(
sizeof(
float) * nvalues);
920 memcpy(nd_stats, floatptr,
sizeof(
float) * nvalues);
923 free_attstatsslot(0, NULL, 0, floatptr, nvalues);
928 rv = get_attstatsslot(&sslot, stats_tuple, stats_kind, InvalidOid,
929 ATTSTATSSLOT_NUMBERS);
931 POSTGIS_DEBUGF(2,
"no slot of kind %d in stats tuple", stats_kind);
936 nd_stats = palloc(
sizeof(float4) * sslot.nnumbers);
937 memcpy(nd_stats, sslot.numbers,
sizeof(float4) * sslot.nnumbers);
939 free_attstatsslot(&sslot);
953 HeapTuple stats_tuple = NULL;
959 POSTGIS_DEBUGF(2,
"searching whole tree stats for \"%s\"", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
960 stats_tuple = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(table_oid), Int16GetDatum(att_num), BoolGetDatum(
true));
962 POSTGIS_DEBUGF(2,
"found whole tree stats for \"%s\"", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
965 if ( only_parent || ! stats_tuple )
967 POSTGIS_DEBUGF(2,
"searching parent table stats for \"%s\"", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
968 stats_tuple = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(table_oid), Int16GetDatum(att_num), BoolGetDatum(
false));
970 POSTGIS_DEBUGF(2,
"found parent table stats for \"%s\"", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
974 POSTGIS_DEBUGF(2,
"stats for \"%s\" do not exist", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
979 ReleaseSysCache(stats_tuple);
983 "histogram for attribute %d of table \"%s\" does not exist?",
984 att_num, get_rel_name(table_oid));
1008 att_num = get_attnum(table_oid, att_name);
1010 elog(ERROR,
"attribute \"%s\" does not exist", att_name);
1016 elog(ERROR,
"attribute name is null");
1039 int ncells1, ncells2;
1040 int ndims1, ndims2, ndims;
1042 double ntuples_not_null1, ntuples_not_null2;
1061 if ( ! ( s1 && s2 ) )
1063 elog(NOTICE,
" estimate_join_selectivity called with null inputs");
1072 if ( ncells1 > ncells2 )
1090 ntuples_max = ntuples_not_null1 * ntuples_not_null2;
1093 ndims1 = (int)roundf(s1->
ndims);
1094 ndims2 = (int)roundf(s2->
ndims);
1095 ndims = Max(ndims1, ndims2);
1104 POSTGIS_DEBUG(3,
"relation stats do not intersect, returning 0");
1105 PG_RETURN_FLOAT8(0.0);
1114 POSTGIS_DEBUG(3,
"could not calculate overlap of relations");
1119 for ( d = 0; d < ndims1; d++ )
1121 at1[d] = ibox1.
min[d];
1124 size1[d] = (int)roundf(s1->
size[d]);
1125 cellsize1[d] = width1[d] / size1[d];
1129 for ( d = 0; d < ndims2; d++ )
1133 size2[d] = (int)roundf(s2->
size[d]);
1134 cellsize2[d] = width2[d] / size2[d];
1144 for ( d = 0; d < ndims1; d++ )
1146 nd_cell1.
min[d] = min1[d] + (at1[d]+0) * cellsize1[d];
1147 nd_cell1.
max[d] = min1[d] + (at1[d]+1) * cellsize1[d];
1154 for ( d = 0; d < ndims2; d++ )
1156 at2[d] = ibox2.
min[d];
1159 POSTGIS_DEBUGF(3,
"at1 %d,%d %s", at1[0], at1[1],
nd_box_to_json(&nd_cell1, ndims1));
1173 for ( d = 0; d < ndims2; d++ )
1175 nd_cell2.
min[d] = min2[d] + (at2[d]+0) * cellsize2[d];
1176 nd_cell2.
max[d] = min2[d] + (at2[d]+1) * cellsize2[d];
1179 POSTGIS_DEBUGF(3,
" at2 %d,%d %s", at2[0], at2[1],
nd_box_to_json(&nd_cell2, ndims2));
1182 ratio2 =
nd_box_ratio(&nd_cell1, &nd_cell2, Max(ndims1, ndims2));
1186 POSTGIS_DEBUGF(3,
" val1 %.6g val2 %.6g ratio %.6g", val1, val2, ratio2);
1187 val += val1 * (val2 * ratio2);
1194 POSTGIS_DEBUGF(3,
"val of histogram = %g", val);
1205 POSTGIS_DEBUGF(3,
"val scaled to full table size = %g", val);
1222 selectivity = val / ntuples_max;
1225 if ( isnan(selectivity) || ! isfinite(selectivity) || selectivity < 0.0 )
1229 else if ( selectivity > 1.0 )
1244 PG_RETURN_DATUM(DirectFunctionCall5(
1246 PG_GETARG_DATUM(0), PG_GETARG_DATUM(1),
1247 PG_GETARG_DATUM(2), PG_GETARG_DATUM(3),
1259 PG_RETURN_DATUM(DirectFunctionCall5(
1261 PG_GETARG_DATUM(0), PG_GETARG_DATUM(1),
1262 PG_GETARG_DATUM(2), PG_GETARG_DATUM(3),
1278 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1280 List *
args = (List *) PG_GETARG_POINTER(2);
1281 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
1282 int mode = PG_GETARG_INT32(4);
1292 if (jointype != JOIN_INNER)
1294 elog(DEBUG1,
"%s: jointype %d not supported", __func__, jointype);
1299 arg1 = (Node*) linitial(
args);
1300 arg2 = (Node*) lsecond(
args);
1306 if (!IsA(arg1, Var) || !IsA(arg2, Var))
1308 elog(DEBUG1,
"%s called with arguments that are not column references", __func__);
1313 relid1 = rt_fetch(var1->varno, root->parse->rtable)->relid;
1314 relid2 = rt_fetch(var2->varno, root->parse->rtable)->relid;
1316 POSTGIS_DEBUGF(3,
"using relations \"%s\" Oid(%d), \"%s\" Oid(%d)",
1317 get_rel_name(relid1) ? get_rel_name(relid1) :
"NULL", relid1, get_rel_name(relid2) ? get_rel_name(relid2) :
"NULL", relid2);
1326 POSTGIS_DEBUGF(3,
"unable to retrieve stats for \"%s\" Oid(%d)", get_rel_name(relid1) ? get_rel_name(relid1) :
"NULL" , relid1);
1329 else if ( ! stats2 )
1331 POSTGIS_DEBUGF(3,
"unable to retrieve stats for \"%s\" Oid(%d)", get_rel_name(relid2) ? get_rel_name(relid2) :
"NULL", relid2);
1336 POSTGIS_DEBUGF(2,
"got selectivity %g", selectivity);
1340 PG_RETURN_FLOAT8(selectivity);
1366 int sample_rows,
double total_rows,
int mode)
1368 MemoryContext old_context;
1370 int notnull_cnt = 0;
1372 int histogram_features = 0;
1375 size_t nd_stats_size;
1377 double total_width = 0;
1378 double total_sample_volume = 0;
1379 double total_cell_count = 0;
1385 const ND_BOX **sample_boxes;
1390 int histo_cells_target;
1392 int histo_cells_new = 1;
1395 int histo_ndims = 0;
1396 double sample_distribution[
ND_DIMS];
1397 double total_distribution;
1415 POSTGIS_DEBUG(2,
"compute_gserialized_stats called");
1416 POSTGIS_DEBUGF(3,
" # sample_rows: %d", sample_rows);
1417 POSTGIS_DEBUGF(3,
" estimate of total_rows: %.6g", total_rows);
1423 sample_boxes = palloc(
sizeof(
ND_BOX*) * sample_rows);
1435 for ( i = 0; i < sample_rows; i++ )
1444 datum = fetchfunc(stats, i, &is_null);
1449 POSTGIS_DEBUGF(4,
" skipped null geometry %d", i);
1456 is_copy = VARATT_IS_EXTENDED(datum);
1460 POSTGIS_DEBUGF(3,
" skipped empty geometry %d", i);
1471 POSTGIS_DEBUGF(3,
" skipped infinite/nan geometry %d", i);
1483 nd_box = palloc(
sizeof(
ND_BOX));
1487 sample_boxes[notnull_cnt] = nd_box;
1490 if ( ! notnull_cnt )
1497 total_width += VARSIZE(geom);
1500 for ( d = 0; d < ndims; d++ )
1502 sum.
min[d] += nd_box->
min[d];
1503 sum.
max[d] += nd_box->
max[d];
1514 vacuum_delay_point();
1525 histo_cells_target = (int)pow((
double)(stats->attr->attstattarget), (
double)ndims);
1526 histo_cells_target = Min(histo_cells_target, ndims * 10000);
1527 histo_cells_target = Min(histo_cells_target, (
int)(total_rows/5));
1528 POSTGIS_DEBUGF(3,
" stats->attr->attstattarget: %d", stats->attr->attstattarget);
1529 POSTGIS_DEBUGF(3,
" target # of histogram cells: %d", histo_cells_target);
1532 if ( ! notnull_cnt )
1534 elog(NOTICE,
"no non-null/empty features, unable to compute statistics");
1535 stats->stats_valid =
false;
1539 POSTGIS_DEBUGF(3,
" sample_extent: %s",
nd_box_to_json(&sample_extent, ndims));
1545 for ( d = 0; d < ndims; d++ )
1548 avg.
min[d] = sum.
min[d] / notnull_cnt;
1549 avg.
max[d] = sum.
max[d] / notnull_cnt;
1552 for ( i = 0; i < notnull_cnt; i++ )
1554 const ND_BOX *ndb = sample_boxes[i];
1555 stddev.
min[d] += (ndb->
min[d] - avg.
min[d]) * (ndb->
min[d] - avg.
min[d]);
1556 stddev.
max[d] += (ndb->
max[d] - avg.
max[d]) * (ndb->
max[d] - avg.
max[d]);
1558 stddev.
min[d] = sqrt(stddev.
min[d] / notnull_cnt);
1559 stddev.
max[d] = sqrt(stddev.
max[d] / notnull_cnt);
1572 for ( i = 0; i < notnull_cnt; i++ )
1574 const ND_BOX *ndb = sample_boxes[i];
1578 POSTGIS_DEBUGF(4,
" feature %d is a hard deviant, skipped", i);
1579 sample_boxes[i] = NULL;
1590 histo_extent = histo_extent_new;
1605 sample_distribution);
1621 for ( d = 0; d < ndims; d++ )
1623 if ( sample_distribution[d] > 0 )
1627 if ( histo_ndims == 0 )
1631 POSTGIS_DEBUG(3,
" special case: no axes have variability");
1632 histo_cells_new = 1;
1633 for ( d = 0; d < ndims; d++ )
1635 histo_size[d] = 1 + (int)pow((
double)histo_cells_target, 1/(double)ndims);
1636 POSTGIS_DEBUGF(3,
" histo_size[d]: %d", histo_size[d]);
1637 histo_cells_new *= histo_size[d];
1639 POSTGIS_DEBUGF(3,
" histo_cells_new: %d", histo_cells_new);
1648 POSTGIS_DEBUG(3,
" allocating histogram axes based on axis variability");
1649 total_distribution =
total_double(sample_distribution, ndims);
1650 POSTGIS_DEBUGF(3,
" total_distribution: %.8g", total_distribution);
1651 histo_cells_new = 1;
1652 for ( d = 0; d < ndims; d++ )
1654 if ( sample_distribution[d] == 0 )
1661 float edge_ratio = (float)sample_distribution[d] / (
float)total_distribution;
1667 histo_size[d] = (int)pow(histo_cells_target * histo_ndims * edge_ratio, 1/(
double)histo_ndims);
1669 if ( ! histo_size[d] )
1672 histo_cells_new *= histo_size[d];
1674 POSTGIS_DEBUGF(3,
" histo_cells_new: %d", histo_cells_new);
1678 histo_cells = histo_cells_new;
1679 POSTGIS_DEBUGF(3,
" histo_cells: %d", histo_cells);
1684 old_context = MemoryContextSwitchTo(stats->anl_context);
1685 nd_stats_size =
sizeof(
ND_STATS) + ((histo_cells - 1) *
sizeof(float4));
1686 nd_stats = palloc(nd_stats_size);
1687 memset(nd_stats, 0, nd_stats_size);
1688 MemoryContextSwitchTo(old_context);
1691 nd_stats->
ndims = ndims;
1692 nd_stats->
extent = histo_extent;
1697 for ( d = 0; d < ndims; d++ )
1698 nd_stats->
size[d] = histo_size[d];
1713 for ( i = 0; i < notnull_cnt; i++ )
1719 double num_cells = 0;
1720 double tmp_volume = 1.0;
1721 double min[
ND_DIMS] = {0.0, 0.0, 0.0, 0.0};
1722 double max[
ND_DIMS] = {0.0, 0.0, 0.0, 0.0};
1723 double cellsize[
ND_DIMS] = {0.0, 0.0, 0.0, 0.0};
1725 nd_box = sample_boxes[i];
1726 if ( ! nd_box )
continue;
1729 vacuum_delay_point();
1733 memset(at, 0,
sizeof(
int)*
ND_DIMS);
1735 POSTGIS_DEBUGF(3,
" feature %d: ibox (%d, %d, %d, %d) (%d, %d, %d, %d)", i,
1736 nd_ibox.
min[0], nd_ibox.
min[1], nd_ibox.
min[2], nd_ibox.
min[3],
1737 nd_ibox.
max[0], nd_ibox.
max[1], nd_ibox.
max[2], nd_ibox.
max[3]);
1739 for ( d = 0; d < nd_stats->
ndims; d++ )
1742 at[d] = nd_ibox.
min[d];
1745 cellsize[d] = (max[d] - min[d])/(nd_stats->
size[d]);
1748 tmp_volume *= (nd_box->
max[d] - nd_box->
min[d]);
1752 total_sample_volume += tmp_volume;
1760 ND_BOX nd_cell = { {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0} };
1763 for ( d = 0; d < nd_stats->
ndims; d++ )
1765 nd_cell.
min[d] = min[d] + (at[d]+0) * cellsize[d];
1766 nd_cell.
max[d] = min[d] + (at[d]+1) * cellsize[d];
1777 POSTGIS_DEBUGF(3,
" ratio (%.8g) num_cells (%.8g)", ratio, num_cells);
1778 POSTGIS_DEBUGF(3,
" at (%d, %d, %d, %d)", at[0], at[1], at[2], at[3]);
1783 total_cell_count += num_cells;
1785 histogram_features++;
1788 POSTGIS_DEBUGF(3,
" histogram_features: %d", histogram_features);
1789 POSTGIS_DEBUGF(3,
" sample_rows: %d", sample_rows);
1790 POSTGIS_DEBUGF(3,
" table_rows: %.6g", total_rows);
1793 if ( ! histogram_features )
1795 POSTGIS_DEBUG(3,
" no stats have been gathered");
1796 elog(NOTICE,
" no features lie in the stats histogram, invalid stats");
1797 stats->stats_valid =
false;
1818 stats->stakind[stats_slot] = stats_kind;
1819 stats->staop[stats_slot] = InvalidOid;
1820 stats->stanumbers[stats_slot] = (float4*)nd_stats;
1821 stats->numnumbers[stats_slot] = nd_stats_size/
sizeof(float4);
1822 stats->stanullfrac = (float4)null_cnt/sample_rows;
1823 stats->stawidth = total_width/notnull_cnt;
1824 stats->stadistinct = -1.0;
1825 stats->stats_valid =
true;
1827 POSTGIS_DEBUGF(3,
" out: slot 0: kind %d (STATISTIC_KIND_ND)", stats->stakind[0]);
1828 POSTGIS_DEBUGF(3,
" out: slot 0: op %d (InvalidOid)", stats->staop[0]);
1829 POSTGIS_DEBUGF(3,
" out: slot 0: numnumbers %d", stats->numnumbers[0]);
1830 POSTGIS_DEBUGF(3,
" out: null fraction: %f=%d/%d", stats->stanullfrac, null_cnt, sample_rows);
1831 POSTGIS_DEBUGF(3,
" out: average width: %d bytes", stats->stawidth);
1832 POSTGIS_DEBUG (3,
" out: distinct values: all (no check done)");
1861 int sample_rows,
double total_rows)
1900 VacAttrStats *stats = (VacAttrStats *)PG_GETARG_POINTER(0);
1901 Form_pg_attribute attr = stats->attr;
1903 POSTGIS_DEBUG(2,
"gserialized_analyze_nd called");
1907 if (attr->attstattarget < 0)
1908 attr->attstattarget = default_statistics_target;
1910 POSTGIS_DEBUGF(3,
" attribute stat target: %d", attr->attstattarget);
1915 stats->minrows = 300 * stats->attr->attstattarget;
1918 POSTGIS_DEBUGF(3,
" minrows: %d", stats->minrows);
1921 PG_RETURN_BOOL(
true);
1947 double total_count = 0.0;
1953 elog(NOTICE,
" estimate_selectivity called with null input");
1967 POSTGIS_DEBUGF(3,
" mode: %d", mode);
1970 POSTGIS_DEBUG(3,
" in 2d mode, stripping the computation down to 2d");
1986 POSTGIS_DEBUG(3,
" search box does not overlap histogram, returning 0");
1993 POSTGIS_DEBUG(3,
" search box contains histogram, returning 1");
2000 POSTGIS_DEBUG(3,
" search box overlap with stats histogram failed");
2005 for ( d = 0; d < nd_stats->
ndims; d++ )
2010 cell_size[d] = (max[d] - min[d]) / nd_stats->
size[d];
2011 POSTGIS_DEBUGF(3,
" cell_size[%d] : %.9g", d, cell_size[d]);
2014 at[d] = nd_ibox.
min[d];
2020 float cell_count, ratio;
2021 ND_BOX nd_cell = { {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0} };
2024 for ( d = 0; d < nd_stats->
ndims; d++ )
2026 nd_cell.
min[d] = min[d] + (at[d]+0) * cell_size[d];
2027 nd_cell.
max[d] = min[d] + (at[d]+1) * cell_size[d];
2034 total_count += cell_count * ratio;
2035 POSTGIS_DEBUGF(4,
" cell (%d,%d), cell value %.6f, ratio %.6f", at[0], at[1], cell_count, ratio);
2042 POSTGIS_DEBUGF(3,
" nd_stats->histogram_features = %f", nd_stats->
histogram_features);
2043 POSTGIS_DEBUGF(3,
" nd_stats->histogram_cells = %f", nd_stats->
histogram_cells);
2044 POSTGIS_DEBUGF(3,
" sum(overlapped histogram cells) = %f", total_count);
2045 POSTGIS_DEBUGF(3,
" selectivity = %f", selectivity);
2048 if (selectivity > 1.0) selectivity = 1.0;
2049 else if (selectivity < 0.0) selectivity = 0.0;
2063 Oid table_oid = PG_GETARG_OID(0);
2064 text *att_text = PG_GETARG_TEXT_P(1);
2069 bool only_parent =
false;
2072 if ( ! PG_ARGISNULL(2) )
2078 elog(ERROR,
"stats for \"%s.%s\" do not exist", get_rel_name(table_oid),
text_to_cstring(att_text));
2082 json = cstring_to_text(str);
2085 PG_RETURN_TEXT_P(json);
2096 Oid table_oid = PG_GETARG_OID(0);
2097 text *att_text = PG_GETARG_TEXT_P(1);
2098 Datum geom_datum = PG_GETARG_DATUM(2);
2100 float8 selectivity = 0;
2105 if ( ! PG_ARGISNULL(3) )
2112 elog(ERROR,
"stats for \"%s.%s\" do not exist", get_rel_name(table_oid),
text_to_cstring(att_text));
2115 if ( ! gserialized_datum_get_gbox_p(geom_datum, &gbox) )
2116 elog(ERROR,
"unable to calculate bounding box from geometry");
2124 PG_RETURN_FLOAT8(selectivity);
2135 Oid table_oid1 = PG_GETARG_OID(0);
2136 text *att_text1 = PG_GETARG_TEXT_P(1);
2137 Oid table_oid2 = PG_GETARG_OID(2);
2138 text *att_text2 = PG_GETARG_TEXT_P(3);
2140 float8 selectivity = 0;
2149 elog(ERROR,
"stats for \"%s.%s\" do not exist", get_rel_name(table_oid1),
text_to_cstring(att_text1));
2152 elog(ERROR,
"stats for \"%s.%s\" do not exist", get_rel_name(table_oid2),
text_to_cstring(att_text2));
2155 if ( ! PG_ARGISNULL(4) )
2157 text *modetxt = PG_GETARG_TEXT_P(4);
2159 if ( modestr[0] ==
'N' )
2168 PG_RETURN_FLOAT8(selectivity);
2178 PG_RETURN_DATUM(DirectFunctionCall5(
2180 PG_GETARG_DATUM(0), PG_GETARG_DATUM(1),
2181 PG_GETARG_DATUM(2), PG_GETARG_DATUM(3),
2193 PG_RETURN_DATUM(DirectFunctionCall5(
2195 PG_GETARG_DATUM(0), PG_GETARG_DATUM(1),
2196 PG_GETARG_DATUM(2), PG_GETARG_DATUM(3),
2217 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2219 List *
args = (List *) PG_GETARG_POINTER(2);
2221 int mode = PG_GETARG_INT32(4);
2223 VariableStatData vardata;
2229 float8 selectivity = 0;
2231 POSTGIS_DEBUG(2,
"gserialized_gist_sel called");
2243 if (list_length(
args) != 2)
2245 POSTGIS_DEBUG(3,
"gserialized_gist_sel: not a binary opclause");
2250 other = (Node *) linitial(
args);
2251 if ( ! IsA(other, Const) )
2253 self = (Var *)other;
2254 other = (Node *) lsecond(
args);
2258 self = (Var *) lsecond(
args);
2261 if ( ! IsA(other, Const) )
2263 POSTGIS_DEBUG(3,
" no constant arguments - returning a default selectivity");
2268 if( ! gserialized_datum_get_gbox_p(((Const*)other)->constvalue, &search_box) )
2270 POSTGIS_DEBUG(3,
"search box is EMPTY");
2271 PG_RETURN_FLOAT8(0.0);
2273 POSTGIS_DEBUGF(4,
" requested search box is: %s",
gbox_to_string(&search_box));
2276 examine_variable(root, (Node*)
self, 0, &vardata);
2277 if ( vardata.statsTuple ) {
2280 ReleaseVariableStats(vardata);
2284 POSTGIS_DEBUG(3,
" unable to load stats from syscache, not analyzed yet?");
2292 POSTGIS_DEBUGF(3,
" returning computed value: %f", selectivity);
2295 PG_RETURN_FLOAT8(selectivity);
2311 char *nsp_tbl = NULL;
2312 Oid tbl_oid, idx_oid;
2315 bool only_parent =
false;
2318 if ( PG_NARGS() == 4 )
2322 col = PG_GETARG_TEXT_P(2);
2323 only_parent = PG_GETARG_BOOL(3);
2324 nsp_tbl = palloc(strlen(nsp) + strlen(tbl) + 6);
2325 sprintf(nsp_tbl,
"\"%s\".\"%s\"", nsp, tbl);
2326 tbl_oid = DatumGetObjectId(DirectFunctionCall1(regclassin, CStringGetDatum(nsp_tbl)));
2329 else if ( PG_NARGS() == 3 )
2333 col = PG_GETARG_TEXT_P(2);
2334 nsp_tbl = palloc(strlen(nsp) + strlen(tbl) + 6);
2335 sprintf(nsp_tbl,
"\"%s\".\"%s\"", nsp, tbl);
2336 tbl_oid = DatumGetObjectId(DirectFunctionCall1(regclassin, CStringGetDatum(nsp_tbl)));
2339 else if ( PG_NARGS() == 2 )
2342 col = PG_GETARG_TEXT_P(1);
2343 nsp_tbl = palloc(strlen(tbl) + 3);
2344 sprintf(nsp_tbl,
"\"%s\"", tbl);
2345 tbl_oid = DatumGetObjectId(DirectFunctionCall1(regclassin, CStringGetDatum(nsp_tbl)));
2350 elog(ERROR,
"estimated_extent() called with wrong number of arguments");
2358 elog(DEBUG2,
"index for \"%s.%s\" does not exist", tbl,
text_to_cstring(col));
2370 elog(WARNING,
"stats for \"%s.%s\" do not exist", tbl,
text_to_cstring(col));
2375 gbox = palloc(
sizeof(
GBOX));
2386 PG_RETURN_POINTER(gbox);
2398 if ( PG_NARGS() == 3 )
2404 PG_GETARG_DATUM(2)));
2406 else if ( PG_NARGS() == 2 )
2411 PG_GETARG_DATUM(1)));
2414 elog(ERROR,
"geometry_estimated_extent() called with wrong number of arguments");
2426 Oid result = InvalidOid;
2430 Oid b2d_oid = postgis_oid(BOX2DFOID);
2431 Oid gdx_oid = postgis_oid(BOX3DOID);
2433 if (!(b2d_oid && gdx_oid))
2436 tbl_rel = RelationIdGetRelation(tbl_oid);
2437 idx_list = RelationGetIndexList(tbl_rel);
2438 RelationClose(tbl_rel);
2441 foreach(lc, idx_list)
2443 Form_pg_class idx_form;
2446 Oid idx_oid = lfirst_oid(lc);
2448 idx_tup = SearchSysCache1(RELOID, ObjectIdGetDatum(idx_oid));
2449 if (!HeapTupleIsValid(idx_tup))
2450 elog(ERROR,
"%s: unable to lookup index %u in syscache", __func__, idx_oid);
2451 idx_form = (Form_pg_class) GETSTRUCT(idx_tup);
2452 idx_relam = idx_form->relam;
2453 ReleaseSysCache(idx_tup);
2456 if (idx_relam == GIST_AM_OID)
2458 Form_pg_attribute att;
2461 HeapTuple att_tup = SearchSysCache2(ATTNAME,
2462 ObjectIdGetDatum(idx_oid),
2463 PointerGetDatum(colname));
2464 if (!HeapTupleIsValid(att_tup))
2467 att = (Form_pg_attribute) GETSTRUCT(att_tup);
2468 atttypid = att->atttypid;
2469 ReleaseSysCache(att_tup);
2472 if (b2d_oid == atttypid || gdx_oid == atttypid)
2488 BOX2DF *bounds_2df = NULL;
2489 GIDX *bounds_gidx = NULL;
2494 OffsetNumber offset;
2495 unsigned long offset_max;
2500 idx_rel = index_open(idx_oid, AccessShareLock);
2501 buffer = ReadBuffer(idx_rel, GIST_ROOT_BLKNO);
2502 page = (Page) BufferGetPage(
buffer);
2503 offset = FirstOffsetNumber;
2504 offset_max = PageGetMaxOffsetNumber(page);
2505 while (offset <= offset_max)
2507 ItemId iid = PageGetItemId(page, offset);
2512 index_close(idx_rel, AccessShareLock);
2515 ituple = (IndexTuple) PageGetItem(page, iid);
2516 if (!GistTupleIsInvalid(ituple))
2519 Datum idx_attr = index_getattr(ituple, 1, idx_rel->rd_att, &isnull);
2524 BOX2DF *b = (BOX2DF*)DatumGetPointer(idx_attr);
2532 GIDX *b = (GIDX*)DatumGetPointer(idx_attr);
2544 index_close(idx_rel, AccessShareLock);
2558 gbox_from_gidx(bounds_gidx, gbox, 0);
2578 Oid tbl_oid = PG_GETARG_DATUM(0);
2579 text *col = PG_GETARG_TEXT_P(1);
2589 PG_RETURN_POINTER(gbox);
GBOX * gbox_new(uint8_t flags)
Create a new gbox with the dimensionality indicated by the flags.
int gbox_is_valid(const GBOX *gbox)
Return false if any of the dimensions is NaN or infinite.
char * gbox_to_string(const GBOX *gbox)
Allocate a string representation of the GBOX, based on dimensionality of flags.
int gserialized_get_gbox_p(const GSERIALIZED *g, GBOX *box)
Read the bounding box off a serialization and calculate one if it is not already there.
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.
struct ND_STATS_T ND_STATS
N-dimensional statistics structure.
static char * nd_stats_to_json(const ND_STATS *nd_stats)
Convert an ND_STATS to a JSON representation for external use.
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 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 int range_quintile(int *vals, int nvals)
The difference between the fourth and first quintile values, the "inter-quintile range".
#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...
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 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.
static GBOX * spatial_index_read_extent(Oid idx_oid, int key_type)
#define ND_DIMS
The maximum number of dimensions our code can handle.
#define STATISTIC_KIND_2D
static int nd_box_merge(const ND_BOX *source, ND_BOX *target)
Create a printable view of the ND_STATS histogram.
#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.
#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'.
Datum gserialized_gist_sel(PG_FUNCTION_ARGS)
static ND_STATS * pg_nd_stats_from_tuple(HeapTuple stats_tuple, 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.
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)
struct ND_IBOX_T ND_IBOX
N-dimensional box index type.
#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)
Datum _postgis_gserialized_sel(PG_FUNCTION_ARGS)
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 double nd_box_ratio(const ND_BOX *b1, const ND_BOX *b2, int ndims)
Returns the proportion of b2 that is covered by b1.
static int nd_stats_value_index(const ND_STATS *stats, int *indexes)
Given a position in the n-d histogram (i,j,k) return the position in the 1-d values array.
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)
static char * nd_box_to_json(const ND_BOX *nd_box, int ndims)
Convert an ND_BOX to a JSON string for printing.
#define MIN_DIMENSION_WIDTH
Minimum width of a dimension that we'll bother trying to compute statistics on.
Datum geometry_estimated_extent(PG_FUNCTION_ARGS)
#define STATISTIC_SLOT_2D
struct ND_BOX_T ND_BOX
N-dimensional box type for calculations, to avoid doing explicit axis conversions from GBOX in all ca...
static Oid table_get_spatial_index(Oid tbl_oid, text *col, int *key_type)
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 homogenously distributed or contentrated within one dimension,...
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)
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)
Macros for manipulating the 'flags' byte.
#define FLAGS_GET_M(flags)
#define FLAGS_SET_GEODETIC(flags, value)
#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.
Datum buffer(PG_FUNCTION_ARGS)
char * text_to_cstring(const text *textptr)
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.
stringbuffer_t * stringbuffer_create(void)
Allocate a new stringbuffer_t.
void stringbuffer_append(stringbuffer_t *s, const char *a)
Append the specified string to the stringbuffer_t.
void stringbuffer_destroy(stringbuffer_t *s)
Free the stringbuffer_t and all memory managed within it.
char * stringbuffer_getstringcopy(stringbuffer_t *s)
Returns a newly allocated string large enough to contain the current state of the string.
N-dimensional box type for calculations, to avoid doing explicit axis conversions from GBOX in all ca...
N-dimensional box index type.
float4 histogram_features
N-dimensional statistics structure.