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 #if PG_VERSION_NUM < 130000
70 #include "access/tuptoaster.h"
72 #include "access/detoast.h"
74 #include "utils/datum.h"
75 #include "access/heapam.h"
76 #include "catalog/index.h"
77 #include "catalog/pg_am.h"
78 #include "miscadmin.h"
79 #include "storage/lmgr.h"
80 #include "catalog/namespace.h"
81 #include "catalog/indexing.h"
83 #include "utils/regproc.h"
84 #include "utils/varlena.h"
86 #include "utils/builtins.h"
87 #include "utils/datum.h"
88 #include "utils/snapmgr.h"
89 #include "utils/fmgroids.h"
91 #include "access/heapam.h"
92 #include "catalog/pg_type.h"
93 #include "access/relscan.h"
95 #include "executor/spi.h"
97 #include "commands/vacuum.h"
98 #include "nodes/pathnodes.h"
100 #include "parser/parsetree.h"
101 #include "utils/array.h"
102 #include "utils/lsyscache.h"
103 #include "utils/builtins.h"
104 #include "utils/syscache.h"
105 #include "utils/rel.h"
106 #include "utils/selfuncs.h"
108 #include "../postgis_config.h"
110 #include "access/htup_details.h"
115 #include "lwgeom_pg.h"
116 #include "gserialized_gist.h"
167 #define STATISTIC_KIND_ND 102
168 #define STATISTIC_KIND_2D 103
178 #define STATISTIC_SLOT_ND 3
179 #define STATISTIC_SLOT_2D 4
187 #define SDFACTOR 3.25
202 #define MIN_DIMENSION_WIDTH 0.000000001
208 #define MAX_DIMENSION_WIDTH 1.0E+20
213 #define DEFAULT_ND_SEL 0.0001
214 #define DEFAULT_ND_JOINSEL 0.001
219 #define FALLBACK_ND_SEL 0.2
220 #define FALLBACK_ND_JOINSEL 0.3
319 if (VARSIZE_ANY_EXHDR(txt) <= 0)
321 modestr = (
char*)VARDATA(txt);
322 if ( modestr[0] ==
'N' )
334 int ia = *((
const int*)a);
335 int ib = *((
const int*)b);
362 qsort(vals, nvals,
sizeof(
int),
cmp_int);
363 return vals[nvals-1] - vals[0];
375 for ( i = 0; i < nvals; i++ )
381 #if POSTGIS_DEBUG_LEVEL >= 3
387 total_int(
const int *vals,
int nvals)
392 for ( i = 0; i < nvals; i++ )
402 avg(
const int *vals,
int nvals)
404 int t = total_int(vals, nvals);
405 return (
double)t / (double)nvals;
412 stddev(
const int *vals,
int nvals)
416 double mean = avg(vals, nvals);
419 for ( i = 0; i < nvals; i++ )
421 double v = (double)(vals[i]);
422 sigma2 += (mean - v) * (mean - v);
424 return sqrt(sigma2 / nvals);
436 int accum = 1, vdx = 0;
441 for ( d = 0; d < (int)(stats->
ndims); d++ )
443 int size = (int)(stats->
size[d]);
444 if ( indexes[d] < 0 || indexes[d] >= size )
446 POSTGIS_DEBUGF(3,
" bad index at (%d, %d)", indexes[0], indexes[1]);
449 vdx += indexes[d] * accum;
466 for ( i = 0; i < ndims; i++ )
472 for ( i = 0; i < ndims; i++ )
492 char *json_extent, *
str;
495 int ndims = (int)roundf(nd_stats->
ndims);
502 for ( d = 0; d < ndims; d++ )
538 int sizex = (int)roundf(stats->
size[0]);
539 int sizey = (int)roundf(stats->
size[1]);
542 for ( k = 0; k < sizey; k++ )
544 for ( j = 0; j < sizex; j++ )
562 for ( d = 0; d <
ND_DIMS; d++ )
564 target->
min[d] = Min(target->
min[d], source->
min[d]);
565 target->
max[d] = Max(target->
max[d], source->
max[d]);
574 memset(a, 0,
sizeof(
ND_BOX));
587 for ( d = 0; d <
ND_DIMS; d++ )
590 a->
max[d] = -1 * FLT_MAX;
637 for ( d = 0; d < ndims; d++ )
639 if ( (a->
min[d] > b->
max[d]) || (a->
max[d] < b->
min[d]) )
652 for ( d = 0; d < ndims; d++ )
654 if ( ! ((a->
min[d] < b->
min[d]) && (a->
max[d] > b->
max[d])) )
669 for ( d = 0; d <
ND_DIMS; d++ )
671 size = nd_box->
max[d] - nd_box->
min[d];
675 nd_box->
min[d] -= size * expansion_factor / 2;
676 nd_box->
max[d] += size * expansion_factor / 2;
693 memset(nd_ibox, 0,
sizeof(
ND_IBOX));
696 for ( d = 0; d < nd_stats->
ndims; d++ )
700 double width = smax - smin;
708 int size = (int)roundf(nd_stats->
size[d]);
711 nd_ibox->
min[d] = floor(size * (nd_box->
min[d] - smin) / width);
712 nd_ibox->
max[d] = floor(size * (nd_box->
max[d] - smin) / width);
714 POSTGIS_DEBUGF(5,
" stats: dim %d: min %g: max %g: width %g", d, smin, smax, width);
715 POSTGIS_DEBUGF(5,
" overlap: dim %d: (%d, %d)", d, nd_ibox->
min[d], nd_ibox->
max[d]);
718 nd_ibox->
min[d] = Max(nd_ibox->
min[d], 0);
719 nd_ibox->
max[d] = Min(nd_ibox->
max[d], size - 1);
736 for ( d = 0 ; d < ndims; d++ )
738 if ( b1->
max[d] <= b2->
min[d] || b1->
min[d] >= b2->
max[d] )
741 if ( b1->
min[d] > b2->
min[d] || b1->
max[d] < b2->
max[d] )
748 for ( d = 0; d < ndims; d++ )
750 double width2 = b2->
max[d] - b2->
min[d];
751 double imin, imax, iwidth;
755 imin = Max(b1->
min[d], b2->
min[d]);
756 imax = Min(b1->
max[d], b2->
max[d]);
757 iwidth = imax - imin;
758 iwidth = Max(0.0, iwidth);
770 #define MAX_NUM_BINS 50
771 #define BIN_MIN_SIZE 10
795 #if POSTGIS_DEBUG_LEVEL >= 3
796 double average, sdev, sdev_ratio;
802 counts = palloc0(num_bins *
sizeof(
int));
805 for ( d = 0; d < ndims; d++ )
808 memset(counts, 0, num_bins *
sizeof(
int));
811 smin = extent->
min[d];
812 smax = extent->
max[d];
813 swidth = smax - smin;
827 for ( i = 0; i < num_boxes; i++ )
829 double minoffset, maxoffset;
833 if ( ! ndb )
continue;
836 minoffset = ndb->
min[d] - smin;
837 maxoffset = ndb->
max[d] - smin;
840 if ( minoffset < 0 || minoffset > swidth ||
841 maxoffset < 0 || maxoffset > swidth )
847 bmin = floor(num_bins * minoffset / swidth);
848 bmax = floor(num_bins * maxoffset / swidth);
851 if (bmax >= num_bins)
854 POSTGIS_DEBUGF(4,
" dimension %d, feature %d: bin %d to bin %d", d, i, bmin, bmax);
857 for ( k = bmin; k <= bmax; k++ )
868 #if POSTGIS_DEBUG_LEVEL >= 3
869 average = avg(counts, num_bins);
870 sdev = stddev(counts, num_bins);
871 sdev_ratio = sdev/average;
873 POSTGIS_DEBUGF(3,
" dimension %d: range = %d", d, range);
874 POSTGIS_DEBUGF(3,
" dimension %d: average = %.6g", d, average);
875 POSTGIS_DEBUGF(3,
" dimension %d: stddev = %.6g", d, sdev);
876 POSTGIS_DEBUGF(3,
" dimension %d: stddev_ratio = %.6g", d, sdev_ratio);
879 distribution[d] = range;
899 if ( counter[d] < ibox->
max[d] )
904 counter[d] = ibox->
min[d];
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);
951 HeapTuple stats_tuple = NULL;
957 POSTGIS_DEBUGF(2,
"searching whole tree stats for \"%s\"", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
958 stats_tuple = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(table_oid), Int16GetDatum(att_num), BoolGetDatum(
true));
960 POSTGIS_DEBUGF(2,
"found whole tree stats for \"%s\"", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
963 if ( only_parent || ! stats_tuple )
965 POSTGIS_DEBUGF(2,
"searching parent table stats for \"%s\"", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
966 stats_tuple = SearchSysCache3(STATRELATTINH, ObjectIdGetDatum(table_oid), Int16GetDatum(att_num), BoolGetDatum(
false));
968 POSTGIS_DEBUGF(2,
"found parent table stats for \"%s\"", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
972 POSTGIS_DEBUGF(2,
"stats for \"%s\" do not exist", get_rel_name(table_oid)? get_rel_name(table_oid) :
"NULL");
977 ReleaseSysCache(stats_tuple);
981 "histogram for attribute %d of table \"%s\" does not exist?",
982 att_num, get_rel_name(table_oid));
999 const char *att_name = text_to_cstring(att_text);
1006 att_num = get_attnum(table_oid, att_name);
1008 elog(ERROR,
"attribute \"%s\" does not exist", att_name);
1014 elog(ERROR,
"attribute name is null");
1037 int ncells1, ncells2;
1038 int ndims1, ndims2, ndims;
1040 double ntuples_not_null1, ntuples_not_null2;
1059 if ( ! ( s1 && s2 ) )
1061 elog(NOTICE,
" estimate_join_selectivity called with null inputs");
1070 if ( ncells1 > ncells2 )
1088 ntuples_max = ntuples_not_null1 * ntuples_not_null2;
1091 ndims1 = (int)roundf(s1->
ndims);
1092 ndims2 = (int)roundf(s2->
ndims);
1093 ndims = Max(ndims1, ndims2);
1102 POSTGIS_DEBUG(3,
"relation stats do not intersect, returning 0");
1103 PG_RETURN_FLOAT8(0.0);
1112 POSTGIS_DEBUG(3,
"could not calculate overlap of relations");
1117 for ( d = 0; d < ndims1; d++ )
1119 at1[d] = ibox1.
min[d];
1122 size1[d] = (int)roundf(s1->
size[d]);
1123 cellsize1[d] = width1[d] / size1[d];
1127 for ( d = 0; d < ndims2; d++ )
1131 size2[d] = (int)roundf(s2->
size[d]);
1132 cellsize2[d] = width2[d] / size2[d];
1142 for ( d = 0; d < ndims1; d++ )
1144 nd_cell1.
min[d] = min1[d] + (at1[d]+0) * cellsize1[d];
1145 nd_cell1.
max[d] = min1[d] + (at1[d]+1) * cellsize1[d];
1152 for ( d = 0; d < ndims2; d++ )
1154 at2[d] = ibox2.
min[d];
1157 POSTGIS_DEBUGF(3,
"at1 %d,%d %s", at1[0], at1[1],
nd_box_to_json(&nd_cell1, ndims1));
1171 for ( d = 0; d < ndims2; d++ )
1173 nd_cell2.
min[d] = min2[d] + (at2[d]+0) * cellsize2[d];
1174 nd_cell2.
max[d] = min2[d] + (at2[d]+1) * cellsize2[d];
1177 POSTGIS_DEBUGF(3,
" at2 %d,%d %s", at2[0], at2[1],
nd_box_to_json(&nd_cell2, ndims2));
1180 ratio2 =
nd_box_ratio(&nd_cell1, &nd_cell2, Max(ndims1, ndims2));
1184 POSTGIS_DEBUGF(3,
" val1 %.6g val2 %.6g ratio %.6g", val1, val2, ratio2);
1185 val += val1 * (val2 * ratio2);
1192 POSTGIS_DEBUGF(3,
"val of histogram = %g", val);
1203 POSTGIS_DEBUGF(3,
"val scaled to full table size = %g", val);
1220 selectivity = val / ntuples_max;
1223 if ( isnan(selectivity) || ! isfinite(selectivity) || selectivity < 0.0 )
1227 else if ( selectivity > 1.0 )
1242 PG_RETURN_DATUM(DirectFunctionCall5(
1244 PG_GETARG_DATUM(0), PG_GETARG_DATUM(1),
1245 PG_GETARG_DATUM(2), PG_GETARG_DATUM(3),
1257 PG_RETURN_DATUM(DirectFunctionCall5(
1259 PG_GETARG_DATUM(0), PG_GETARG_DATUM(1),
1260 PG_GETARG_DATUM(2), PG_GETARG_DATUM(3),
1271 Node *arg1 = (Node*) linitial(
args);
1272 Node *arg2 = (Node*) lsecond(
args);
1273 Var *var1 = (Var*) arg1;
1274 Var *var2 = (Var*) arg2;
1276 POSTGIS_DEBUGF(2,
"%s: entered function", __func__);
1280 if (!IsA(arg1, Var) || !IsA(arg2, Var))
1282 POSTGIS_DEBUGF(1,
"%s called with arguments that are not column references", __func__);
1287 relid1 = rt_fetch(var1->varno, root->parse->rtable)->relid;
1288 relid2 = rt_fetch(var2->varno, root->parse->rtable)->relid;
1297 POSTGIS_DEBUGF(2,
"%s: cannot find stats for \"%s\"", __func__, get_rel_name(relid2) ? get_rel_name(relid2) :
"NULL");
1302 POSTGIS_DEBUGF(2,
"%s: cannot find stats for \"%s\"", __func__, get_rel_name(relid2) ? get_rel_name(relid2) :
"NULL");
1307 POSTGIS_DEBUGF(2,
"got selectivity %g", selectivity);
1324 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
1326 List *
args = (List *) PG_GETARG_POINTER(2);
1327 JoinType jointype = (JoinType) PG_GETARG_INT16(3);
1328 int mode = PG_GETARG_INT32(4);
1330 POSTGIS_DEBUGF(2,
"%s: entered function", __func__);
1333 if (list_length(
args) != 2)
1335 POSTGIS_DEBUGF(2,
"%s: got nargs == %d", __func__, list_length(
args));
1340 if (jointype != JOIN_INNER)
1342 POSTGIS_DEBUGF(1,
"%s: jointype %d not supported", __func__, jointype);
1369 int sample_rows,
double total_rows,
int mode)
1371 MemoryContext old_context;
1373 int notnull_cnt = 0;
1375 int histogram_features = 0;
1378 size_t nd_stats_size;
1380 double total_width = 0;
1381 double total_cell_count = 0;
1387 const ND_BOX **sample_boxes;
1392 int histo_cells_target;
1394 int histo_cells_new = 1;
1397 int histo_ndims = 0;
1398 double sample_distribution[
ND_DIMS];
1399 double total_distribution;
1417 POSTGIS_DEBUG(2,
"compute_gserialized_stats called");
1418 POSTGIS_DEBUGF(3,
" # sample_rows: %d", sample_rows);
1419 POSTGIS_DEBUGF(3,
" estimate of total_rows: %.6g", total_rows);
1425 sample_boxes = palloc(
sizeof(
ND_BOX*) * sample_rows);
1437 for ( i = 0; i < sample_rows; i++ )
1444 datum = fetchfunc(stats, i, &is_null);
1449 POSTGIS_DEBUGF(4,
" skipped null geometry %d", i);
1458 POSTGIS_DEBUGF(3,
" skipped empty geometry %d", i);
1469 POSTGIS_DEBUGF(3,
" skipped infinite/nan geometry %d", i);
1481 nd_box = palloc(
sizeof(
ND_BOX));
1485 sample_boxes[notnull_cnt] = nd_box;
1488 if ( ! notnull_cnt )
1495 total_width += toast_raw_datum_size(datum);
1498 for ( d = 0; d < ndims; d++ )
1500 sum.
min[d] += nd_box->
min[d];
1501 sum.
max[d] += nd_box->
max[d];
1508 #if POSTGIS_PGSQL_VERSION >= 180
1509 vacuum_delay_point(
true);
1511 vacuum_delay_point();
1522 #if POSTGIS_PGSQL_VERSION >= 170
1523 histo_cells_target = (int)pow((
double)(stats->attstattarget), (
double)ndims);
1524 POSTGIS_DEBUGF(3,
" stats->attstattarget: %d", stats->attstattarget);
1526 histo_cells_target = (int)pow((
double)(stats->attr->attstattarget), (
double)ndims);
1527 POSTGIS_DEBUGF(3,
" stats->attr->attstattarget: %d", stats->attr->attstattarget);
1529 histo_cells_target = Min(histo_cells_target, ndims * 100000);
1530 histo_cells_target = Min(histo_cells_target, (
int)(10 * ndims * total_rows));
1531 POSTGIS_DEBUGF(3,
" target # of histogram cells: %d", histo_cells_target);
1534 if ( ! notnull_cnt )
1536 stats->stats_valid =
false;
1540 POSTGIS_DEBUGF(3,
" sample_extent: %s",
nd_box_to_json(&sample_extent, ndims));
1546 for ( d = 0; d < ndims; d++ )
1549 avg.
min[d] = sum.
min[d] / notnull_cnt;
1550 avg.
max[d] = sum.
max[d] / notnull_cnt;
1553 for ( i = 0; i < notnull_cnt; i++ )
1555 const ND_BOX *ndb = sample_boxes[i];
1556 stddev.
min[d] += (ndb->
min[d] - avg.
min[d]) * (ndb->
min[d] - avg.
min[d]);
1557 stddev.
max[d] += (ndb->
max[d] - avg.
max[d]) * (ndb->
max[d] - avg.
max[d]);
1559 stddev.
min[d] = sqrt(stddev.
min[d] / notnull_cnt);
1560 stddev.
max[d] = sqrt(stddev.
max[d] / notnull_cnt);
1573 for ( i = 0; i < notnull_cnt; i++ )
1575 const ND_BOX *ndb = sample_boxes[i];
1579 POSTGIS_DEBUGF(4,
" feature %d is a hard deviant, skipped", i);
1580 sample_boxes[i] = NULL;
1591 histo_extent = histo_extent_new;
1606 sample_distribution);
1622 for ( d = 0; d < ndims; d++ )
1624 if ( sample_distribution[d] > 0 )
1628 if ( histo_ndims == 0 )
1632 POSTGIS_DEBUG(3,
" special case: no axes have variability");
1633 histo_cells_new = 1;
1634 for ( d = 0; d < ndims; d++ )
1636 histo_size[d] = (int)pow((
double)histo_cells_target, 1/(double)ndims);
1637 if ( ! histo_size[d] )
1639 POSTGIS_DEBUGF(3,
" histo_size[d]: %d", histo_size[d]);
1640 histo_cells_new *= histo_size[d];
1642 POSTGIS_DEBUGF(3,
" histo_cells_new: %d", histo_cells_new);
1651 POSTGIS_DEBUG(3,
" allocating histogram axes based on axis variability");
1652 total_distribution =
total_double(sample_distribution, ndims);
1653 POSTGIS_DEBUGF(3,
" total_distribution: %.8g", total_distribution);
1654 histo_cells_new = 1;
1655 for ( d = 0; d < ndims; d++ )
1657 if ( sample_distribution[d] == 0 )
1664 float edge_ratio = (float)sample_distribution[d] / (
float)total_distribution;
1670 histo_size[d] = (int)pow((
double)histo_cells_target * histo_ndims * edge_ratio, 1/(double)histo_ndims);
1672 if ( ! histo_size[d] )
1675 histo_cells_new *= histo_size[d];
1677 POSTGIS_DEBUGF(3,
" histo_cells_new: %d", histo_cells_new);
1681 histo_cells = histo_cells_new;
1682 POSTGIS_DEBUGF(3,
" histo_cells: %d", histo_cells);
1687 old_context = MemoryContextSwitchTo(stats->anl_context);
1688 nd_stats_size =
sizeof(
ND_STATS) + ((histo_cells - 1) *
sizeof(float4));
1689 nd_stats = palloc(nd_stats_size);
1690 memset(nd_stats, 0, nd_stats_size);
1691 MemoryContextSwitchTo(old_context);
1694 nd_stats->
ndims = ndims;
1695 nd_stats->
extent = histo_extent;
1700 for ( d = 0; d < ndims; d++ )
1701 nd_stats->
size[d] = histo_size[d];
1716 for ( i = 0; i < notnull_cnt; i++ )
1721 double num_cells = 0;
1722 double min[
ND_DIMS] = {0.0, 0.0, 0.0, 0.0};
1723 double max[
ND_DIMS] = {0.0, 0.0, 0.0, 0.0};
1724 double cellsize[
ND_DIMS] = {0.0, 0.0, 0.0, 0.0};
1726 nd_box = sample_boxes[i];
1727 if ( ! nd_box )
continue;
1730 #if POSTGIS_PGSQL_VERSION >= 180
1731 vacuum_delay_point(
true);
1733 vacuum_delay_point();
1738 memset(at, 0,
sizeof(
int)*
ND_DIMS);
1740 POSTGIS_DEBUGF(3,
" feature %d: ibox (%d, %d, %d, %d) (%d, %d, %d, %d)", i,
1741 nd_ibox.
min[0], nd_ibox.
min[1], nd_ibox.
min[2], nd_ibox.
min[3],
1742 nd_ibox.
max[0], nd_ibox.
max[1], nd_ibox.
max[2], nd_ibox.
max[3]);
1744 for ( d = 0; d < nd_stats->
ndims; d++ )
1747 at[d] = nd_ibox.
min[d];
1750 cellsize[d] = (max[d] - min[d])/(nd_stats->
size[d]);
1759 ND_BOX nd_cell = { {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0} };
1762 for ( d = 0; d < nd_stats->
ndims; d++ )
1764 nd_cell.
min[d] = min[d] + (at[d]+0) * cellsize[d];
1765 nd_cell.
max[d] = min[d] + (at[d]+1) * cellsize[d];
1776 POSTGIS_DEBUGF(3,
" ratio (%.8g) num_cells (%.8g)", ratio, num_cells);
1777 POSTGIS_DEBUGF(3,
" at (%d, %d, %d, %d)", at[0], at[1], at[2], at[3]);
1782 total_cell_count += num_cells;
1784 histogram_features++;
1787 POSTGIS_DEBUGF(3,
" histogram_features: %d", histogram_features);
1788 POSTGIS_DEBUGF(3,
" sample_rows: %d", sample_rows);
1789 POSTGIS_DEBUGF(3,
" table_rows: %.6g", total_rows);
1792 if ( ! histogram_features )
1794 POSTGIS_DEBUG(3,
" no stats have been gathered");
1795 elog(NOTICE,
" no features lie in the stats histogram, invalid stats");
1796 stats->stats_valid =
false;
1817 stats->stakind[stats_slot] = stats_kind;
1818 stats->staop[stats_slot] = InvalidOid;
1819 stats->stanumbers[stats_slot] = (float4*)nd_stats;
1820 stats->numnumbers[stats_slot] = nd_stats_size/
sizeof(float4);
1821 stats->stanullfrac = (float4)null_cnt/sample_rows;
1822 stats->stawidth = total_width/notnull_cnt;
1823 stats->stadistinct = -1.0;
1824 stats->stats_valid =
true;
1826 POSTGIS_DEBUGF(3,
" out: slot 0: kind %d (STATISTIC_KIND_ND)", stats->stakind[0]);
1827 POSTGIS_DEBUGF(3,
" out: slot 0: op %d (InvalidOid)", stats->staop[0]);
1828 POSTGIS_DEBUGF(3,
" out: slot 0: numnumbers %d", stats->numnumbers[0]);
1829 POSTGIS_DEBUGF(3,
" out: null fraction: %f=%d/%d", stats->stanullfrac, null_cnt, sample_rows);
1830 POSTGIS_DEBUGF(3,
" out: average width: %d bytes", stats->stawidth);
1831 POSTGIS_DEBUG (3,
" out: distinct values: all (no check done)");
1860 int sample_rows,
double total_rows)
1866 stats->extra_data = extra_data;
1871 if (stats->stats_valid)
1908 VacAttrStats *stats = (VacAttrStats *)PG_GETARG_POINTER(0);
1913 if (!std_typanalyze(stats))
1914 PG_RETURN_BOOL(
false);
1921 stats->extra_data = extra_data;
1924 PG_RETURN_BOOL(
true);
1950 double total_count = 0.0;
1956 elog(NOTICE,
" estimate_selectivity called with null input");
1970 POSTGIS_DEBUGF(3,
" mode: %d", mode);
1973 POSTGIS_DEBUG(3,
" in 2d mode, stripping the computation down to 2d");
1991 POSTGIS_DEBUG(3,
" search box does not overlap histogram, returning 0");
1998 POSTGIS_DEBUG(3,
" search box contains histogram, returning 1");
2005 POSTGIS_DEBUG(3,
" search box overlap with stats histogram failed");
2010 for ( d = 0; d < nd_stats->
ndims; d++ )
2015 cell_size[d] = (max[d] - min[d]) / nd_stats->
size[d];
2016 POSTGIS_DEBUGF(3,
" cell_size[%d] : %.9g", d, cell_size[d]);
2019 at[d] = nd_ibox.
min[d];
2025 float cell_count, ratio;
2026 ND_BOX nd_cell = { {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0} };
2029 for ( d = 0; d < nd_stats->
ndims; d++ )
2031 nd_cell.
min[d] = min[d] + (at[d]+0) * cell_size[d];
2032 nd_cell.
max[d] = min[d] + (at[d]+1) * cell_size[d];
2039 total_count += (double)cell_count * ratio;
2040 POSTGIS_DEBUGF(4,
" cell (%d,%d), cell value %.6f, ratio %.6f", at[0], at[1], cell_count, ratio);
2047 POSTGIS_DEBUGF(3,
" nd_stats->histogram_features = %f", nd_stats->
histogram_features);
2048 POSTGIS_DEBUGF(3,
" nd_stats->histogram_cells = %f", nd_stats->
histogram_cells);
2049 POSTGIS_DEBUGF(3,
" sum(overlapped histogram cells) = %f", total_count);
2050 POSTGIS_DEBUGF(3,
" selectivity = %f", selectivity);
2053 if (selectivity > 1.0) selectivity = 1.0;
2054 else if (selectivity < 0.0) selectivity = 0.0;
2068 Oid table_oid = PG_GETARG_OID(0);
2069 text *att_text = PG_GETARG_TEXT_P(1);
2074 bool only_parent =
false;
2077 if ( ! PG_ARGISNULL(2) )
2083 elog(ERROR,
"stats for \"%s.%s\" do not exist", get_rel_name(table_oid), text_to_cstring(att_text));
2088 json = cstring_to_text(
str);
2092 PG_RETURN_TEXT_P(json);
2103 Oid table_oid = PG_GETARG_OID(0);
2104 text *att_text = PG_GETARG_TEXT_P(1);
2105 Datum geom_datum = PG_GETARG_DATUM(2);
2107 float8 selectivity = 0;
2112 if ( ! PG_ARGISNULL(3) )
2119 elog(ERROR,
"stats for \"%s.%s\" do not exist", get_rel_name(table_oid), text_to_cstring(att_text));
2123 elog(ERROR,
"unable to calculate bounding box from geometry");
2131 PG_RETURN_FLOAT8(selectivity);
2142 Oid table_oid1 = PG_GETARG_OID(0);
2143 text *att_text1 = PG_GETARG_TEXT_P(1);
2144 Oid table_oid2 = PG_GETARG_OID(2);
2145 text *att_text2 = PG_GETARG_TEXT_P(3);
2147 float8 selectivity = 0;
2156 elog(ERROR,
"stats for \"%s.%s\" do not exist", get_rel_name(table_oid1), text_to_cstring(att_text1));
2159 elog(ERROR,
"stats for \"%s.%s\" do not exist", get_rel_name(table_oid2), text_to_cstring(att_text2));
2162 if ( ! PG_ARGISNULL(4) )
2164 text *modetxt = PG_GETARG_TEXT_P(4);
2165 char *modestr = text_to_cstring(modetxt);
2166 if ( modestr[0] ==
'N' )
2175 PG_RETURN_FLOAT8(selectivity);
2185 PG_RETURN_DATUM(DirectFunctionCall5(
2187 PG_GETARG_DATUM(0), PG_GETARG_DATUM(1),
2188 PG_GETARG_DATUM(2), PG_GETARG_DATUM(3),
2200 PG_RETURN_DATUM(DirectFunctionCall5(
2202 PG_GETARG_DATUM(0), PG_GETARG_DATUM(1),
2203 PG_GETARG_DATUM(2), PG_GETARG_DATUM(3),
2226 VariableStatData vardata;
2232 float8 selectivity = 0;
2235 POSTGIS_DEBUGF(2,
"%s: entered function", __func__);
2237 if (!get_restriction_variable(root,
args, varRelid, &vardata, &other, &varonleft))
2239 POSTGIS_DEBUGF(2,
"%s: could not find vardata", __func__);
2243 if (!IsA(other, Const))
2245 ReleaseVariableStats(vardata);
2246 POSTGIS_DEBUGF(2,
"%s: no constant argument, returning default selectivity %g", __func__,
DEFAULT_ND_SEL);
2250 otherConst = (Const*)other;
2251 if ((!otherConst) || otherConst->constisnull)
2253 ReleaseVariableStats(vardata);
2254 POSTGIS_DEBUGF(2,
"%s: constant argument is NULL", __func__);
2260 ReleaseVariableStats(vardata);
2261 POSTGIS_DEBUGF(2,
"%s: search box is EMPTY", __func__);
2265 if (!vardata.statsTuple)
2267 POSTGIS_DEBUGF(1,
"%s: no statistics available on table. Empty? Need to ANALYZE?", __func__);
2272 ReleaseVariableStats(vardata);
2283 PlannerInfo *root = (PlannerInfo *) PG_GETARG_POINTER(0);
2285 List *
args = (List *) PG_GETARG_POINTER(2);
2286 int varRelid = PG_GETARG_INT32(3);
2287 int mode = PG_GETARG_INT32(4);
2289 POSTGIS_DEBUGF(2,
"%s: selectivity is %g", __func__, selectivity);
2290 PG_RETURN_FLOAT8(selectivity);
2304 HeapTuple index_tuple;
2305 Form_pg_index index_form;
2306 int16 index_attnum = InvalidAttrNumber;
2309 index_tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(index_oid));
2310 if (!HeapTupleIsValid(index_tuple))
2311 elog(ERROR,
"cache lookup failed for index %u", index_oid);
2313 index_form = (Form_pg_index) GETSTRUCT(index_tuple);
2316 if (index_form->indrelid != table_oid)
2317 elog(ERROR,
"table=%u and index=%u are not related", table_oid, index_oid);
2320 for (int16 i = 0; i < (int16)(index_form->indkey.dim1); i++)
2322 if (index_form->indkey.values[i] == table_attnum)
2328 ReleaseSysCache(index_tuple);
2329 return index_attnum;
2341 Form_pg_class index_rel_form;
2342 HeapTuple index_rel_tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(index_oid));
2344 if (!HeapTupleIsValid(index_rel_tuple))
2345 elog(ERROR,
"cache lookup failed for index %u", index_oid);
2347 index_rel_form = (Form_pg_class) GETSTRUCT(index_rel_tuple);
2348 index_am = index_rel_form->relam;
2349 ReleaseSysCache(index_rel_tuple);
2361 Oid atttypid = InvalidOid;
2362 Form_pg_attribute att_form;
2365 HeapTuple att_tuple = SearchSysCache2(ATTNUM,
2366 ObjectIdGetDatum(index_oid),
2367 Int16GetDatum(index_attnum));
2369 if (!HeapTupleIsValid(att_tuple))
2370 elog(ERROR,
"cache lookup failed for index %u attribute %d", index_oid, index_attnum);
2372 att_form = (Form_pg_attribute) GETSTRUCT(att_tuple);
2373 atttypid = att_form->atttypid;
2374 ReleaseSysCache(att_tuple);
2394 Oid b2d_oid = postgis_oid(BOX2DFOID);
2395 Oid gdx_oid = postgis_oid(GIDXOID);
2397 if (!(b2d_oid && gdx_oid))
2401 table_rel = RelationIdGetRelation(table_oid);
2402 index_list = RelationGetIndexList(table_rel);
2403 RelationClose(table_rel);
2406 foreach(lc, index_list)
2408 Oid index_oid = lfirst_oid(lc);
2415 if (*idx_attnum == InvalidAttrNumber)
2425 if (atttypid == b2d_oid || atttypid == gdx_oid)
2444 BOX2DF *bounds_2df = NULL;
2445 GIDX *bounds_gidx = NULL;
2450 unsigned long offset;
2451 unsigned long offset_max;
2456 idx_rel = index_open(idx_oid, AccessShareLock);
2457 buffer = ReadBuffer(idx_rel, GIST_ROOT_BLKNO);
2458 page = (Page) BufferGetPage(
buffer);
2459 offset = FirstOffsetNumber;
2460 offset_max = PageGetMaxOffsetNumber(page);
2461 while (offset <= offset_max)
2463 ItemId iid = PageGetItemId(page, offset);
2468 index_close(idx_rel, AccessShareLock);
2471 ituple = (IndexTuple) PageGetItem(page, iid);
2472 if (!GistTupleIsInvalid(ituple))
2475 Datum idx_attr = index_getattr(ituple, idx_att_num, idx_rel->rd_att, &isnull);
2480 BOX2DF *b = (BOX2DF*)DatumGetPointer(idx_attr);
2488 GIDX *b = (GIDX*)DatumGetPointer(idx_attr);
2500 index_close(idx_rel, AccessShareLock);
2517 gbox_from_gidx(bounds_gidx, gbox, flags);
2537 int16 att_num, idx_att_num = InvalidAttrNumber;
2538 Oid tbl_oid = PG_GETARG_DATUM(0);
2539 char *col = text_to_cstring(PG_GETARG_TEXT_P(1));
2546 postgis_initialize_cache();
2548 att_num = get_attnum(tbl_oid, col);
2549 if (att_num == InvalidAttrNumber)
2560 PG_RETURN_POINTER(gbox);
2571 HeapTuple att_tuple;
2572 Form_pg_attribute att;
2574 if (!attnum || !atttypid)
2575 elog(ERROR,
"%s got null input parameters", __func__);
2578 att_tuple = SearchSysCache2(ATTNAME,
2579 ObjectIdGetDatum(table_oid),
2580 PointerGetDatum(col));
2582 if (!HeapTupleIsValid(att_tuple))
2585 att = (Form_pg_attribute) GETSTRUCT(att_tuple);
2586 *atttypid = att->atttypid;
2587 *attnum = att->attnum;
2588 ReleaseSysCache(att_tuple);
2601 text *coltxt = NULL;
2603 int16 attnum, idx_attnum;
2604 Oid atttypid = InvalidOid;
2605 char nsp_tbl[2*NAMEDATALEN+6];
2607 Oid tbl_oid, idx_oid = 0;
2610 bool only_parent =
false;
2612 Oid geographyOid = postgis_oid(GEOGRAPHYOID);
2613 Oid geometryOid = postgis_oid(GEOMETRYOID);
2616 postgis_initialize_cache();
2618 if (PG_NARGS() < 2 || PG_NARGS() > 4)
2619 elog(ERROR,
"ST_EstimatedExtent() called with wrong number of arguments");
2621 if ( PG_NARGS() == 4 )
2623 only_parent = PG_GETARG_BOOL(3);
2625 if ( PG_NARGS() >= 3 )
2627 char *nsp = text_to_cstring(PG_GETARG_TEXT_P(0));
2628 tbl = text_to_cstring(PG_GETARG_TEXT_P(1));
2629 coltxt = PG_GETARG_TEXT_P(2);
2630 snprintf(nsp_tbl,
sizeof(nsp_tbl),
"\"%s\".\"%s\"", nsp, tbl);
2632 if ( PG_NARGS() == 2 )
2634 tbl = text_to_cstring(PG_GETARG_TEXT_P(0));
2635 coltxt = PG_GETARG_TEXT_P(1);
2636 snprintf(nsp_tbl,
sizeof(nsp_tbl),
"\"%s\"", tbl);
2640 tbl_oid = DatumGetObjectId(DirectFunctionCall1(regclassin, CStringGetDatum(nsp_tbl)));
2642 elog(ERROR,
"cannot lookup table %s", nsp_tbl);
2645 col = text_to_cstring(coltxt);
2647 elog(ERROR,
"column %s.\"%s\" does not exist", nsp_tbl, col);
2650 if ((atttypid != geographyOid) && (atttypid != geometryOid))
2652 elog(ERROR,
"column %s.\"%s\" must be a geometry or geography", nsp_tbl, col);
2658 if (idx_oid != InvalidOid)
2662 elog(DEBUG3,
"index for %s.\"%s\" exists, reading gbox from there", nsp_tbl, col);
2663 if (!gbox) PG_RETURN_NULL();
2670 elog(DEBUG3,
"index for %s.\"%s\" does not exist", nsp_tbl, col);
2673 if (atttypid == geographyOid)
2682 elog(WARNING,
"stats for \"%s.%s\" do not exist", tbl, col);
2692 if (stats_mode != 2)
2704 if (atttypid == geographyOid)
2708 PG_RETURN_POINTER(gbox_planar);
2711 PG_RETURN_POINTER(gbox);
2720 if ( PG_NARGS() == 3 )
2726 PG_GETARG_DATUM(2)));
2728 else if ( PG_NARGS() == 2 )
2733 PG_GETARG_DATUM(1)));
2736 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.
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.
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 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,...
#define STATISTIC_SLOT_ND
static char * nd_stats_to_grid(const ND_STATS *stats)
Create a printable view of the ND_STATS histogram.
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 int range_full(int *vals, int nvals)
The difference between the fourth and first quintile values, the "inter-quintile range".
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 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)
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'.
Datum gserialized_gist_sel(PG_FUNCTION_ARGS)
float8 gserialized_joinsel_internal(PlannerInfo *root, List *args, JoinType jointype, int mode)
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.
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)
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)
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 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 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)
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)
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_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.
static void stringbuffer_append(stringbuffer_t *s, const char *a)
Append the specified string to the stringbuffer_t.
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.