PostgreSQL Source Code  git master
tablefunc.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "common/pg_prng.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "miscadmin.h"
#include "tablefunc.h"
#include "utils/builtins.h"
Include dependency graph for tablefunc.c:

Go to the source code of this file.

Data Structures

struct  normal_rand_fctx
 
struct  crosstab_cat_desc
 
struct  crosstab_hashent
 

Macros

#define xpfree(var_)
 
#define xpstrdup(tgtvar_, srcvar_)
 
#define xstreq(tgtvar_, srcvar_)
 
#define INT32_STRLEN   12
 
#define MAX_CATNAME_LEN   NAMEDATALEN
 
#define INIT_CATS   64
 
#define crosstab_HashTableLookup(HASHTAB, CATNAME, CATDESC)
 
#define crosstab_HashTableInsert(HASHTAB, CATDESC)
 
#define CONNECTBY_NCOLS   4
 
#define CONNECTBY_NCOLS_NOBRANCH   3
 

Typedefs

typedef struct crosstab_cat_desc crosstab_cat_desc
 
typedef struct crosstab_hashent crosstab_HashEnt
 

Functions

static HTABload_categories_hash (char *cats_sql, MemoryContext per_query_ctx)
 
static Tuplestorestateget_crosstab_tuplestore (char *sql, HTAB *crosstab_hash, TupleDesc tupdesc, bool randomAccess)
 
static void validateConnectbyTupleDesc (TupleDesc td, bool show_branch, bool show_serial)
 
static bool compatCrosstabTupleDescs (TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
 
static void compatConnectbyTupleDescs (TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
 
static void get_normal_pair (float8 *x1, float8 *x2)
 
static Tuplestorestateconnectby (char *relname, char *key_fld, char *parent_key_fld, char *orderby_fld, char *branch_delim, char *start_with, int max_depth, bool show_branch, bool show_serial, MemoryContext per_query_ctx, bool randomAccess, AttInMetadata *attinmeta)
 
static void build_tuplestore_recursively (char *key_fld, char *parent_key_fld, char *relname, char *orderby_fld, char *branch_delim, char *start_with, char *branch, int level, int *serial, int max_depth, bool show_branch, bool show_serial, MemoryContext per_query_ctx, AttInMetadata *attinmeta, Tuplestorestate *tupstore)
 
 PG_FUNCTION_INFO_V1 (normal_rand)
 
Datum normal_rand (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (crosstab)
 
Datum crosstab (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (crosstab_hash)
 
Datum crosstab_hash (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (connectby_text)
 
Datum connectby_text (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (connectby_text_serial)
 
Datum connectby_text_serial (PG_FUNCTION_ARGS)
 

Variables

 PG_MODULE_MAGIC
 

Macro Definition Documentation

◆ CONNECTBY_NCOLS

#define CONNECTBY_NCOLS   4

Definition at line 985 of file tablefunc.c.

◆ CONNECTBY_NCOLS_NOBRANCH

#define CONNECTBY_NCOLS_NOBRANCH   3

Definition at line 986 of file tablefunc.c.

◆ crosstab_HashTableInsert

#define crosstab_HashTableInsert (   HASHTAB,
  CATDESC 
)
Value:
do { \
crosstab_HashEnt *hentry; bool found; char key[MAX_CATNAME_LEN]; \
snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATDESC->catname); \
hentry = (crosstab_HashEnt*) hash_search(HASHTAB, \
key, HASH_ENTER, &found); \
if (found) \
ereport(ERROR, \
errmsg("duplicate category name"))); \
hentry->catdesc = CATDESC; \
} while(0)
#define MemSet(start, val, len)
Definition: c.h:1004
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:953
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
@ HASH_ENTER
Definition: hsearch.h:114
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#define MAX_CATNAME_LEN
Definition: tablefunc.c:125

Definition at line 142 of file tablefunc.c.

◆ crosstab_HashTableLookup

#define crosstab_HashTableLookup (   HASHTAB,
  CATNAME,
  CATDESC 
)
Value:
do { \
crosstab_HashEnt *hentry; char key[MAX_CATNAME_LEN]; \
snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATNAME); \
hentry = (crosstab_HashEnt*) hash_search(HASHTAB, \
key, HASH_FIND, NULL); \
if (hentry) \
CATDESC = hentry->catdesc; \
else \
CATDESC = NULL; \
} while(0)
@ HASH_FIND
Definition: hsearch.h:113

Definition at line 128 of file tablefunc.c.

◆ INIT_CATS

#define INIT_CATS   64

Definition at line 126 of file tablefunc.c.

◆ INT32_STRLEN

#define INT32_STRLEN   12

Definition at line 116 of file tablefunc.c.

◆ MAX_CATNAME_LEN

#define MAX_CATNAME_LEN   NAMEDATALEN

Definition at line 125 of file tablefunc.c.

◆ xpfree

#define xpfree (   var_)
Value:
do { \
if (var_ != NULL) \
{ \
pfree(var_); \
var_ = NULL; \
} \
} while (0)

Definition at line 94 of file tablefunc.c.

◆ xpstrdup

#define xpstrdup (   tgtvar_,
  srcvar_ 
)
Value:
do { \
if (srcvar_) \
tgtvar_ = pstrdup(srcvar_); \
else \
tgtvar_ = NULL; \
} while (0)
char * pstrdup(const char *in)
Definition: mcxt.c:1644

Definition at line 103 of file tablefunc.c.

◆ xstreq

#define xstreq (   tgtvar_,
  srcvar_ 
)
Value:
(((tgtvar_ == NULL) && (srcvar_ == NULL)) || \
((tgtvar_ != NULL) && (srcvar_ != NULL) && (strcmp(tgtvar_, srcvar_) == 0)))

Definition at line 111 of file tablefunc.c.

Typedef Documentation

◆ crosstab_cat_desc

◆ crosstab_HashEnt

Function Documentation

◆ build_tuplestore_recursively()

static void build_tuplestore_recursively ( char *  key_fld,
char *  parent_key_fld,
char *  relname,
char *  orderby_fld,
char *  branch_delim,
char *  start_with,
char *  branch,
int  level,
int *  serial,
int  max_depth,
bool  show_branch,
bool  show_serial,
MemoryContext  per_query_ctx,
AttInMetadata attinmeta,
Tuplestorestate tupstore 
)
static

Definition at line 1204 of file tablefunc.c.

