selfuncs.c 49.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
/*-------------------------------------------------------------------------
 *
 * selfuncs.c
 *	  Selectivity functions and index cost estimation functions for
 *	  standard operators and index access methods.
 *
 *	  Selectivity routines are registered in the pg_operator catalog
 *	  in the "oprrest" and "oprjoin" attributes.
 *
 *	  Index cost functions are registered in the pg_am catalog
 *	  in the "amcostestimate" attribute.
 *
 * Portions Copyright (c) 1996-2000, PostgreSQL, Inc
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
 *	  $Header: /cvsroot/pgsql/src/backend/utils/adt/selfuncs.c,v 1.70 2000/06/09 01:11:09 tgl Exp $
 *
 *-------------------------------------------------------------------------
 */

#include "postgres.h"

#include <ctype.h>
#include <math.h>

#include "access/heapam.h"
#include "catalog/catname.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_statistic.h"
#include "catalog/pg_type.h"
#include "mb/pg_wchar.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
#include "utils/builtins.h"
#include "utils/int8.h"
#include "utils/lsyscache.h"
#include "utils/syscache.h"

/* N is not a valid var/constant or relation id */
#define NONVALUE(N)		((N) == 0)

/* default selectivity estimate for equalities such as "A = b" */
#define DEFAULT_EQ_SEL	0.01

/* default selectivity estimate for inequalities such as "A < b" */
#define DEFAULT_INEQ_SEL  (1.0 / 3.0)

/* default selectivity estimate for pattern-match operators such as LIKE */
#define DEFAULT_MATCH_SEL	0.01

/* "fudge factor" for estimating frequency of not-most-common values */
#define NOT_MOST_COMMON_RATIO  0.1

static bool convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
							  Datum lobound, Datum hibound, Oid boundstypid,
							  double *scaledlobound, double *scaledhibound);
static double convert_numeric_to_scalar(Datum value, Oid typid);
static void convert_string_to_scalar(unsigned char *value,
									 double *scaledvalue,
									 unsigned char *lobound,
									 double *scaledlobound,
									 unsigned char *hibound,
									 double *scaledhibound);
static double convert_one_string_to_scalar(unsigned char *value,
										   int rangelo, int rangehi);
static unsigned char * convert_string_datum(Datum value, Oid typid);
static double convert_timevalue_to_scalar(Datum value, Oid typid);
static void getattproperties(Oid relid, AttrNumber attnum,
				 Oid *typid,
				 int *typlen,
				 bool *typbyval,
				 int32 *typmod);
static bool getattstatistics(Oid relid, AttrNumber attnum,
				 Oid typid, int32 typmod,
				 double *nullfrac,
				 double *commonfrac,
				 Datum *commonval,
				 Datum *loval,
				 Datum *hival);
static Selectivity prefix_selectivity(char *prefix,
									  Oid relid,
									  AttrNumber attno,
									  Oid datatype);
static Selectivity pattern_selectivity(char *patt, Pattern_Type ptype);
static bool string_lessthan(const char *str1, const char *str2,
				Oid datatype);
static Oid	find_operator(const char *opname, Oid datatype);
static Datum string_to_datum(const char *str, Oid datatype);


/*
 *		eqsel			- Selectivity of "=" for any data types.
 *
 * Note: this routine is also used to estimate selectivity for some
 * operators that are not "=" but have comparable selectivity behavior,
 * such as "~=" (geometric approximate-match).  Even for "=", we must
 * keep in mind that the left and right datatypes may differ, so the type
 * of the given constant "value" may be different from the type of the
 * attribute.
 */
Datum
eqsel(PG_FUNCTION_ARGS)
{
	Oid			opid = PG_GETARG_OID(0);
	Oid			relid = PG_GETARG_OID(1);
	AttrNumber	attno = PG_GETARG_INT16(2);
	Datum		value = PG_GETARG_DATUM(3);
	int32		flag = PG_GETARG_INT32(4);
	float8		result;

	if (NONVALUE(attno) || NONVALUE(relid))
		result = DEFAULT_EQ_SEL;
	else
	{
		Oid			typid;
		int			typlen;
		bool		typbyval;
		int32		typmod;
		double		nullfrac;
		double		commonfrac;
		Datum		commonval;
		double		selec;

		/* get info about the attribute */
		getattproperties(relid, attno,
						 &typid, &typlen, &typbyval, &typmod);

		/* get stats for the attribute, if available */
		if (getattstatistics(relid, attno, typid, typmod,
							 &nullfrac, &commonfrac, &commonval,
							 NULL, NULL))
		{
			if (flag & SEL_CONSTANT)
			{

				/*
				 * Is the constant "=" to the column's most common value?
				 * (Although the operator may not really be "=", we will
				 * assume that seeing whether it returns TRUE for the most
				 * common value is useful information. If you don't like
				 * it, maybe you shouldn't be using eqsel for your
				 * operator...)
				 */
				RegProcedure eqproc = get_opcode(opid);
				bool		mostcommon;

				if (eqproc == (RegProcedure) NULL)
					elog(ERROR, "eqsel: no procedure for operator %u",
						 opid);

				/* be careful to apply operator right way 'round */
				if (flag & SEL_RIGHT)
					mostcommon = DatumGetBool(OidFunctionCall2(eqproc,
															   commonval,
															   value));
				else
					mostcommon = DatumGetBool(OidFunctionCall2(eqproc,
															   value,
															   commonval));

				if (mostcommon)
				{

					/*
					 * Constant is "=" to the most common value.  We know
					 * selectivity exactly (or as exactly as VACUUM could
					 * calculate it, anyway).
					 */
					selec = commonfrac;
				}
				else
				{

					/*
					 * Comparison is against a constant that is neither
					 * the most common value nor null.	Its selectivity
					 * cannot be more than this:
					 */
					selec = 1.0 - commonfrac - nullfrac;
					if (selec > commonfrac)
						selec = commonfrac;

					/*
					 * and in fact it's probably less, so we should apply
					 * a fudge factor.	The only case where we don't is
					 * for a boolean column, where indeed we have
					 * estimated the less-common value's frequency
					 * exactly!
					 */
					if (typid != BOOLOID)
						selec *= NOT_MOST_COMMON_RATIO;
				}
			}
			else
			{

				/*
				 * Search is for a value that we do not know a priori, but
				 * we will assume it is not NULL.  Selectivity cannot be
				 * more than this:
				 */
				selec = 1.0 - nullfrac;
				if (selec > commonfrac)
					selec = commonfrac;

				/*
				 * and in fact it's probably less, so apply a fudge
				 * factor.
				 */
				selec *= NOT_MOST_COMMON_RATIO;
			}

			/* result should be in range, but make sure... */
			if (selec < 0.0)
				selec = 0.0;
			else if (selec > 1.0)
				selec = 1.0;

			if (!typbyval)
				pfree(DatumGetPointer(commonval));
		}
		else
		{

			/*
			 * No VACUUM ANALYZE stats available, so make a guess using
			 * the disbursion stat (if we have that, which is unlikely for
			 * a normal attribute; but for a system attribute we may be
			 * able to estimate it).
			 */
			selec = get_attdisbursion(relid, attno, 0.01);
		}

		result = (float8) selec;
	}
	PG_RETURN_FLOAT8(result);
}

/*
 *		neqsel			- Selectivity of "!=" for any data types.
 *
 * This routine is also used for some operators that are not "!="
 * but have comparable selectivity behavior.  See above comments
 * for eqsel().
 */
Datum
neqsel(PG_FUNCTION_ARGS)
{
	float8		result;

	result = DatumGetFloat8(eqsel(fcinfo));
	result = 1.0 - result;
	PG_RETURN_FLOAT8(result);
}

/*
 *		scalarltsel		- Selectivity of "<" (also "<=") for scalars.
 *
 * This routine works for any datatype (or pair of datatypes) known to
 * convert_to_scalar().  If it is applied to some other datatype,
 * it will return a default estimate.
 */
Datum
scalarltsel(PG_FUNCTION_ARGS)
{
	Oid			opid = PG_GETARG_OID(0);
	Oid			relid = PG_GETARG_OID(1);
	AttrNumber	attno = PG_GETARG_INT16(2);
	Datum		value = PG_GETARG_DATUM(3);
	int32		flag = PG_GETARG_INT32(4);
	float8		result;

	if (!(flag & SEL_CONSTANT) || NONVALUE(attno) || NONVALUE(relid))
		result = DEFAULT_INEQ_SEL;
	else
	{
		HeapTuple	oprtuple;
		Oid			ltype,
					rtype,
					contype;
		Oid			typid;
		int			typlen;
		bool		typbyval;
		int32		typmod;
		Datum		hival,
					loval;
		double		val,
					high,
					low,
					numerator,
					denominator;

		/*
		 * Get left and right datatypes of the operator so we know what
		 * type the constant is.
		 */
		oprtuple = get_operator_tuple(opid);
		if (!HeapTupleIsValid(oprtuple))
			elog(ERROR, "scalarltsel: no tuple for operator %u", opid);
		ltype = ((Form_pg_operator) GETSTRUCT(oprtuple))->oprleft;
		rtype = ((Form_pg_operator) GETSTRUCT(oprtuple))->oprright;
		contype = (flag & SEL_RIGHT) ? rtype : ltype;

		/* Now get info and stats about the attribute */
		getattproperties(relid, attno,
						 &typid, &typlen, &typbyval, &typmod);

		if (!getattstatistics(relid, attno, typid, typmod,
							  NULL, NULL, NULL,
							  &loval, &hival))
		{
			/* no stats available, so default result */
			PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
		}

		/* Convert the values to a uniform comparison scale. */
		if (!convert_to_scalar(value, contype, &val,
							   loval, hival, typid,
							   &low, &high))
		{

			/*
			 * Ideally we'd produce an error here, on the grounds that the
			 * given operator shouldn't have scalarltsel registered as its
			 * selectivity func unless we can deal with its operand types.
			 * But currently, all manner of stuff is invoking scalarltsel,
			 * so give a default estimate until that can be fixed.
			 */
			if (!typbyval)
			{
				pfree(DatumGetPointer(hival));
				pfree(DatumGetPointer(loval));
			}
			PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
		}

		/* release temp storage if needed */
		if (!typbyval)
		{
			pfree(DatumGetPointer(hival));
			pfree(DatumGetPointer(loval));
		}

		if (high <= low)
		{

			/*
			 * If we trusted the stats fully, we could return a small or
			 * large selec depending on which side of the single data
			 * point the constant is on.  But it seems better to assume
			 * that the stats are wrong and return a default...
			 */
			result = DEFAULT_INEQ_SEL;
		}
		else if (val < low || val > high)
		{

			/*
			 * If given value is outside the statistical range, return a
			 * small or large value; but not 0.0/1.0 since there is a
			 * chance the stats are out of date.
			 */
			if (flag & SEL_RIGHT)
				result = (val < low) ? 0.001 : 0.999;
			else
				result = (val < low) ? 0.999 : 0.001;
		}
		else
		{
			denominator = high - low;
			if (flag & SEL_RIGHT)
				numerator = val - low;
			else
				numerator = high - val;
			result = numerator / denominator;
		}
	}
	PG_RETURN_FLOAT8(result);
}

/*
 *		scalargtsel		- Selectivity of ">" (also ">=") for integers.
 *
 * See above comments for scalarltsel.
 */
Datum
scalargtsel(PG_FUNCTION_ARGS)
{
	float8		result;

	/*
	 * Compute selectivity of "<", then invert --- but only if we were
	 * able to produce a non-default estimate.
	 */
	result = DatumGetFloat8(scalarltsel(fcinfo));
	if (result != DEFAULT_INEQ_SEL)
		result = 1.0 - result;
	PG_RETURN_FLOAT8(result);
}

/*
 * patternsel			- Generic code for pattern-match selectivity.
 */
static Datum
patternsel(PG_FUNCTION_ARGS, Pattern_Type ptype)
{
	Oid			opid = PG_GETARG_OID(0);
	Oid			relid = PG_GETARG_OID(1);
	AttrNumber	attno = PG_GETARG_INT16(2);
	Datum		value = PG_GETARG_DATUM(3);
	int32		flag = PG_GETARG_INT32(4);
	float8		result;

	/* Must have a constant for the pattern, or cannot learn anything */
	if ((flag & (SEL_CONSTANT | SEL_RIGHT)) != (SEL_CONSTANT | SEL_RIGHT))
		result = DEFAULT_MATCH_SEL;
	else
	{
		HeapTuple	oprtuple;
		Oid			ltype,
					rtype;
		char	   *patt;
		Pattern_Prefix_Status pstatus;
		char	   *prefix;
		char	   *rest;

		/*
		 * Get left and right datatypes of the operator so we know what
		 * type the attribute is.
		 */
		oprtuple = get_operator_tuple(opid);
		if (!HeapTupleIsValid(oprtuple))
			elog(ERROR, "patternsel: no tuple for operator %u", opid);
		ltype = ((Form_pg_operator) GETSTRUCT(oprtuple))->oprleft;
		rtype = ((Form_pg_operator) GETSTRUCT(oprtuple))->oprright;

		/* the right-hand const is type text for all supported operators */
		Assert(rtype == TEXTOID);
		patt = textout((text *) DatumGetPointer(value));

		/* divide pattern into fixed prefix and remainder */
		pstatus = pattern_fixed_prefix(patt, ptype, &prefix, &rest);

		if (pstatus == Pattern_Prefix_Exact)
		{
			/* Pattern specifies an exact match, so pretend operator is '=' */
			Oid		eqopr = find_operator("=", ltype);
			Datum	eqcon;

			if (eqopr == InvalidOid)
				elog(ERROR, "patternsel: no = operator for type %u", ltype);
			eqcon = string_to_datum(prefix, ltype);
			result = DatumGetFloat8(DirectFunctionCall5(eqsel,
									ObjectIdGetDatum(eqopr),
									ObjectIdGetDatum(relid),
									Int16GetDatum(attno),
									eqcon,
									Int32GetDatum(SEL_CONSTANT|SEL_RIGHT)));
			pfree(DatumGetPointer(eqcon));
		}
		else
		{
			/*
			 * Not exact-match pattern.  We estimate selectivity of the
			 * fixed prefix and remainder of pattern separately, then
			 * combine the two.
			 */
			Selectivity prefixsel;
			Selectivity restsel;
			Selectivity selec;

			if (pstatus == Pattern_Prefix_Partial)
				prefixsel = prefix_selectivity(prefix, relid, attno, ltype);
			else
				prefixsel = 1.0;
			restsel = pattern_selectivity(rest, ptype);
			selec = prefixsel * restsel;
			/* result should be in range, but make sure... */
			if (selec < 0.0)
				selec = 0.0;
			else if (selec > 1.0)
				selec = 1.0;
			result = (float8) selec;
		}
		if (prefix)
			pfree(prefix);
		pfree(patt);
	}
	PG_RETURN_FLOAT8(result);
}