1219 {
1220  TupleDesc tupdesc = attinmeta->tupdesc;
1221  int ret;
1222  uint64 proc;
1223  int serial_column;
1224  StringInfoData sql;
1225  char **values;
1226  char *current_key;
1227  char *current_key_parent;
1228  char current_level[INT32_STRLEN];
1229  char serial_str[INT32_STRLEN];
1230  char *current_branch;
1231  HeapTuple tuple;
1232 
1233  if (max_depth > 0 && level > max_depth)
1234  return;
1235 
1236  initStringInfo(&sql);
1237 
1238  /* Build initial sql statement */
1239  if (!show_serial)
1240  {
1241  appendStringInfo(&sql, "SELECT %s, %s FROM %s WHERE %s = %s AND %s IS NOT NULL AND %s <> %s",
1242  key_fld,
1243  parent_key_fld,
1244  relname,
1245  parent_key_fld,
1246  quote_literal_cstr(start_with),
1247  key_fld, key_fld, parent_key_fld);
1248  serial_column = 0;
1249  }
1250  else
1251  {
1252  appendStringInfo(&sql, "SELECT %s, %s FROM %s WHERE %s = %s AND %s IS NOT NULL AND %s <> %s ORDER BY %s",
1253  key_fld,
1254  parent_key_fld,
1255  relname,
1256  parent_key_fld,
1257  quote_literal_cstr(start_with),
1258  key_fld, key_fld, parent_key_fld,
1259  orderby_fld);
1260  serial_column = 1;
1261  }
1262 
1263  if (show_branch)
1264  values = (char **) palloc((CONNECTBY_NCOLS + serial_column) * sizeof(char *));
1265  else
1266  values = (char **) palloc((CONNECTBY_NCOLS_NOBRANCH + serial_column) * sizeof(char *));
1267 
1268  /* First time through, do a little setup */
1269  if (level == 0)
1270  {
1271  /* root value is the one we initially start with */
1272  values[0] = start_with;
1273 
1274  /* root value has no parent */
1275  values[1] = NULL;
1276 
1277  /* root level is 0 */
1278  sprintf(current_level, "%d", level);
1279  values[2] = current_level;
1280 
1281  /* root branch is just starting root value */
1282  if (show_branch)
1283  values[3] = start_with;
1284 
1285  /* root starts the serial with 1 */
1286  if (show_serial)
1287  {
1288  sprintf(serial_str, "%d", (*serial)++);
1289  if (show_branch)
1290  values[4] = serial_str;
1291  else
1292  values[3] = serial_str;
1293  }
1294 
1295  /* construct the tuple */
1296  tuple = BuildTupleFromCStrings(attinmeta, values);
1297 
1298  /* now store it */
1299  tuplestore_puttuple(tupstore, tuple);
1300 
1301  /* increment level */
1302  level++;
1303  }
1304 
1305  /* Retrieve the desired rows */
1306  ret = SPI_execute(sql.data, true, 0);
1307  proc = SPI_processed;
1308 
1309  /* Check for qualifying tuples */
1310  if ((ret == SPI_OK_SELECT) && (proc > 0))
1311  {
1312  HeapTuple spi_tuple;
1313  SPITupleTable *tuptable = SPI_tuptable;
1314  TupleDesc spi_tupdesc = tuptable->tupdesc;
1315  uint64 i;
1316  StringInfoData branchstr;
1317  StringInfoData chk_branchstr;
1318  StringInfoData chk_current_key;
1319 
1320  /*
1321  * Check that return tupdesc is compatible with the one we got from
1322  * the query.
1323  */
1324  compatConnectbyTupleDescs(tupdesc, spi_tupdesc);
1325 
1326  initStringInfo(&branchstr);
1327  initStringInfo(&chk_branchstr);
1328  initStringInfo(&chk_current_key);
1329 
1330  for (i = 0; i < proc; i++)
1331  {
1332  /* initialize branch for this pass */
1333  appendStringInfoString(&branchstr, branch);
1334  appendStringInfo(&chk_branchstr, "%s%s%s", branch_delim, branch, branch_delim);
1335 
1336  /* get the next sql result tuple */
1337  spi_tuple = tuptable->vals[i];
1338 
1339  /* get the current key (might be NULL) */
1340  current_key = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
1341 
1342  /* get the parent key (might be NULL) */
1343  current_key_parent = SPI_getvalue(spi_tuple, spi_tupdesc, 2);
1344 
1345  /* get the current level */
1346  sprintf(current_level, "%d", level);
1347 
1348  /* check to see if this key is also an ancestor */
1349  if (current_key)
1350  {
1351  appendStringInfo(&chk_current_key, "%s%s%s",
1352  branch_delim, current_key, branch_delim);
1353  if (strstr(chk_branchstr.data, chk_current_key.data))
1354  ereport(ERROR,
1355  (errcode(ERRCODE_INVALID_RECURSION),
1356  errmsg("infinite recursion detected")));
1357  }
1358 
1359  /* OK, extend the branch */
1360  if (current_key)
1361  appendStringInfo(&branchstr, "%s%s", branch_delim, current_key);
1362  current_branch = branchstr.data;
1363 
1364  /* build a tuple */
1365  values[0] = current_key;
1366  values[1] = current_key_parent;
1367  values[2] = current_level;
1368  if (show_branch)
1369  values[3] = current_branch;
1370  if (show_serial)
1371  {
1372  sprintf(serial_str, "%d", (*serial)++);
1373  if (show_branch)
1374  values[4] = serial_str;
1375  else
1376  values[3] = serial_str;
1377  }
1378 
1379  tuple = BuildTupleFromCStrings(attinmeta, values);
1380 
1381  /* store the tuple for later use */
1382  tuplestore_puttuple(tupstore, tuple);
1383 
1384  heap_freetuple(tuple);
1385 
1386  /* recurse using current_key as the new start_with */
1387  if (current_key)
1389  parent_key_fld,
1390  relname,
1391  orderby_fld,
1392  branch_delim,
1393  current_key,
1394  current_branch,
1395  level + 1,
1396  serial,
1397  max_depth,
1398  show_branch,
1399  show_serial,
1400  per_query_ctx,
1401  attinmeta,
1402  tupstore);
1403 
1404  xpfree(current_key);
1405  xpfree(current_key_parent);
1406 
1407  /* reset branch for next pass */
1408  resetStringInfo(&branchstr);
1409  resetStringInfo(&chk_branchstr);
1410  resetStringInfo(&chk_current_key);
1411  }
1412 
1413  xpfree(branchstr.data);
1414  xpfree(chk_branchstr.data);
1415  xpfree(chk_current_key.data);
1416  }
1417 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define ereport(elevel,...)
Definition: elog.h:149
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2136
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
int i
Definition: isn.c:73
void * palloc(Size size)
Definition: mcxt.c:1226
NameData relname
Definition: pg_class.h:38
#define sprintf
Definition: port.h:240
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:103
uint64 SPI_processed
Definition: spi.c:45
SPITupleTable * SPI_tuptable
Definition: spi.c:46
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:1218
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:594
#define SPI_OK_SELECT
Definition: spi.h:86
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
TupleDesc tupdesc
Definition: funcapi.h:38
TupleDesc tupdesc
Definition: spi.h:25
HeapTuple * vals
Definition: spi.h:26
#define CONNECTBY_NCOLS_NOBRANCH
Definition: tablefunc.c:986
#define INT32_STRLEN
Definition: tablefunc.c:116
static void build_tuplestore_recursively(char *key_fld, char *parent_key_fld, char *relname, char *orderby_fld, char *branch_delim, char *start_with, char *branch, int level, int *serial, int max_depth, bool show_branch, bool show_serial, MemoryContext per_query_ctx, AttInMetadata *attinmeta, Tuplestorestate *tupstore)
Definition: tablefunc.c:1204
#define CONNECTBY_NCOLS
Definition: tablefunc.c:985
static void compatConnectbyTupleDescs(TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
Definition: tablefunc.c:1498
#define xpfree(var_)
Definition: tablefunc.c:94
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:730

References appendStringInfo(), appendStringInfoString(), BuildTupleFromCStrings(), compatConnectbyTupleDescs(), CONNECTBY_NCOLS, CONNECTBY_NCOLS_NOBRANCH, StringInfoData::data, ereport, errcode(), errmsg(), ERROR, heap_freetuple(), i, initStringInfo(), INT32_STRLEN, palloc(), quote_literal_cstr(), relname, resetStringInfo(), SPI_execute(), SPI_getvalue(), SPI_OK_SELECT, SPI_processed, SPI_tuptable, sprintf, SPITupleTable::tupdesc, AttInMetadata::tupdesc, tuplestore_puttuple(), SPITupleTable::vals, values, and xpfree.

Referenced by connectby().

◆ compatConnectbyTupleDescs()

static void compatConnectbyTupleDescs ( TupleDesc  ret_tupdesc,
TupleDesc  sql_tupdesc 
)
static

Definition at line 1498 of file tablefunc.c.

1499 {
1500  Oid ret_atttypid;
1501  Oid sql_atttypid;
1502  int32 ret_atttypmod;
1503  int32 sql_atttypmod;
1504 
1505  /*
1506  * Result must have at least 2 columns.
1507  */
1508  if (sql_tupdesc->natts < 2)
1509  ereport(ERROR,
1510  (errcode(ERRCODE_DATATYPE_MISMATCH),
1511  errmsg("invalid return type"),
1512  errdetail("Query must return at least two columns.")));
1513 
1514  /*
1515  * These columns must match the result type indicated by the calling
1516  * query.
1517  */
1518  ret_atttypid = TupleDescAttr(ret_tupdesc, 0)->atttypid;
1519  sql_atttypid = TupleDescAttr(sql_tupdesc, 0)->atttypid;
1520  ret_atttypmod = TupleDescAttr(ret_tupdesc, 0)->atttypmod;
1521  sql_atttypmod = TupleDescAttr(sql_tupdesc, 0)->atttypmod;
1522  if (ret_atttypid != sql_atttypid ||
1523  (ret_atttypmod >= 0 && ret_atttypmod != sql_atttypmod))
1524  ereport(ERROR,
1525  (errcode(ERRCODE_DATATYPE_MISMATCH),
1526  errmsg("invalid return type"),
1527  errdetail("SQL key field type %s does " \
1528  "not match return key field type %s.",
1529  format_type_with_typemod(ret_atttypid, ret_atttypmod),
1530  format_type_with_typemod(sql_atttypid, sql_atttypmod))));
1531 
1532  ret_atttypid = TupleDescAttr(ret_tupdesc, 1)->atttypid;
1533  sql_atttypid = TupleDescAttr(sql_tupdesc, 1)->atttypid;
1534  ret_atttypmod = TupleDescAttr(ret_tupdesc, 1)->atttypmod;
1535  sql_atttypmod = TupleDescAttr(sql_tupdesc, 1)->atttypmod;
1536  if (ret_atttypid != sql_atttypid ||
1537  (ret_atttypmod >= 0 && ret_atttypmod != sql_atttypmod))
1538  ereport(ERROR,
1539  (errcode(ERRCODE_DATATYPE_MISMATCH),
1540  errmsg("invalid return type"),
1541  errdetail("SQL parent key field type %s does " \
1542  "not match return parent key field type %s.",
1543  format_type_with_typemod(ret_atttypid, ret_atttypmod),
1544  format_type_with_typemod(sql_atttypid, sql_atttypmod))));
1545 
1546  /* OK, the two tupdescs are compatible for our purposes */
1547 }
signed int int32
Definition: c.h:478
int errdetail(const char *fmt,...)
Definition: elog.c:1202
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:358
unsigned int Oid
Definition: postgres_ext.h:31
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References ereport, errcode(), errdetail(), errmsg(), ERROR, format_type_with_typemod(), TupleDescData::natts, and TupleDescAttr.

Referenced by build_tuplestore_recursively().

◆ compatCrosstabTupleDescs()

static bool compatCrosstabTupleDescs ( TupleDesc  ret_tupdesc,
TupleDesc  sql_tupdesc 
)
static

Definition at line 1553 of file tablefunc.c.

1554 {
1555  int i;
1556  Form_pg_attribute ret_attr;
1557  Oid ret_atttypid;
1558  Form_pg_attribute sql_attr;
1559  Oid sql_atttypid;
1560 
1561  if (ret_tupdesc->natts < 2 ||
1562  sql_tupdesc->natts < 3)
1563  return false;
1564 
1565  /* check the rowid types match */
1566  ret_atttypid = TupleDescAttr(ret_tupdesc, 0)->atttypid;
1567  sql_atttypid = TupleDescAttr(sql_tupdesc, 0)->atttypid;
1568  if (ret_atttypid != sql_atttypid)
1569  ereport(ERROR,
1570  (errcode(ERRCODE_DATATYPE_MISMATCH),
1571  errmsg("invalid return type"),
1572  errdetail("SQL rowid datatype does not match " \
1573  "return rowid datatype.")));
1574 
1575  /*
1576  * - attribute [1] of the sql tuple is the category; no need to check it -
1577  * attribute [2] of the sql tuple should match attributes [1] to [natts]
1578  * of the return tuple
1579  */
1580  sql_attr = TupleDescAttr(sql_tupdesc, 2);
1581  for (i = 1; i < ret_tupdesc->natts; i++)
1582  {
1583  ret_attr = TupleDescAttr(ret_tupdesc, i);
1584 
1585  if (ret_attr->atttypid != sql_attr->atttypid)
1586  return false;
1587  }
1588 
1589  /* OK, the two tupdescs are compatible for our purposes */
1590  return true;
1591 }
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209

References ereport, errcode(), errdetail(), errmsg(), ERROR, i, TupleDescData::natts, and TupleDescAttr.

Referenced by crosstab().

◆ connectby()

static Tuplestorestate * connectby ( char *  relname,
char *  key_fld,
char *  parent_key_fld,
char *  orderby_fld,
char *  branch_delim,
char *  start_with,
int  max_depth,
bool  show_branch,
bool  show_serial,
MemoryContext  per_query_ctx,
bool  randomAccess,
AttInMetadata attinmeta 
)
static

Definition at line 1149 of file tablefunc.c.

1161 {
1162  Tuplestorestate *tupstore = NULL;
1163  int ret;
1164  MemoryContext oldcontext;
1165 
1166  int serial = 1;
1167 
1168  /* Connect to SPI manager */
1169  if ((ret = SPI_connect()) < 0)
1170  /* internal error */
1171  elog(ERROR, "connectby: SPI_connect returned %d", ret);
1172 
1173  /* switch to longer term context to create the tuple store */
1174  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1175 
1176  /* initialize our tuplestore */
1177  tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
1178 
1179  MemoryContextSwitchTo(oldcontext);
1180 
1181  /* now go get the whole tree */
1183  parent_key_fld,
1184  relname,
1185  orderby_fld,
1186  branch_delim,
1187  start_with,
1188  start_with, /* current_branch */
1189  0, /* initial level is 0 */
1190  &serial, /* initial serial is 1 */
1191  max_depth,
1192  show_branch,
1193  show_serial,
1194  per_query_ctx,
1195  attinmeta,
1196  tupstore);
1197 
1198  SPI_finish();
1199 
1200  return tupstore;
1201 }
int work_mem
Definition: globals.c:125
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
int SPI_connect(void)
Definition: spi.c:95
int SPI_finish(void)
Definition: spi.c:183
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318