/*
 *		regexeqsel		- Selectivity of regular-expression pattern match.
 */
Datum
regexeqsel(PG_FUNCTION_ARGS)
{
	return patternsel(fcinfo, Pattern_Type_Regex);
}

/*
 *		icregexeqsel	- Selectivity of case-insensitive regex match.
 */
Datum
icregexeqsel(PG_FUNCTION_ARGS)
{
	return patternsel(fcinfo, Pattern_Type_Regex_IC);
}

/*
 *		likesel			- Selectivity of LIKE pattern match.
 */
Datum
likesel(PG_FUNCTION_ARGS)
{
	return patternsel(fcinfo, Pattern_Type_Like);
}

/*
 *		regexnesel		- Selectivity of regular-expression pattern non-match.
 */
Datum
regexnesel(PG_FUNCTION_ARGS)
{
	float8		result;

	result = DatumGetFloat8(patternsel(fcinfo, Pattern_Type_Regex));
	result = 1.0 - result;
	PG_RETURN_FLOAT8(result);
}

/*
 *		icregexnesel	- Selectivity of case-insensitive regex non-match.
 */
Datum
icregexnesel(PG_FUNCTION_ARGS)
{
	float8		result;

	result = DatumGetFloat8(patternsel(fcinfo, Pattern_Type_Regex_IC));
	result = 1.0 - result;
	PG_RETURN_FLOAT8(result);
}

/*
 *		nlikesel		- Selectivity of LIKE pattern non-match.
 */
Datum
nlikesel(PG_FUNCTION_ARGS)
{
	float8		result;

	result = DatumGetFloat8(patternsel(fcinfo, Pattern_Type_Like));
	result = 1.0 - result;
	PG_RETURN_FLOAT8(result);
}

/*
 *		eqjoinsel		- Join selectivity of "="
 */
Datum
eqjoinsel(PG_FUNCTION_ARGS)
{
#ifdef NOT_USED
	Oid			opid = PG_GETARG_OID(0);
#endif
	Oid			relid1 = PG_GETARG_OID(1);
	AttrNumber	attno1 = PG_GETARG_INT16(2);
	Oid			relid2 = PG_GETARG_OID(3);
	AttrNumber	attno2 = PG_GETARG_INT16(4);
	float8		result;
	float8		num1,
				num2,
				min;
	bool		unknown1 = NONVALUE(relid1) || NONVALUE(attno1);
	bool		unknown2 = NONVALUE(relid2) || NONVALUE(attno2);

	if (unknown1 && unknown2)
		result = DEFAULT_EQ_SEL;
	else
	{
		num1 = unknown1 ? 1.0 : get_attdisbursion(relid1, attno1, 0.01);
		num2 = unknown2 ? 1.0 : get_attdisbursion(relid2, attno2, 0.01);

		/*
		 * The join selectivity cannot be more than num2, since each tuple
		 * in table 1 could match no more than num2 fraction of tuples in
		 * table 2 (and that's only if the table-1 tuple matches the most
		 * common value in table 2, so probably it's less).  By the same
		 * reasoning it is not more than num1. The min is therefore an
		 * upper bound.
		 *
		 * If we know the disbursion of only one side, use it; the reasoning
		 * above still works.
		 *
		 * XXX can we make a better estimate here?	Using the nullfrac
		 * statistic might be helpful, for example.  Assuming the operator
		 * is strict (does not succeed for null inputs) then the
		 * selectivity couldn't be more than (1-nullfrac1)*(1-nullfrac2),
		 * which might be usefully small if there are many nulls.  How
		 * about applying the operator to the most common values?
		 */
		min = (num1 < num2) ? num1 : num2;
		result = min;
	}
	PG_RETURN_FLOAT8(result);
}

/*
 *		neqjoinsel		- Join selectivity of "!="
 */
Datum
neqjoinsel(PG_FUNCTION_ARGS)
{
	float8		result;

	result = DatumGetFloat8(eqjoinsel(fcinfo));
	result = 1.0 - result;
	PG_RETURN_FLOAT8(result);
}

/*
 *		scalarltjoinsel - Join selectivity of "<" and "<=" for scalars
 */
Datum
scalarltjoinsel(PG_FUNCTION_ARGS)
{
	PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
}

/*
 *		scalargtjoinsel - Join selectivity of ">" and ">=" for scalars
 */
Datum
scalargtjoinsel(PG_FUNCTION_ARGS)
{
	PG_RETURN_FLOAT8(DEFAULT_INEQ_SEL);
}

/*
 *		regexeqjoinsel	- Join selectivity of regular-expression pattern match.
 */
Datum
regexeqjoinsel(PG_FUNCTION_ARGS)
{
	PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
}

/*
 *		icregexeqjoinsel	- Join selectivity of case-insensitive regex match.
 */
Datum
icregexeqjoinsel(PG_FUNCTION_ARGS)
{
	PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
}

/*
 *		likejoinsel			- Join selectivity of LIKE pattern match.
 */
Datum
likejoinsel(PG_FUNCTION_ARGS)
{
	PG_RETURN_FLOAT8(DEFAULT_MATCH_SEL);
}

/*
 *		regexnejoinsel	- Join selectivity of regex non-match.
 */
Datum
regexnejoinsel(PG_FUNCTION_ARGS)
{
	float8		result;

	result = DatumGetFloat8(regexeqjoinsel(fcinfo));
	result = 1.0 - result;
	PG_RETURN_FLOAT8(result);
}

/*
 *		icregexnejoinsel	- Join selectivity of case-insensitive regex non-match.
 */
Datum
icregexnejoinsel(PG_FUNCTION_ARGS)
{
	float8		result;

	result = DatumGetFloat8(icregexeqjoinsel(fcinfo));
	result = 1.0 - result;
	PG_RETURN_FLOAT8(result);
}

/*
 *		nlikejoinsel		- Join selectivity of LIKE pattern non-match.
 */
Datum
nlikejoinsel(PG_FUNCTION_ARGS)
{
	float8		result;

	result = DatumGetFloat8(likejoinsel(fcinfo));
	result = 1.0 - result;
	PG_RETURN_FLOAT8(result);
}


/*
 * convert_to_scalar
 *	  Convert non-NULL values of the indicated types to the comparison
 *	  scale needed by scalarltsel()/scalargtsel().
 *	  Returns "true" if successful.
 *
 * All numeric datatypes are simply converted to their equivalent
 * "double" values.
 *
 * String datatypes are converted by convert_string_to_scalar(),
 * which is explained below.  The reason why this routine deals with
 * three values at a time, not just one, is that we need it for strings.
 *
 * The several datatypes representing absolute times are all converted
 * to Timestamp, which is actually a double, and then we just use that
 * double value.  Note this will give bad results for the various "special"
 * values of Timestamp --- what can we do with those?
 *
 * The several datatypes representing relative times (intervals) are all
 * converted to measurements expressed in seconds.
 */
static bool
convert_to_scalar(Datum value, Oid valuetypid, double *scaledvalue,
				  Datum lobound, Datum hibound, Oid boundstypid,
				  double *scaledlobound, double *scaledhibound)
{
	switch (valuetypid)
	{

		/*
		 * Built-in numeric types
		 */
		case BOOLOID:
		case INT2OID:
		case INT4OID:
		case INT8OID:
		case FLOAT4OID:
		case FLOAT8OID:
		case NUMERICOID:
		case OIDOID:
		case REGPROCOID:
			*scaledvalue = convert_numeric_to_scalar(value, valuetypid);
			*scaledlobound = convert_numeric_to_scalar(lobound, boundstypid);
			*scaledhibound = convert_numeric_to_scalar(hibound, boundstypid);
			return true;

		/*
		 * Built-in string types
		 */
		case CHAROID:
		case BPCHAROID:
		case VARCHAROID:
		case TEXTOID:
		case NAMEOID:
		{
			unsigned char *valstr = convert_string_datum(value, valuetypid);
			unsigned char *lostr = convert_string_datum(lobound, boundstypid);
			unsigned char *histr = convert_string_datum(hibound, boundstypid);

			convert_string_to_scalar(valstr, scaledvalue,
									 lostr, scaledlobound,
									 histr, scaledhibound);
			pfree(valstr);
			pfree(lostr);
			pfree(histr);
			return true;
		}

		/*
		 * Built-in time types
		 */
		case TIMESTAMPOID:
		case ABSTIMEOID:
		case DATEOID:
		case INTERVALOID:
		case RELTIMEOID:
		case TINTERVALOID:
		case TIMEOID:
			*scaledvalue = convert_timevalue_to_scalar(value, valuetypid);
			*scaledlobound = convert_timevalue_to_scalar(lobound, boundstypid);
			*scaledhibound = convert_timevalue_to_scalar(hibound, boundstypid);
			return true;
	}
	/* Don't know how to convert */
	return false;
}

/*
 * Do convert_to_scalar()'s work for any numeric data type.
 */
static double
convert_numeric_to_scalar(Datum value, Oid typid)
{
	switch (typid)
	{
		case BOOLOID:
			return (double) DatumGetBool(value);
		case INT2OID:
			return (double) DatumGetInt16(value);
		case INT4OID:
			return (double) DatumGetInt32(value);
		case INT8OID:
			return (double) DatumGetInt64(value);
		case FLOAT4OID:
			return (double) DatumGetFloat4(value);
		case FLOAT8OID:
			return (double) DatumGetFloat8(value);
		case NUMERICOID:
			return (double) (*numeric_float8((Numeric) DatumGetPointer(value)));
		case OIDOID:
		case REGPROCOID:
			/* we can treat OIDs as integers... */
			return (double) DatumGetObjectId(value);
	}
	/* Can't get here unless someone tries to use scalarltsel/scalargtsel
	 * on an operator with one numeric and one non-numeric operand.
	 */
	elog(ERROR, "convert_numeric_to_scalar: unsupported type %u", typid);
	return 0;
}

/*
 * Do convert_to_scalar()'s work for any character-string data type.
 *
 * String datatypes are converted to a scale that ranges from 0 to 1,
 * where we visualize the bytes of the string as fractional digits.
 *
 * We do not want the base to be 256, however, since that tends to
 * generate inflated selectivity estimates; few databases will have
 * occurrences of all 256 possible byte values at each position.
 * Instead, use the smallest and largest byte values seen in the bounds
 * as the estimated range for each byte, after some fudging to deal with
 * the fact that we probably aren't going to see the full range that way.
 *
 * An additional refinement is that we discard any common prefix of the
 * three strings before computing the scaled values.  This allows us to
 * "zoom in" when we encounter a narrow data range.  An example is a phone
 * number database where all the values begin with the same area code.
 */
static void
convert_string_to_scalar(unsigned char *value,
						 double *scaledvalue,
						 unsigned char *lobound,
						 double *scaledlobound,
						 unsigned char *hibound,
						 double *scaledhibound)
{
	int			rangelo,
				rangehi;
	unsigned char *sptr;

	rangelo = rangehi = hibound[0];
	for (sptr = lobound; *sptr; sptr++)
	{
		if (rangelo > *sptr)
			rangelo = *sptr;
		if (rangehi < *sptr)
			rangehi = *sptr;
	}
	for (sptr = hibound; *sptr; sptr++)
	{
		if (rangelo > *sptr)
			rangelo = *sptr;
		if (rangehi < *sptr)
			rangehi = *sptr;
	}
	/* If range includes any upper-case ASCII chars, make it include all */
	if (rangelo <= 'Z' && rangehi >= 'A')
	{
		if (rangelo > 'A')
			rangelo = 'A';
		if (rangehi < 'Z')
			rangehi = 'Z';
	}
	/* Ditto lower-case */
	if (rangelo <= 'z' && rangehi >= 'a')
	{
		if (rangelo > 'a')
			rangelo = 'a';
		if (rangehi < 'z')
			rangehi = 'z';
	}
	/* Ditto digits */
	if (rangelo <= '9' && rangehi >= '0')
	{
		if (rangelo > '0')
			rangelo = '0';
		if (rangehi < '9')
			rangehi = '9';
	}
	/* If range includes less than 10 chars, assume we have not got enough
	 * data, and make it include regular ASCII set.
	 */
	if (rangehi - rangelo < 9)
	{
		rangelo = ' ';
		rangehi = 127;
	}

	/*
	 * Now strip any common prefix of the three strings.
	 */
	while (*lobound)
	{
		if (*lobound != *hibound || *lobound != *value)
			break;
		lobound++, hibound++, value++;
	}

	/*
	 * Now we can do the conversions.
	 */
	*scaledvalue = convert_one_string_to_scalar(value, rangelo, rangehi);
	*scaledlobound = convert_one_string_to_scalar(lobound, rangelo, rangehi);
	*scaledhibound = convert_one_string_to_scalar(hibound, rangelo, rangehi);
}

static double
convert_one_string_to_scalar(unsigned char *value, int rangelo, int rangehi)
{
	int			slen = strlen((char *) value);
	double		num,
				denom,
				base;

	if (slen <= 0)
		return 0.0;				/* empty string has scalar value 0 */

	/* Since base is at least 10, need not consider more than about 20 chars */
	if (slen > 20)
		slen = 20;

	/* Convert initial characters to fraction */
	base = rangehi - rangelo + 1;
	num = 0.0;
	denom = base;
	while (slen-- > 0)
	{
		int		ch = *value++;

		if (ch < rangelo)
			ch = rangelo-1;
		else if (ch > rangehi)
			ch = rangehi+1;
		num += ((double) (ch - rangelo)) / denom;
		denom *= base;
	}

	return num;
}

/*
 * Convert a string-type Datum into a palloc'd, null-terminated string.
 *
 * If USE_LOCALE is defined, we must pass the string through strxfrm()
 * before continuing, so as to generate correct locale-specific results.
 */