References build_tuplestore_recursively(), elog(), ERROR, MemoryContextSwitchTo(), relname, SPI_connect(), SPI_finish(), tuplestore_begin_heap(), and work_mem.

Referenced by connectby_text(), and connectby_text_serial().

◆ connectby_text()

Datum connectby_text ( PG_FUNCTION_ARGS  )

Definition at line 989 of file tablefunc.c.

990 {
992  char *key_fld = text_to_cstring(PG_GETARG_TEXT_PP(1));
993  char *parent_key_fld = text_to_cstring(PG_GETARG_TEXT_PP(2));
994  char *start_with = text_to_cstring(PG_GETARG_TEXT_PP(3));
995  int max_depth = PG_GETARG_INT32(4);
996  char *branch_delim = NULL;
997  bool show_branch = false;
998  bool show_serial = false;
999  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1000  TupleDesc tupdesc;
1001  AttInMetadata *attinmeta;
1002  MemoryContext per_query_ctx;
1003  MemoryContext oldcontext;
1004 
1005  /* check to see if caller supports us returning a tuplestore */
1006  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1007  ereport(ERROR,
1008  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1009  errmsg("set-valued function called in context that cannot accept a set")));
1010  if (!(rsinfo->allowedModes & SFRM_Materialize) ||
1011  rsinfo->expectedDesc == NULL)
1012  ereport(ERROR,
1013  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1014  errmsg("materialize mode required, but it is not allowed in this context")));
1015 
1016  if (fcinfo->nargs == 6)
1017  {
1018  branch_delim = text_to_cstring(PG_GETARG_TEXT_PP(5));
1019  show_branch = true;
1020  }
1021  else
1022  /* default is no show, tilde for the delimiter */
1023  branch_delim = pstrdup("~");
1024 
1025  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1026  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1027 
1028  /* get the requested return tuple description */
1029  tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1030 
1031  /* does it meet our needs */
1032  validateConnectbyTupleDesc(tupdesc, show_branch, show_serial);
1033 
1034  /* OK, use it then */
1035  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1036 
1037  /* OK, go to work */
1038  rsinfo->returnMode = SFRM_Materialize;
1039  rsinfo->setResult = connectby(relname,
1040  key_fld,
1041  parent_key_fld,
1042  NULL,
1043  branch_delim,
1044  start_with,
1045  max_depth,
1046  show_branch,
1047  show_serial,
1048  per_query_ctx,
1050  attinmeta);
1051  rsinfo->setDesc = tupdesc;
1052 
1053  MemoryContextSwitchTo(oldcontext);
1054 
1055  /*
1056  * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1057  * tuples are in our tuplestore and passed back through rsinfo->setResult.
1058  * rsinfo->setDesc is set to the tuple description that we actually used
1059  * to build our tuples with, so the caller can verify we did what it was
1060  * expecting.
1061  */
1062  return (Datum) 0;
1063 }
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2087
@ SFRM_Materialize_Random
Definition: execnodes.h:312
@ SFRM_Materialize
Definition: execnodes.h:311
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
uintptr_t Datum
Definition: postgres.h:64
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:256
SetFunctionReturnMode returnMode
Definition: execnodes.h:330
ExprContext * econtext
Definition: execnodes.h:326
TupleDesc setDesc
Definition: execnodes.h:334
Tuplestorestate * setResult
Definition: execnodes.h:333
TupleDesc expectedDesc
Definition: execnodes.h:327
int allowedModes
Definition: execnodes.h:328
static void validateConnectbyTupleDesc(TupleDesc td, bool show_branch, bool show_serial)
Definition: tablefunc.c:1423
static Tuplestorestate * connectby(char *relname, char *key_fld, char *parent_key_fld, char *orderby_fld, char *branch_delim, char *start_with, int max_depth, bool show_branch, bool show_serial, MemoryContext per_query_ctx, bool randomAccess, AttInMetadata *attinmeta)
Definition: tablefunc.c:1149
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:111
char * text_to_cstring(const text *t)
Definition: varlena.c:215