static unsigned char *
convert_string_datum(Datum value, Oid typid)
{
	char	   *val;
#ifdef USE_LOCALE
	char	   *xfrmstr;
	size_t		xfrmsize;
	size_t		xfrmlen;
#endif

	switch (typid)
	{
		case CHAROID:
			val = (char *) palloc(2);
			val[0] = DatumGetChar(value);
			val[1] = '\0';
			break;
		case BPCHAROID:
		case VARCHAROID:
		case TEXTOID:
		{
			char	   *str = (char *) VARDATA(DatumGetPointer(value));
			int			strlength = VARSIZE(DatumGetPointer(value)) - VARHDRSZ;

			val = (char *) palloc(strlength+1);
			memcpy(val, str, strlength);
			val[strlength] = '\0';
			break;
		}
		case NAMEOID:
		{
			NameData   *nm = (NameData *) DatumGetPointer(value);

			val = pstrdup(NameStr(*nm));
			break;
		}
		default:
			/* Can't get here unless someone tries to use scalarltsel
			 * on an operator with one string and one non-string operand.
			 */
			elog(ERROR, "convert_string_datum: unsupported type %u", typid);
			return NULL;
	}

#ifdef USE_LOCALE
	/* Guess that transformed string is not much bigger than original */
	xfrmsize = strlen(val) + 32;		/* arbitrary pad value here... */
	xfrmstr = (char *) palloc(xfrmsize);
	xfrmlen = strxfrm(xfrmstr, val, xfrmsize);
	if (xfrmlen >= xfrmsize)
	{
		/* Oops, didn't make it */
		pfree(xfrmstr);
		xfrmstr = (char *) palloc(xfrmlen + 1);
		xfrmlen = strxfrm(xfrmstr, val, xfrmlen + 1);
	}
	pfree(val);
	val = xfrmstr;
#endif

	return (unsigned char *) val;
}

/*
 * Do convert_to_scalar()'s work for any timevalue data type.
 */
static double
convert_timevalue_to_scalar(Datum value, Oid typid)
{
	switch (typid)
	{
		case TIMESTAMPOID:
			return DatumGetTimestamp(value);
		case ABSTIMEOID:
			return DatumGetTimestamp(DirectFunctionCall1(abstime_timestamp,
														 value));
		case DATEOID:
			return DatumGetTimestamp(DirectFunctionCall1(date_timestamp,
														 value));
		case INTERVALOID:
		{
			Interval   *interval = DatumGetIntervalP(value);

			/*
			 * Convert the month part of Interval to days using
			 * assumed average month length of 365.25/12.0 days.  Not
			 * too accurate, but plenty good enough for our purposes.
			 */
			return interval->time +
				interval->month * (365.25 / 12.0 * 24.0 * 60.0 * 60.0);
		}
		case RELTIMEOID:
			return DatumGetRelativeTime(value);
		case TINTERVALOID:
		{
			TimeInterval interval = DatumGetTimeInterval(value);

			if (interval->status != 0)
				return interval->data[1] - interval->data[0];
			return 0;			/* for lack of a better idea */
		}
		case TIMEOID:
			return DatumGetTimeADT(value);
	}
	/* Can't get here unless someone tries to use scalarltsel/scalargtsel
	 * on an operator with one timevalue and one non-timevalue operand.
	 */
	elog(ERROR, "convert_timevalue_to_scalar: unsupported type %u", typid);
	return 0;
}


/*
 * getattproperties
 *	  Retrieve pg_attribute properties for an attribute,
 *	  including type OID, type len, type byval flag, typmod.
 */
static void
getattproperties(Oid relid, AttrNumber attnum,
				 Oid *typid, int *typlen, bool *typbyval, int32 *typmod)
{
	HeapTuple	atp;
	Form_pg_attribute att_tup;

	atp = SearchSysCacheTuple(ATTNUM,
							  ObjectIdGetDatum(relid),
							  Int16GetDatum(attnum),
							  0, 0);
	if (!HeapTupleIsValid(atp))
		elog(ERROR, "getattproperties: no attribute tuple %u %d",
			 relid, (int) attnum);
	att_tup = (Form_pg_attribute) GETSTRUCT(atp);

	*typid = att_tup->atttypid;
	*typlen = att_tup->attlen;
	*typbyval = att_tup->attbyval;
	*typmod = att_tup->atttypmod;
}

/*
 * getattstatistics
 *	  Retrieve the pg_statistic data for an attribute.
 *	  Returns 'false' if no stats are available.
 *
 * Inputs:
 * 'relid' and 'attnum' are the relation and attribute number.
 * 'typid' and 'typmod' are the type and typmod of the column,
 * which the caller must already have looked up.
 *
 * Outputs:
 * The available stats are nullfrac, commonfrac, commonval, loval, hival.
 * The caller need not retrieve all five --- pass NULL pointers for the
 * unwanted values.
 *
 * commonval, loval, hival are returned as Datums holding the internal
 * representation of the values.  (Note that these should be pfree'd
 * after use if the data type is not by-value.)
 */
static bool
getattstatistics(Oid relid,
				 AttrNumber attnum,
				 Oid typid,
				 int32 typmod,
				 double *nullfrac,
				 double *commonfrac,
				 Datum *commonval,
				 Datum *loval,
				 Datum *hival)
{
	HeapTuple	tuple;
	HeapTuple	typeTuple;
	FmgrInfo	inputproc;
	Oid			typelem;
	bool		isnull;

	/*
	 * We assume that there will only be one entry in pg_statistic for the
	 * given rel/att, so we search WITHOUT considering the staop column.
	 * Someday, VACUUM might store more than one entry per rel/att,
	 * corresponding to more than one possible sort ordering defined for
	 * the column type.  However, to make that work we will need to figure
	 * out which staop to search for --- it's not necessarily the one we
	 * have at hand!  (For example, we might have a '>' operator rather
	 * than the '<' operator that will appear in staop.)
	 */
	tuple = SearchSysCacheTuple(STATRELID,
								ObjectIdGetDatum(relid),
								Int16GetDatum((int16) attnum),
								0,
								0);
	if (!HeapTupleIsValid(tuple))
	{
		/* no such stats entry */
		return false;
	}

	if (nullfrac)
		*nullfrac = ((Form_pg_statistic) GETSTRUCT(tuple))->stanullfrac;
	if (commonfrac)
		*commonfrac = ((Form_pg_statistic) GETSTRUCT(tuple))->stacommonfrac;

	/* Get the type input proc for the column datatype */
	typeTuple = SearchSysCacheTuple(TYPEOID,
									ObjectIdGetDatum(typid),
									0, 0, 0);
	if (!HeapTupleIsValid(typeTuple))
		elog(ERROR, "getattstatistics: Cache lookup failed for type %u",
			 typid);
	fmgr_info(((Form_pg_type) GETSTRUCT(typeTuple))->typinput, &inputproc);
	typelem = ((Form_pg_type) GETSTRUCT(typeTuple))->typelem;

	/*
	 * Values are variable-length fields, so cannot access as struct
	 * fields. Must do it the hard way with SysCacheGetAttr.
	 */
	if (commonval)
	{
		text	   *val = (text *) SysCacheGetAttr(STATRELID, tuple,
										  Anum_pg_statistic_stacommonval,
												   &isnull);

		if (isnull)
		{
			elog(DEBUG, "getattstatistics: stacommonval is null");
			*commonval = PointerGetDatum(NULL);
		}
		else
		{
			char	   *strval = textout(val);

			*commonval = FunctionCall3(&inputproc,
									   CStringGetDatum(strval),
									   ObjectIdGetDatum(typelem),
									   Int32GetDatum(typmod));
			pfree(strval);
		}
	}

	if (loval)
	{
		text	   *val = (text *) SysCacheGetAttr(STATRELID, tuple,
												   Anum_pg_statistic_staloval,
												   &isnull);

		if (isnull)
		{
			elog(DEBUG, "getattstatistics: staloval is null");
			*loval = PointerGetDatum(NULL);
		}
		else
		{
			char	   *strval = textout(val);

			*loval = FunctionCall3(&inputproc,
								   CStringGetDatum(strval),
								   ObjectIdGetDatum(typelem),
								   Int32GetDatum(typmod));
			pfree(strval);
		}
	}

	if (hival)
	{
		text	   *val = (text *) SysCacheGetAttr(STATRELID, tuple,
											  Anum_pg_statistic_stahival,
												   &isnull);

		if (isnull)
		{
			elog(DEBUG, "getattstatistics: stahival is null");
			*hival = PointerGetDatum(NULL);
		}
		else
		{
			char	   *strval = textout(val);

			*hival = FunctionCall3(&inputproc,
								   CStringGetDatum(strval),
								   ObjectIdGetDatum(typelem),
								   Int32GetDatum(typmod));
			pfree(strval);
		}
	}

	return true;
}

/*-------------------------------------------------------------------------
 *
 * Pattern analysis functions
 *
 * These routines support analysis of LIKE and regular-expression patterns
 * by the planner/optimizer.  It's important that they agree with the
 * regular-expression code in backend/regex/ and the LIKE code in
 * backend/utils/adt/like.c.
 *
 * Note that the prefix-analysis functions are called from
 * backend/optimizer/path/indxpath.c as well as from routines in this file.
 *
 *-------------------------------------------------------------------------
 */

/*
 * Extract the fixed prefix, if any, for a pattern.
 * *prefix is set to a palloc'd prefix string,
 * or to NULL if no fixed prefix exists for the pattern.
 * *rest is set to point to the remainder of the pattern after the
 * portion describing the fixed prefix.
 * The return value distinguishes no fixed prefix, a partial prefix,
 * or an exact-match-only pattern.
 */

static Pattern_Prefix_Status
like_fixed_prefix(char *patt, char **prefix, char **rest)
{
	char	   *match;
	int			pos,
				match_pos;

	*prefix = match = palloc(strlen(patt) + 1);
	match_pos = 0;

	for (pos = 0; patt[pos]; pos++)
	{
		/* % and _ are wildcard characters in LIKE */
		if (patt[pos] == '%' ||
			patt[pos] == '_')
			break;
		/* Backslash quotes the next character */
		if (patt[pos] == '\\')
		{
			pos++;
			if (patt[pos] == '\0')
				break;
		}

		/*
		 * NOTE: this code used to think that %% meant a literal %, but
		 * textlike() itself does not think that, and the SQL92 spec
		 * doesn't say any such thing either.
		 */
		match[match_pos++] = patt[pos];
	}

	match[match_pos] = '\0';
	*rest = &patt[pos];

	/* in LIKE, an empty pattern is an exact match! */
	if (patt[pos] == '\0')
		return Pattern_Prefix_Exact;	/* reached end of pattern, so exact */

	if (match_pos > 0)
		return Pattern_Prefix_Partial;

	pfree(match);
	*prefix = NULL;
	return Pattern_Prefix_None;
}

static Pattern_Prefix_Status
regex_fixed_prefix(char *patt, bool case_insensitive,
				   char **prefix, char **rest)
{
	char	   *match;
	int			pos,
				match_pos,
				paren_depth;

	/* Pattern must be anchored left */
	if (patt[0] != '^')
	{
		*prefix = NULL;
		*rest = patt;
		return Pattern_Prefix_None;
	}

	/* If unquoted | is present at paren level 0 in pattern, then there
	 * are multiple alternatives for the start of the string.
	 */
	paren_depth = 0;
	for (pos = 1; patt[pos]; pos++)
	{
		if (patt[pos] == '|' && paren_depth == 0)
		{
			*prefix = NULL;
			*rest = patt;
			return Pattern_Prefix_None;
		}
		else if (patt[pos] == '(')
			paren_depth++;
		else if (patt[pos] == ')' && paren_depth > 0)
			paren_depth--;
		else if (patt[pos] == '\\')
		{
			/* backslash quotes the next character */
			pos++;
			if (patt[pos] == '\0')
				break;
		}
	}

	/* OK, allocate space for pattern */
	*prefix = match = palloc(strlen(patt) + 1);
	match_pos = 0;

	/* note start at pos 1 to skip leading ^ */
	for (pos = 1; patt[pos]; pos++)
	{
		/*
		 * Check for characters that indicate multiple possible matches here.
		 * XXX I suspect isalpha() is not an adequately locale-sensitive
		 * test for characters that can vary under case folding?
		 */
		if (patt[pos] == '.' ||
			patt[pos] == '(' ||
			patt[pos] == '[' ||
			patt[pos] == '$' ||
			(case_insensitive && isalpha(patt[pos])))
			break;
		/*
		 * Check for quantifiers.  Except for +, this means the preceding
		 * character is optional, so we must remove it from the prefix too!
		 */
		if (patt[pos] == '*' ||
			patt[pos] == '?' ||
			patt[pos] == '{')
		{
			if (match_pos > 0)
				match_pos--;
			pos--;
			break;
		}
		if (patt[pos] == '+')
		{
			pos--;
			break;
		}
		if (patt[pos] == '\\')
		{
			/* backslash quotes the next character */
			pos++;
			if (patt[pos] == '\0')
				break;
		}
		match[match_pos++] = patt[pos];
	}

	match[match_pos] = '\0';
	*rest = &patt[pos];

	if (patt[pos] == '$' && patt[pos + 1] == '\0')
	{
		*rest = &patt[pos + 1];
		return Pattern_Prefix_Exact;	/* pattern specifies exact match */
	}

	if (match_pos > 0)
		return Pattern_Prefix_Partial;

	pfree(match);
	*prefix = NULL;
	return Pattern_Prefix_None;
}

Pattern_Prefix_Status
pattern_fixed_prefix(char *patt, Pattern_Type ptype,
					 char **prefix, char **rest)
{
	Pattern_Prefix_Status result;

	switch (ptype)
	{
		case Pattern_Type_Like:
			result = like_fixed_prefix(patt, prefix, rest);
			break;
		case Pattern_Type_Regex:
			result = regex_fixed_prefix(patt, false, prefix, rest);
			break;
		case Pattern_Type_Regex_IC:
			result = regex_fixed_prefix(patt, true, prefix, rest);
			break;
		default:
			elog(ERROR, "pattern_fixed_prefix: bogus ptype");
			result = Pattern_Prefix_None; /* keep compiler quiet */
			break;
	}
	return result;
}

/*
 * Estimate the selectivity of a fixed prefix for a pattern match.
 *
 * A fixed prefix "foo" is estimated as the selectivity of the expression
 * "var >= 'foo' AND var < 'fop'" (see also indxqual.c).
 */