References ReturnSetInfo::allowedModes, connectby(), CreateTupleDescCopy(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, ereport, errcode(), errmsg(), ERROR, ReturnSetInfo::expectedDesc, if(), IsA, MemoryContextSwitchTo(), PG_GETARG_INT32, PG_GETARG_TEXT_PP, pstrdup(), relname, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Random, text_to_cstring(), TupleDescGetAttInMetadata(), and validateConnectbyTupleDesc().

◆ connectby_text_serial()

Datum connectby_text_serial ( PG_FUNCTION_ARGS  )

Definition at line 1067 of file tablefunc.c.

1068 {
1070  char *key_fld = text_to_cstring(PG_GETARG_TEXT_PP(1));
1071  char *parent_key_fld = text_to_cstring(PG_GETARG_TEXT_PP(2));
1072  char *orderby_fld = text_to_cstring(PG_GETARG_TEXT_PP(3));
1073  char *start_with = text_to_cstring(PG_GETARG_TEXT_PP(4));
1074  int max_depth = PG_GETARG_INT32(5);
1075  char *branch_delim = NULL;
1076  bool show_branch = false;
1077  bool show_serial = true;
1078  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1079  TupleDesc tupdesc;
1080  AttInMetadata *attinmeta;
1081  MemoryContext per_query_ctx;
1082  MemoryContext oldcontext;
1083 
1084  /* check to see if caller supports us returning a tuplestore */
1085  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1086  ereport(ERROR,
1087  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1088  errmsg("set-valued function called in context that cannot accept a set")));
1089  if (!(rsinfo->allowedModes & SFRM_Materialize) ||
1090  rsinfo->expectedDesc == NULL)
1091  ereport(ERROR,
1092  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1093  errmsg("materialize mode required, but it is not allowed in this context")));
1094 
1095  if (fcinfo->nargs == 7)
1096  {
1097  branch_delim = text_to_cstring(PG_GETARG_TEXT_PP(6));
1098  show_branch = true;
1099  }
1100  else
1101  /* default is no show, tilde for the delimiter */
1102  branch_delim = pstrdup("~");
1103 
1104  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1105  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1106 
1107  /* get the requested return tuple description */
1108  tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1109 
1110  /* does it meet our needs */
1111  validateConnectbyTupleDesc(tupdesc, show_branch, show_serial);
1112 
1113  /* OK, use it then */
1114  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1115 
1116  /* OK, go to work */
1117  rsinfo->returnMode = SFRM_Materialize;
1118  rsinfo->setResult = connectby(relname,
1119  key_fld,
1120  parent_key_fld,
1121  orderby_fld,
1122  branch_delim,
1123  start_with,
1124  max_depth,
1125  show_branch,
1126  show_serial,
1127  per_query_ctx,
1129  attinmeta);
1130  rsinfo->setDesc = tupdesc;
1131 
1132  MemoryContextSwitchTo(oldcontext);
1133 
1134  /*
1135  * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1136  * tuples are in our tuplestore and passed back through rsinfo->setResult.
1137  * rsinfo->setDesc is set to the tuple description that we actually used
1138  * to build our tuples with, so the caller can verify we did what it was
1139  * expecting.
1140  */
1141  return (Datum) 0;
1142 }