static Selectivity
prefix_selectivity(char *prefix,
				   Oid relid,
				   AttrNumber attno,
				   Oid datatype)
{
	Selectivity	prefixsel;
	Oid			cmpopr;
	Datum		prefixcon;
	char	   *greaterstr;

	cmpopr = find_operator(">=", datatype);
	if (cmpopr == InvalidOid)
		elog(ERROR, "prefix_selectivity: no >= operator for type %u",
			 datatype);
	prefixcon = string_to_datum(prefix, datatype);
	/* Assume scalargtsel is appropriate for all supported types */
	prefixsel = DatumGetFloat8(DirectFunctionCall5(scalargtsel,
							   ObjectIdGetDatum(cmpopr),
							   ObjectIdGetDatum(relid),
							   Int16GetDatum(attno),
							   prefixcon,
							   Int32GetDatum(SEL_CONSTANT|SEL_RIGHT)));
	pfree(DatumGetPointer(prefixcon));

	/*
	 * If we can create a string larger than the prefix,
	 * say "x < greaterstr".
	 */
	greaterstr = make_greater_string(prefix, datatype);
	if (greaterstr)
	{
		Selectivity		topsel;

		cmpopr = find_operator("<", datatype);
		if (cmpopr == InvalidOid)
			elog(ERROR, "prefix_selectivity: no < operator for type %u",
				 datatype);
		prefixcon = string_to_datum(greaterstr, datatype);
		/* Assume scalarltsel is appropriate for all supported types */
		topsel = DatumGetFloat8(DirectFunctionCall5(scalarltsel,
								ObjectIdGetDatum(cmpopr),
								ObjectIdGetDatum(relid),
								Int16GetDatum(attno),
								prefixcon,
								Int32GetDatum(SEL_CONSTANT|SEL_RIGHT)));
		pfree(DatumGetPointer(prefixcon));
		pfree(greaterstr);

		/*
		 * Merge the two selectivities in the same way as for
		 * a range query (see clauselist_selectivity()).
		 */
		prefixsel = topsel + prefixsel - 1.0;

		/*
		 * A zero or slightly negative prefixsel should be converted into a
		 * small positive value; we probably are dealing with a very
		 * tight range and got a bogus result due to roundoff errors.
		 * However, if prefixsel is very negative, then we probably have
		 * default selectivity estimates on one or both sides of the
		 * range.  In that case, insert a not-so-wildly-optimistic
		 * default estimate.
		 */
		if (prefixsel <= 0.0)
		{
			if (prefixsel < -0.01)
			{

				/*
				 * No data available --- use a default estimate that
				 * is small, but not real small.
				 */
				prefixsel = 0.01;
			}
			else
			{

				/*
				 * It's just roundoff error; use a small positive value
				 */
				prefixsel = 1.0e-10;
			}
		}
	}

	return prefixsel;
}


/*
 * Estimate the selectivity of a pattern of the specified type.
 * Note that any fixed prefix of the pattern will have been removed already.
 *
 * For now, we use a very simplistic approach: fixed characters reduce the
 * selectivity a good deal, character ranges reduce it a little,
 * wildcards (such as % for LIKE or .* for regex) increase it.
 */

#define FIXED_CHAR_SEL	0.04	/* about 1/25 */
#define CHAR_RANGE_SEL	0.25
#define ANY_CHAR_SEL	0.9		/* not 1, since it won't match end-of-string */
#define FULL_WILDCARD_SEL 5.0
#define PARTIAL_WILDCARD_SEL 2.0

static Selectivity
like_selectivity(char *patt)
{
	Selectivity		sel = 1.0;
	int				pos;

	/* Skip any leading %; it's already factored into initial sel */
	pos = (*patt == '%') ? 1 : 0;
	for (; patt[pos]; pos++)
	{
		/* % and _ are wildcard characters in LIKE */
		if (patt[pos] == '%')
			sel *= FULL_WILDCARD_SEL;
		else if (patt[pos] == '_')
			sel *= ANY_CHAR_SEL;
		else if (patt[pos] == '\\')
		{
			/* Backslash quotes the next character */
			pos++;
			if (patt[pos] == '\0')
				break;
			sel *= FIXED_CHAR_SEL;
		}
		else
			sel *= FIXED_CHAR_SEL;
	}
	/* Could get sel > 1 if multiple wildcards */
	if (sel > 1.0)
		sel = 1.0;
	return sel;
}

static Selectivity
regex_selectivity_sub(char *patt, int pattlen, bool case_insensitive)
{
	Selectivity		sel = 1.0;
	int				paren_depth = 0;
	int				paren_pos = 0; /* dummy init to keep compiler quiet */
	int				pos;

	for (pos = 0; pos < pattlen; pos++)
	{
		if (patt[pos] == '(')
		{
			if (paren_depth == 0)
				paren_pos = pos; /* remember start of parenthesized item */
			paren_depth++;
		}
		else if (patt[pos] == ')' && paren_depth > 0)
		{
			paren_depth--;
			if (paren_depth == 0)
				sel *= regex_selectivity_sub(patt + (paren_pos + 1),
											 pos - (paren_pos + 1),
											 case_insensitive);
		}
		else if (patt[pos] == '|' && paren_depth == 0)
		{
			/*
			 * If unquoted | is present at paren level 0 in pattern,
			 * we have multiple alternatives; sum their probabilities.
			 */
			sel += regex_selectivity_sub(patt + (pos + 1),
										 pattlen - (pos + 1),
										 case_insensitive);
			break;				/* rest of pattern is now processed */
		}
		else if (patt[pos] == '[')
		{
			bool	negclass = false;

			if (patt[++pos] == '^')
			{
				negclass = true;
				pos++;
			}
			if (patt[pos] == ']') /* ']' at start of class is not special */
				pos++;
			while (pos < pattlen && patt[pos] != ']')
				pos++;
			if (paren_depth == 0)
				sel *= (negclass ? (1.0-CHAR_RANGE_SEL) : CHAR_RANGE_SEL);
		}
		else if (patt[pos] == '.')
		{
			if (paren_depth == 0)
				sel *= ANY_CHAR_SEL;
		}
		else if (patt[pos] == '*' ||
				 patt[pos] == '?' ||
				 patt[pos] == '+')
		{
			/* Ought to be smarter about quantifiers... */
			if (paren_depth == 0)
				sel *= PARTIAL_WILDCARD_SEL;
		}
		else if (patt[pos] == '{')
		{
			while (pos < pattlen && patt[pos] != '}')
				pos++;
			if (paren_depth == 0)
				sel *= PARTIAL_WILDCARD_SEL;
		}
		else if (patt[pos] == '\\')
		{
			/* backslash quotes the next character */
			pos++;
			if (pos >= pattlen)
				break;
			if (paren_depth == 0)
				sel *= FIXED_CHAR_SEL;
		}
		else
		{
			if (paren_depth == 0)
				sel *= FIXED_CHAR_SEL;
		}
	}
	/* Could get sel > 1 if multiple wildcards */
	if (sel > 1.0)
		sel = 1.0;
	return sel;
}

static Selectivity
regex_selectivity(char *patt, bool case_insensitive)
{
	Selectivity		sel;
	int				pattlen = strlen(patt);

	/* If patt doesn't end with $, consider it to have a trailing wildcard */
	if (pattlen > 0 && patt[pattlen-1] == '$' &&
		(pattlen == 1 || patt[pattlen-2] != '\\'))
	{
		/* has trailing $ */
		sel = regex_selectivity_sub(patt, pattlen-1, case_insensitive);
	}
	else
	{
		/* no trailing $ */
		sel = regex_selectivity_sub(patt, pattlen, case_insensitive);
		sel *= FULL_WILDCARD_SEL;
		if (sel > 1.0)
			sel = 1.0;
	}
	return sel;
}

static Selectivity
pattern_selectivity(char *patt, Pattern_Type ptype)
{
	Selectivity result;

	switch (ptype)
	{
		case Pattern_Type_Like:
			result = like_selectivity(patt);
			break;
		case Pattern_Type_Regex:
			result = regex_selectivity(patt, false);
			break;
		case Pattern_Type_Regex_IC:
			result = regex_selectivity(patt, true);
			break;
		default:
			elog(ERROR, "pattern_selectivity: bogus ptype");
			result = 1.0;		/* keep compiler quiet */
			break;
	}
	return result;
}


/*
 * Try to generate a string greater than the given string or any string it is
 * a prefix of.  If successful, return a palloc'd string; else return NULL.
 *
 * To work correctly in non-ASCII locales with weird collation orders,
 * we cannot simply increment "foo" to "fop" --- we have to check whether
 * we actually produced a string greater than the given one.  If not,
 * increment the righthand byte again and repeat.  If we max out the righthand
 * byte, truncate off the last character and start incrementing the next.
 * For example, if "z" were the last character in the sort order, then we
 * could produce "foo" as a string greater than "fonz".
 *
 * This could be rather slow in the worst case, but in most cases we won't
 * have to try more than one or two strings before succeeding.
 *
 * XXX in a sufficiently weird locale, this might produce incorrect results?
 * For example, in German I believe "ss" is treated specially --- if we are
 * given "foos" and return "foot", will this actually be greater than "fooss"?
 */
char *
make_greater_string(const char *str, Oid datatype)
{
	char	   *workstr;
	int			len;

	/*
	 * Make a modifiable copy, which will be our return value if
	 * successful
	 */
	workstr = pstrdup((char *) str);

	while ((len = strlen(workstr)) > 0)
	{
		unsigned char *lastchar = (unsigned char *) (workstr + len - 1);

		/*
		 * Try to generate a larger string by incrementing the last byte.
		 */
		while (*lastchar < (unsigned char) 255)
		{
			(*lastchar)++;
			if (string_lessthan(str, workstr, datatype))
				return workstr; /* Success! */
		}

		/*
		 * Truncate off the last character, which might be more than 1
		 * byte in MULTIBYTE case.
		 */
#ifdef MULTIBYTE
		len = pg_mbcliplen((const unsigned char *) workstr, len, len - 1);
		workstr[len] = '\0';
#else
		*lastchar = '\0';
#endif
	}

	/* Failed... */
	pfree(workstr);
	return NULL;
}

/*
 * Test whether two strings are "<" according to the rules of the given
 * datatype.  We do this the hard way, ie, actually calling the type's
 * "<" operator function, to ensure we get the right result...
 */
static bool
string_lessthan(const char *str1, const char *str2, Oid datatype)
{
	Datum		datum1 = string_to_datum(str1, datatype);
	Datum		datum2 = string_to_datum(str2, datatype);
	bool		result;

	switch (datatype)
	{
		case TEXTOID:
			result = text_lt((text *) datum1, (text *) datum2);
			break;

		case BPCHAROID:
			result = bpcharlt((char *) datum1, (char *) datum2);
			break;

		case VARCHAROID:
			result = varcharlt((char *) datum1, (char *) datum2);
			break;

		case NAMEOID:
			result = namelt((NameData *) datum1, (NameData *) datum2);
			break;

		default:
			elog(ERROR, "string_lessthan: unexpected datatype %u", datatype);
			result = false;
			break;
	}

	pfree(DatumGetPointer(datum1));
	pfree(DatumGetPointer(datum2));

	return result;
}

/* See if there is a binary op of the given name for the given datatype */
static Oid
find_operator(const char *opname, Oid datatype)
{
	HeapTuple	optup;

	optup = SearchSysCacheTuple(OPERNAME,
								PointerGetDatum(opname),
								ObjectIdGetDatum(datatype),
								ObjectIdGetDatum(datatype),
								CharGetDatum('b'));
	if (!HeapTupleIsValid(optup))
		return InvalidOid;
	return optup->t_data->t_oid;
}

/*
 * Generate a Datum of the appropriate type from a C string.
 * Note that all of the supported types are pass-by-ref, so the
 * returned value should be pfree'd if no longer needed.
 */
static Datum
string_to_datum(const char *str, Oid datatype)
{

	/*
	 * We cheat a little by assuming that textin() will do for bpchar and
	 * varchar constants too...
	 */
	if (datatype == NAMEOID)
		return PointerGetDatum(namein((char *) str));
	else
		return PointerGetDatum(textin((char *) str));
}

/*-------------------------------------------------------------------------
 *
 * Index cost estimation functions
 *
 * genericcostestimate is a general-purpose estimator for use when we
 * don't have any better idea about how to estimate.  Index-type-specific
 * knowledge can be incorporated in the type-specific routines.
 *
 *-------------------------------------------------------------------------
 */

static Datum
genericcostestimate(PG_FUNCTION_ARGS)
{
	Query	   *root = (Query *) PG_GETARG_POINTER(0);
	RelOptInfo *rel = (RelOptInfo *) PG_GETARG_POINTER(1);
	IndexOptInfo *index = (IndexOptInfo *) PG_GETARG_POINTER(2);
	List	   *indexQuals = (List *) PG_GETARG_POINTER(3);
	Cost	   *indexStartupCost = (Cost *) PG_GETARG_POINTER(4);
	Cost	   *indexTotalCost = (Cost *) PG_GETARG_POINTER(5);
	Selectivity *indexSelectivity = (Selectivity *) PG_GETARG_POINTER(6);
	double		numIndexTuples;
	double		numIndexPages;

	/* Estimate the fraction of main-table tuples that will be visited */
	*indexSelectivity = clauselist_selectivity(root, indexQuals,
											   lfirsti(rel->relids));

	/* Estimate the number of index tuples that will be visited */
	numIndexTuples = *indexSelectivity * index->tuples;

	/* Estimate the number of index pages that will be retrieved */
	numIndexPages = *indexSelectivity * index->pages;

	/*
	 * Always estimate at least one tuple and page are touched, even when
	 * indexSelectivity estimate is tiny.
	 */
	if (numIndexTuples < 1.0)
		numIndexTuples = 1.0;
	if (numIndexPages < 1.0)
		numIndexPages = 1.0;

	/*
	 * Compute the index access cost.
	 *
	 * Our generic assumption is that the index pages will be read
	 * sequentially, so they have cost 1.0 each, not random_page_cost.
	 * Also, we charge for evaluation of the indexquals at each index
	 * tuple. All the costs are assumed to be paid incrementally during
	 * the scan.
	 */
	*indexStartupCost = 0;
	*indexTotalCost = numIndexPages +
		(cpu_index_tuple_cost + cost_qual_eval(indexQuals)) * numIndexTuples;

	/* No real return value ... */
	PG_RETURN_POINTER(NULL);
}

/*
 * For first cut, just use generic function for all index types.
 */

Datum
btcostestimate(PG_FUNCTION_ARGS)
{
	return genericcostestimate(fcinfo);
}

Datum
rtcostestimate(PG_FUNCTION_ARGS)
{
	return genericcostestimate(fcinfo);
}

Datum
hashcostestimate(PG_FUNCTION_ARGS)
{
	return genericcostestimate(fcinfo);
}

Datum
gistcostestimate(PG_FUNCTION_ARGS)
{
	return genericcostestimate(fcinfo);
}