References ReturnSetInfo::allowedModes, connectby(), CreateTupleDescCopy(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, ereport, errcode(), errmsg(), ERROR, ReturnSetInfo::expectedDesc, if(), IsA, MemoryContextSwitchTo(), PG_GETARG_INT32, PG_GETARG_TEXT_PP, pstrdup(), relname, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Random, text_to_cstring(), TupleDescGetAttInMetadata(), and validateConnectbyTupleDesc().

◆ crosstab()

Datum crosstab ( PG_FUNCTION_ARGS  )

Definition at line 355 of file tablefunc.c.

356 {
357  char *sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
358  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
359  Tuplestorestate *tupstore;
360  TupleDesc tupdesc;
361  uint64 call_cntr;
362  uint64 max_calls;
363  AttInMetadata *attinmeta;
364  SPITupleTable *spi_tuptable;
365  TupleDesc spi_tupdesc;
366  bool firstpass;
367  char *lastrowid;
368  int i;
369  int num_categories;
370  MemoryContext per_query_ctx;
371  MemoryContext oldcontext;
372  int ret;
373  uint64 proc;
374 
375  /* check to see if caller supports us returning a tuplestore */
376  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
377  ereport(ERROR,
378  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
379  errmsg("set-valued function called in context that cannot accept a set")));
380  if (!(rsinfo->allowedModes & SFRM_Materialize))
381  ereport(ERROR,
382  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
383  errmsg("materialize mode required, but it is not allowed in this context")));
384 
385  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
386 
387  /* Connect to SPI manager */
388  if ((ret = SPI_connect()) < 0)
389  /* internal error */
390  elog(ERROR, "crosstab: SPI_connect returned %d", ret);
391 
392  /* Retrieve the desired rows */
393  ret = SPI_execute(sql, true, 0);
394  proc = SPI_processed;
395 
396  /* If no qualifying tuples, fall out early */
397  if (ret != SPI_OK_SELECT || proc == 0)
398  {
399  SPI_finish();
400  rsinfo->isDone = ExprEndResult;
401  PG_RETURN_NULL();
402  }
403 
404  spi_tuptable = SPI_tuptable;
405  spi_tupdesc = spi_tuptable->tupdesc;
406 
407  /*----------
408  * The provided SQL query must always return three columns.
409  *
410  * 1. rowname
411  * the label or identifier for each row in the final result
412  * 2. category
413  * the label or identifier for each column in the final result
414  * 3. values
415  * the value for each column in the final result
416  *----------
417  */
418  if (spi_tupdesc->natts != 3)
419  ereport(ERROR,
420  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
421  errmsg("invalid source data SQL statement"),
422  errdetail("The provided SQL must return 3 "
423  "columns: rowid, category, and values.")));
424 
425  /* get a tuple descriptor for our result type */
426  switch (get_call_result_type(fcinfo, NULL, &tupdesc))
427  {
428  case TYPEFUNC_COMPOSITE:
429  /* success */
430  break;
431  case TYPEFUNC_RECORD:
432  /* failed to determine actual type of RECORD */
433  ereport(ERROR,
434  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
435  errmsg("function returning record called in context "
436  "that cannot accept type record")));
437  break;
438  default:
439  /* result type isn't composite */
440  ereport(ERROR,
441  (errcode(ERRCODE_DATATYPE_MISMATCH),
442  errmsg("return type must be a row type")));
443  break;
444  }
445 
446  /*
447  * Check that return tupdesc is compatible with the data we got from SPI,
448  * at least based on number and type of attributes
449  */
450  if (!compatCrosstabTupleDescs(tupdesc, spi_tupdesc))
451  ereport(ERROR,
452  (errcode(ERRCODE_SYNTAX_ERROR),
453  errmsg("return and sql tuple descriptions are " \
454  "incompatible")));
455 
456  /*
457  * switch to long-lived memory context
458  */
459  oldcontext = MemoryContextSwitchTo(per_query_ctx);
460 
461  /* make sure we have a persistent copy of the result tupdesc */
462  tupdesc = CreateTupleDescCopy(tupdesc);
463 
464  /* initialize our tuplestore in long-lived context */
465  tupstore =
467  false, work_mem);
468 
469  MemoryContextSwitchTo(oldcontext);
470 
471  /*
472  * Generate attribute metadata needed later to produce tuples from raw C
473  * strings
474  */
475  attinmeta = TupleDescGetAttInMetadata(tupdesc);
476 
477  /* total number of tuples to be examined */
478  max_calls = proc;
479 
480  /* the return tuple always must have 1 rowid + num_categories columns */
481  num_categories = tupdesc->natts - 1;
482 
483  firstpass = true;
484  lastrowid = NULL;
485 
486  for (call_cntr = 0; call_cntr < max_calls; call_cntr++)
487  {
488  bool skip_tuple = false;
489  char **values;
490 
491  /* allocate and zero space */
492  values = (char **) palloc0((1 + num_categories) * sizeof(char *));
493 
494  /*
495  * now loop through the sql results and assign each value in sequence
496  * to the next category
497  */
498  for (i = 0; i < num_categories; i++)
499  {
500  HeapTuple spi_tuple;
501  char *rowid;
502 
503  /* see if we've gone too far already */
504  if (call_cntr >= max_calls)
505  break;
506 
507  /* get the next sql result tuple */
508  spi_tuple = spi_tuptable->vals[call_cntr];
509 
510  /* get the rowid from the current sql result tuple */
511  rowid = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
512 
513  /*
514  * If this is the first pass through the values for this rowid,
515  * set the first column to rowid
516  */
517  if (i == 0)
518  {
519  xpstrdup(values[0], rowid);
520 
521  /*
522  * Check to see if the rowid is the same as that of the last
523  * tuple sent -- if so, skip this tuple entirely
524  */
525  if (!firstpass && xstreq(lastrowid, rowid))
526  {
527  xpfree(rowid);
528  skip_tuple = true;
529  break;
530  }
531  }
532 
533  /*
534  * If rowid hasn't changed on us, continue building the output
535  * tuple.
536  */
537  if (xstreq(rowid, values[0]))
538  {
539  /*
540  * Get the next category item value, which is always attribute
541  * number three.
542  *
543  * Be careful to assign the value to the array index based on
544  * which category we are presently processing.
545  */
546  values[1 + i] = SPI_getvalue(spi_tuple, spi_tupdesc, 3);
547 
548  /*
549  * increment the counter since we consume a row for each
550  * category, but not for last pass because the outer loop will
551  * do that for us
552  */
553  if (i < (num_categories - 1))
554  call_cntr++;
555  xpfree(rowid);
556  }
557  else
558  {
559  /*
560  * We'll fill in NULLs for the missing values, but we need to
561  * decrement the counter since this sql result row doesn't
562  * belong to the current output tuple.
563  */
564  call_cntr--;
565  xpfree(rowid);
566  break;
567  }
568  }
569 
570  if (!skip_tuple)
571  {
572  HeapTuple tuple;
573 
574  /* build the tuple and store it */
575  tuple = BuildTupleFromCStrings(attinmeta, values);
576  tuplestore_puttuple(tupstore, tuple);
577  heap_freetuple(tuple);
578  }
579 
580  /* Remember current rowid */
581  xpfree(lastrowid);
582  xpstrdup(lastrowid, values[0]);
583  firstpass = false;
584 
585  /* Clean up */
586  for (i = 0; i < num_categories + 1; i++)
587  if (values[i] != NULL)
588  pfree(values[i]);
589  pfree(values);
590  }
591 
592  /* let the caller know we're sending back a tuplestore */
593  rsinfo->returnMode = SFRM_Materialize;
594  rsinfo->setResult = tupstore;
595  rsinfo->setDesc = tupdesc;
596 
597  /* release SPI related resources (and return to caller's context) */
598  SPI_finish();
599 
600  return (Datum) 0;
601 }
@ ExprEndResult
Definition: execnodes.h:299
#define PG_RETURN_NULL()
Definition: fmgr.h:345
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:276
@ TYPEFUNC_COMPOSITE
Definition: funcapi.h:149
@ TYPEFUNC_RECORD
Definition: funcapi.h:151
void pfree(void *pointer)
Definition: mcxt.c:1456
void * palloc0(Size size)
Definition: mcxt.c:1257
ExprDoneCond isDone
Definition: execnodes.h:331
#define xpstrdup(tgtvar_, srcvar_)
Definition: tablefunc.c:103
#define xstreq(tgtvar_, srcvar_)
Definition: tablefunc.c:111
static bool compatCrosstabTupleDescs(TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
Definition: tablefunc.c:1553

References ReturnSetInfo::allowedModes, BuildTupleFromCStrings(), compatCrosstabTupleDescs(), CreateTupleDescCopy(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog(), ereport, errcode(), errdetail(), errmsg(), ERROR, ExprEndResult, get_call_result_type(), heap_freetuple(), i, if(), IsA, ReturnSetInfo::isDone, MemoryContextSwitchTo(), palloc0(), pfree(), PG_GETARG_TEXT_PP, PG_RETURN_NULL, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Random, SPI_connect(), SPI_execute(), SPI_finish(), SPI_getvalue(), SPI_OK_SELECT, SPI_processed, SPI_tuptable, text_to_cstring(), SPITupleTable::tupdesc, TupleDescGetAttInMetadata(), tuplestore_begin_heap(), tuplestore_puttuple(), TYPEFUNC_COMPOSITE, TYPEFUNC_RECORD, values, work_mem, xpfree, xpstrdup, and xstreq.

◆ crosstab_hash()

Datum crosstab_hash ( PG_FUNCTION_ARGS  )

Definition at line 640 of file tablefunc.c.

641 {
642  char *sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
643  char *cats_sql = text_to_cstring(PG_GETARG_TEXT_PP(1));
644  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
645  TupleDesc tupdesc;
646  MemoryContext per_query_ctx;
647  MemoryContext oldcontext;
649 
650  /* check to see if caller supports us returning a tuplestore */
651  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
652  ereport(ERROR,
653  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
654  errmsg("set-valued function called in context that cannot accept a set")));
655  if (!(rsinfo->allowedModes & SFRM_Materialize) ||
656  rsinfo->expectedDesc == NULL)
657  ereport(ERROR,
658  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
659  errmsg("materialize mode required, but it is not allowed in this context")));
660 
661  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
662  oldcontext = MemoryContextSwitchTo(per_query_ctx);
663 
664  /* get the requested return tuple description */
665  tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
666 
667  /*
668  * Check to make sure we have a reasonable tuple descriptor
669  *
670  * Note we will attempt to coerce the values into whatever the return
671  * attribute type is and depend on the "in" function to complain if
672  * needed.
673  */
674  if (tupdesc->natts < 2)
675  ereport(ERROR,
676  (errcode(ERRCODE_SYNTAX_ERROR),
677  errmsg("query-specified return tuple and " \
678  "crosstab function are not compatible")));
679 
680  /* load up the categories hash table */
681  crosstab_hash = load_categories_hash(cats_sql, per_query_ctx);
682 
683  /* let the caller know we're sending back a tuplestore */
684  rsinfo->returnMode = SFRM_Materialize;
685 
686  /* now go build it */
687  rsinfo->setResult = get_crosstab_tuplestore(sql,
689  tupdesc,
691 
692  /*
693  * SFRM_Materialize mode expects us to return a NULL Datum. The actual
694  * tuples are in our tuplestore and passed back through rsinfo->setResult.
695  * rsinfo->setDesc is set to the tuple description that we actually used
696  * to build our tuples with, so the caller can verify we did what it was
697  * expecting.
698  */
699  rsinfo->setDesc = tupdesc;
700  MemoryContextSwitchTo(oldcontext);
701 
702  return (Datum) 0;
703 }
Definition: dynahash.c:220
static Tuplestorestate * get_crosstab_tuplestore(char *sql, HTAB *crosstab_hash, TupleDesc tupdesc, bool randomAccess)
Definition: tablefunc.c:798
Datum crosstab_hash(PG_FUNCTION_ARGS)
Definition: tablefunc.c:640
static HTAB * load_categories_hash(char *cats_sql, MemoryContext per_query_ctx)
Definition: tablefunc.c:709

References ReturnSetInfo::allowedModes, CreateTupleDescCopy(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, ereport, errcode(), errmsg(), ERROR, ReturnSetInfo::expectedDesc, get_crosstab_tuplestore(), if(), IsA, load_categories_hash(), MemoryContextSwitchTo(), PG_GETARG_TEXT_PP, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SFRM_Materialize_Random, and text_to_cstring().

Referenced by get_crosstab_tuplestore(), and load_categories_hash().

◆ get_crosstab_tuplestore()

static Tuplestorestate * get_crosstab_tuplestore ( char *  sql,
HTAB crosstab_hash,
TupleDesc  tupdesc,
bool  randomAccess 
)
static

Definition at line 798 of file tablefunc.c.

802 {
803  Tuplestorestate *tupstore;
804  int num_categories = hash_get_num_entries(crosstab_hash);
805  AttInMetadata *attinmeta = TupleDescGetAttInMetadata(tupdesc);
806  char **values;
807  HeapTuple tuple;
808  int ret;
809  uint64 proc;
810 
811  /* initialize our tuplestore (while still in query context!) */
812  tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
813 
814  /* Connect to SPI manager */
815  if ((ret = SPI_connect()) < 0)
816  /* internal error */
817  elog(ERROR, "get_crosstab_tuplestore: SPI_connect returned %d", ret);
818 
819  /* Now retrieve the crosstab source rows */
820  ret = SPI_execute(sql, true, 0);
821  proc = SPI_processed;
822 
823  /* Check for qualifying tuples */
824  if ((ret == SPI_OK_SELECT) && (proc > 0))
825  {
826  SPITupleTable *spi_tuptable = SPI_tuptable;
827  TupleDesc spi_tupdesc = spi_tuptable->tupdesc;
828  int ncols = spi_tupdesc->natts;
829  char *rowid;
830  char *lastrowid = NULL;
831  bool firstpass = true;
832  uint64 i;
833  int j;
834  int result_ncols;
835 
836  if (num_categories == 0)
837  {
838  /* no qualifying category tuples */
839  ereport(ERROR,
840  (errcode(ERRCODE_SYNTAX_ERROR),
841  errmsg("provided \"categories\" SQL must " \
842  "return 1 column of at least one row")));
843  }
844 
845  /*
846  * The provided SQL query must always return at least three columns:
847  *
848  * 1. rowname the label for each row - column 1 in the final result
849  * 2. category the label for each value-column in the final result 3.
850  * value the values used to populate the value-columns
851  *
852  * If there are more than three columns, the last two are taken as
853  * "category" and "values". The first column is taken as "rowname".
854  * Additional columns (2 thru N-2) are assumed the same for the same
855  * "rowname", and are copied into the result tuple from the first time
856  * we encounter a particular rowname.
857  */
858  if (ncols < 3)
859  ereport(ERROR,
860  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
861  errmsg("invalid source data SQL statement"),
862  errdetail("The provided SQL must return 3 " \
863  " columns; rowid, category, and values.")));
864 
865  result_ncols = (ncols - 2) + num_categories;
866 
867  /* Recheck to make sure we tuple descriptor still looks reasonable */
868  if (tupdesc->natts != result_ncols)
869  ereport(ERROR,
870  (errcode(ERRCODE_SYNTAX_ERROR),
871  errmsg("invalid return type"),
872  errdetail("Query-specified return " \
873  "tuple has %d columns but crosstab " \
874  "returns %d.", tupdesc->natts, result_ncols)));
875 
876  /* allocate space and make sure it's clear */
877  values = (char **) palloc0(result_ncols * sizeof(char *));
878 
879  for (i = 0; i < proc; i++)
880  {
881  HeapTuple spi_tuple;
882  crosstab_cat_desc *catdesc;
883  char *catname;
884 
885  /* get the next sql result tuple */
886  spi_tuple = spi_tuptable->vals[i];
887 
888  /* get the rowid from the current sql result tuple */
889  rowid = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
890 
891  /*
892  * if we're on a new output row, grab the column values up to
893  * column N-2 now
894  */
895  if (firstpass || !xstreq(lastrowid, rowid))
896  {
897  /*
898  * a new row means we need to flush the old one first, unless
899  * we're on the very first row
900  */
901  if (!firstpass)
902  {
903  /* rowid changed, flush the previous output row */
904  tuple = BuildTupleFromCStrings(attinmeta, values);
905 
906  tuplestore_puttuple(tupstore, tuple);
907 
908  for (j = 0; j < result_ncols; j++)
909  xpfree(values[j]);
910  }
911 
912  values[0] = rowid;
913  for (j = 1; j < ncols - 2; j++)
914  values[j] = SPI_getvalue(spi_tuple, spi_tupdesc, j + 1);
915 
916  /* we're no longer on the first pass */
917  firstpass = false;
918  }
919 
920  /* look up the category and fill in the appropriate column */
921  catname = SPI_getvalue(spi_tuple, spi_tupdesc, ncols - 1);
922 
923  if (catname != NULL)
924  {
925  crosstab_HashTableLookup(crosstab_hash, catname, catdesc);
926 
927  if (catdesc)
928  values[catdesc->attidx + ncols - 2] =
929  SPI_getvalue(spi_tuple, spi_tupdesc, ncols);
930  }
931 
932  xpfree(lastrowid);
933  xpstrdup(lastrowid, rowid);
934  }
935 
936  /* flush the last output row */
937  tuple = BuildTupleFromCStrings(attinmeta, values);
938 
939  tuplestore_puttuple(tupstore, tuple);
940  }
941 
942  if (SPI_finish() != SPI_OK_FINISH)
943  /* internal error */
944  elog(ERROR, "get_crosstab_tuplestore: SPI_finish() failed");
945 
946  return tupstore;
947 }
long hash_get_num_entries(HTAB *hashp)
Definition: dynahash.c:1377
int j
Definition: isn.c:74
#define SPI_OK_FINISH
Definition: spi.h:83
#define crosstab_HashTableLookup(HASHTAB, CATNAME, CATDESC)
Definition: tablefunc.c:128

References crosstab_cat_desc::attidx, BuildTupleFromCStrings(), crosstab_hash(), crosstab_HashTableLookup, elog(), ereport, errcode(), errdetail(), errmsg(), ERROR, hash_get_num_entries(), i, j, TupleDescData::natts, palloc0(), SPI_connect(), SPI_execute(), SPI_finish(), SPI_getvalue(), SPI_OK_FINISH, SPI_OK_SELECT, SPI_processed, SPI_tuptable, SPITupleTable::tupdesc, TupleDescGetAttInMetadata(), tuplestore_begin_heap(), tuplestore_puttuple(), SPITupleTable::vals, values, work_mem, xpfree, xpstrdup, and xstreq.

Referenced by crosstab_hash().

◆ get_normal_pair()

static void get_normal_pair ( float8 x1,
float8 x2 
)
static

Definition at line 284 of file tablefunc.c.

285 {
286  float8 u1,
287  u2,
288  v1,
289  v2,
290  s;
291 
292  do
293  {
296 
297  v1 = (2.0 * u1) - 1.0;
298  v2 = (2.0 * u2) - 1.0;
299 
300  s = v1 * v1 + v2 * v2;
301  } while (s >= 1.0);
302 
303  if (s == 0)
304  {
305  *x1 = 0;
306  *x2 = 0;
307  }
308  else
309  {
310  s = sqrt((-2.0 * log(s)) / s);
311  *x1 = v1 * s;
312  *x2 = v2 * s;
313  }
314 }
double float8
Definition: c.h:614
double pg_prng_double(pg_prng_state *state)
Definition: pg_prng.c:232
pg_prng_state pg_global_prng_state
Definition: pg_prng.c:34

References pg_global_prng_state, and pg_prng_double().

Referenced by normal_rand().

◆ load_categories_hash()

static HTAB * load_categories_hash ( char *  cats_sql,
MemoryContext  per_query_ctx 
)
static

Definition at line 709 of file tablefunc.c.

710 {
712  HASHCTL ctl;
713  int ret;
714  uint64 proc;
715  MemoryContext SPIcontext;
716 
717  /* initialize the category hash table */
718  ctl.keysize = MAX_CATNAME_LEN;
719  ctl.entrysize = sizeof(crosstab_HashEnt);
720  ctl.hcxt = per_query_ctx;
721 
722  /*
723  * use INIT_CATS, defined above as a guess of how many hash table entries
724  * to create, initially
725  */
726  crosstab_hash = hash_create("crosstab hash",
727  INIT_CATS,
728  &ctl,
730 
731  /* Connect to SPI manager */
732  if ((ret = SPI_connect()) < 0)
733  /* internal error */
734  elog(ERROR, "load_categories_hash: SPI_connect returned %d", ret);
735 
736  /* Retrieve the category name rows */
737  ret = SPI_execute(cats_sql, true, 0);
738  proc = SPI_processed;
739 
740  /* Check for qualifying tuples */
741  if ((ret == SPI_OK_SELECT) && (proc > 0))
742  {
743  SPITupleTable *spi_tuptable = SPI_tuptable;
744  TupleDesc spi_tupdesc = spi_tuptable->tupdesc;
745  uint64 i;
746 
747  /*
748  * The provided categories SQL query must always return one column:
749  * category - the label or identifier for each column
750  */
751  if (spi_tupdesc->natts != 1)
752  ereport(ERROR,
753  (errcode(ERRCODE_SYNTAX_ERROR),
754  errmsg("provided \"categories\" SQL must " \
755  "return 1 column of at least one row")));
756 
757  for (i = 0; i < proc; i++)
758  {
759  crosstab_cat_desc *catdesc;
760  char *catname;
761  HeapTuple spi_tuple;
762 
763  /* get the next sql result tuple */
764  spi_tuple = spi_tuptable->vals[i];
765 
766  /* get the category from the current sql result tuple */
767  catname = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
768  if (catname == NULL)
769  ereport(ERROR,
770  (errcode(ERRCODE_SYNTAX_ERROR),
771  errmsg("provided \"categories\" SQL must " \
772  "not return NULL values")));
773 
774  SPIcontext = MemoryContextSwitchTo(per_query_ctx);
775 
776  catdesc = (crosstab_cat_desc *) palloc(sizeof(crosstab_cat_desc));
777  catdesc->catname = catname;
778  catdesc->attidx = i;
779 
780  /* Add the proc description block to the hashtable */
782 
783  MemoryContextSwitchTo(SPIcontext);
784  }
785  }
786 
787  if (SPI_finish() != SPI_OK_FINISH)
788  /* internal error */
789  elog(ERROR, "load_categories_hash: SPI_finish() failed");
790 
791  return crosstab_hash;
792 }
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:350
#define HASH_STRINGS
Definition: hsearch.h:96
#define HASH_CONTEXT
Definition: hsearch.h:102
#define HASH_ELEM
Definition: hsearch.h:95
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
MemoryContext hcxt
Definition: hsearch.h:86
#define crosstab_HashTableInsert(HASHTAB, CATDESC)
Definition: tablefunc.c:142
#define INIT_CATS
Definition: tablefunc.c:126
struct crosstab_hashent crosstab_HashEnt

References crosstab_cat_desc::attidx, crosstab_cat_desc::catname, crosstab_hash(), crosstab_HashTableInsert, elog(), HASHCTL::entrysize, ereport, errcode(), errmsg(), ERROR, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_STRINGS, HASHCTL::hcxt, i, INIT_CATS, HASHCTL::keysize, MAX_CATNAME_LEN, MemoryContextSwitchTo(), TupleDescData::natts, palloc(), SPI_connect(), SPI_execute(), SPI_finish(), SPI_getvalue(), SPI_OK_FINISH, SPI_OK_SELECT, SPI_processed, SPI_tuptable, SPITupleTable::tupdesc, and SPITupleTable::vals.

Referenced by crosstab_hash().

◆ normal_rand()

Datum normal_rand ( PG_FUNCTION_ARGS  )

Definition at line 173 of file tablefunc.c.

174 {
175  FuncCallContext *funcctx;
176  uint64 call_cntr;
177  uint64 max_calls;
178  normal_rand_fctx *fctx;
179  float8 mean;
180  float8 stddev;
181  float8 carry_val;
182  bool use_carry;
183  MemoryContext oldcontext;
184 
185  /* stuff done only on the first call of the function */
186  if (SRF_IS_FIRSTCALL())
187  {
188  int32 num_tuples;
189 
190  /* create a function context for cross-call persistence */
191  funcctx = SRF_FIRSTCALL_INIT();
192 
193  /*
194  * switch to memory context appropriate for multiple function calls
195  */
196  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
197 
198  /* total number of tuples to be returned */
199  num_tuples = PG_GETARG_INT32(0);
200  if (num_tuples < 0)
201  ereport(ERROR,
202  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
203  errmsg("number of rows cannot be negative")));
204  funcctx->max_calls = num_tuples;
205 
206  /* allocate memory for user context */
207  fctx = (normal_rand_fctx *) palloc(sizeof(normal_rand_fctx));
208 
209  /*
210  * Use fctx to keep track of upper and lower bounds from call to call.
211  * It will also be used to carry over the spare value we get from the
212  * Box-Muller algorithm so that we only actually calculate a new value
213  * every other call.
214  */
215  fctx->mean = PG_GETARG_FLOAT8(1);
216  fctx->stddev = PG_GETARG_FLOAT8(2);
217  fctx->carry_val = 0;
218  fctx->use_carry = false;
219 
220  funcctx->user_fctx = fctx;
221 
222  MemoryContextSwitchTo(oldcontext);
223  }
224 
225  /* stuff done on every call of the function */
226  funcctx = SRF_PERCALL_SETUP();
227 
228  call_cntr = funcctx->call_cntr;
229  max_calls = funcctx->max_calls;
230  fctx = funcctx->user_fctx;
231  mean = fctx->mean;
232  stddev = fctx->stddev;
233  carry_val = fctx->carry_val;
234  use_carry = fctx->use_carry;
235 
236  if (call_cntr < max_calls) /* do when there is more left to send */
237  {
238  float8 result;
239 
240  if (use_carry)
241  {
242  /*
243  * reset use_carry and use second value obtained on last pass
244  */
245  fctx->use_carry = false;
246  result = carry_val;
247  }
248  else
249  {
250  float8 normval_1;
251  float8 normval_2;
252 
253  /* Get the next two normal values */
254  get_normal_pair(&normval_1, &normval_2);
255 
256  /* use the first */
257  result = mean + (stddev * normval_1);
258 
259  /* and save the second */
260  fctx->carry_val = mean + (stddev * normval_2);
261  fctx->use_carry = true;
262  }
263 
264  /* send the result */
265  SRF_RETURN_NEXT(funcctx, Float8GetDatum(result));
266  }
267  else
268  /* do when there is no more left */
269  SRF_RETURN_DONE(funcctx);
270 }
Datum Float8GetDatum(float8 X)
Definition: fmgr.c:1787
#define PG_GETARG_FLOAT8(n)
Definition: fmgr.h:282
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:304
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:308
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:310
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:306
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:328
void * user_fctx
Definition: funcapi.h:82
uint64 max_calls
Definition: funcapi.h:74
uint64 call_cntr
Definition: funcapi.h:65
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
float8 carry_val
Definition: tablefunc.c:90
static void get_normal_pair(float8 *x1, float8 *x2)
Definition: tablefunc.c:284

References FuncCallContext::call_cntr, normal_rand_fctx::carry_val, ereport, errcode(), errmsg(), ERROR, Float8GetDatum(), get_normal_pair(), FuncCallContext::max_calls, normal_rand_fctx::mean, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, palloc(), PG_GETARG_FLOAT8, PG_GETARG_INT32, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, normal_rand_fctx::stddev, normal_rand_fctx::use_carry, and FuncCallContext::user_fctx.

◆ PG_FUNCTION_INFO_V1() [1/5]

PG_FUNCTION_INFO_V1 ( connectby_text  )

◆ PG_FUNCTION_INFO_V1() [2/5]

PG_FUNCTION_INFO_V1 ( connectby_text_serial  )

◆ PG_FUNCTION_INFO_V1() [3/5]

PG_FUNCTION_INFO_V1 ( crosstab  )

◆ PG_FUNCTION_INFO_V1() [4/5]

PG_FUNCTION_INFO_V1 ( crosstab_hash  )

◆ PG_FUNCTION_INFO_V1() [5/5]

PG_FUNCTION_INFO_V1 ( normal_rand  )

◆ validateConnectbyTupleDesc()

static void validateConnectbyTupleDesc ( TupleDesc  td,
bool  show_branch,
bool  show_serial 
)
static

Definition at line 1423 of file tablefunc.c.

1424 {
1425  int serial_column = 0;
1426 
1427  if (show_serial)
1428  serial_column = 1;
1429 
1430  /* are there the correct number of columns */
1431  if (show_branch)
1432  {
1433  if (td->natts != (CONNECTBY_NCOLS + serial_column))
1434  ereport(ERROR,
1435  (errcode(ERRCODE_DATATYPE_MISMATCH),
1436  errmsg("invalid return type"),
1437  errdetail("Query-specified return tuple has " \
1438  "wrong number of columns.")));
1439  }
1440  else
1441  {
1442  if (td->natts != CONNECTBY_NCOLS_NOBRANCH + serial_column)
1443  ereport(ERROR,
1444  (errcode(ERRCODE_DATATYPE_MISMATCH),
1445  errmsg("invalid return type"),
1446  errdetail("Query-specified return tuple has " \
1447  "wrong number of columns.")));
1448  }
1449 
1450  /* check that the types of the first two columns match */
1451  if (TupleDescAttr(td, 0)->atttypid != TupleDescAttr(td, 1)->atttypid)
1452  ereport(ERROR,
1453  (errcode(ERRCODE_DATATYPE_MISMATCH),
1454  errmsg("invalid return type"),
1455  errdetail("First two columns must be the same type.")));
1456 
1457  /* check that the type of the third column is INT4 */
1458  if (TupleDescAttr(td, 2)->atttypid != INT4OID)
1459  ereport(ERROR,
1460  (errcode(ERRCODE_DATATYPE_MISMATCH),
1461  errmsg("invalid return type"),
1462  errdetail("Third column must be type %s.",
1463  format_type_be(INT4OID))));
1464 
1465  /* check that the type of the fourth column is TEXT if applicable */
1466  if (show_branch && TupleDescAttr(td, 3)->atttypid != TEXTOID)
1467  ereport(ERROR,
1468  (errcode(ERRCODE_DATATYPE_MISMATCH),
1469  errmsg("invalid return type"),
1470  errdetail("Fourth column must be type %s.",
1471  format_type_be(TEXTOID))));
1472 
1473  /* check that the type of the fifth column is INT4 */
1474  if (show_branch && show_serial &&
1475  TupleDescAttr(td, 4)->atttypid != INT4OID)
1476  ereport(ERROR,
1477  (errcode(ERRCODE_DATATYPE_MISMATCH),
1478  errmsg("query-specified return tuple not valid for Connectby: "
1479  "fifth column must be type %s",
1480  format_type_be(INT4OID))));
1481 
1482  /* check that the type of the fourth column is INT4 */
1483  if (!show_branch && show_serial &&
1484  TupleDescAttr(td, 3)->atttypid != INT4OID)
1485  ereport(ERROR,
1486  (errcode(ERRCODE_DATATYPE_MISMATCH),
1487  errmsg("query-specified return tuple not valid for Connectby: "
1488  "fourth column must be type %s",
1489  format_type_be(INT4OID))));
1490 
1491  /* OK, the tupdesc is valid for our purposes */
1492 }
char * format_type_be(Oid type_oid)
Definition: format_type.c:339

References CONNECTBY_NCOLS, CONNECTBY_NCOLS_NOBRANCH, ereport, errcode(), errdetail(), errmsg(), ERROR, format_type_be(), TupleDescData::natts, and TupleDescAttr.

Referenced by connectby_text(), and connectby_text_serial().

Variable Documentation

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 47 of file tablefunc.c.