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 "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, MemoryContext per_query_ctx, bool randomAccess)
 
static void validateConnectbyTupleDesc (TupleDesc tupdesc, bool show_branch, bool show_serial)
 
static bool compatCrosstabTupleDescs (TupleDesc tupdesc1, TupleDesc tupdesc2)
 
static void compatConnectbyTupleDescs (TupleDesc tupdesc1, TupleDesc tupdesc2)
 
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 980 of file tablefunc.c.

Referenced by build_tuplestore_recursively(), and validateConnectbyTupleDesc().

◆ CONNECTBY_NCOLS_NOBRANCH

#define CONNECTBY_NCOLS_NOBRANCH   3

Definition at line 981 of file tablefunc.c.

Referenced by build_tuplestore_recursively(), and validateConnectbyTupleDesc().

◆ 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 MAX_CATNAME_LEN
Definition: tablefunc.c:125
int errcode(int sqlerrcode)
Definition: elog.c:608
#define MemSet(start, val, len)
Definition: c.h:962
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
#define ERROR
Definition: elog.h:43
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:31

Definition at line 142 of file tablefunc.c.

Referenced by load_categories_hash().

◆ 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)
#define MAX_CATNAME_LEN
Definition: tablefunc.c:125
#define MemSet(start, val, len)
Definition: c.h:962
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906

Definition at line 128 of file tablefunc.c.

Referenced by get_crosstab_tuplestore().

◆ INIT_CATS

#define INIT_CATS   64

Definition at line 126 of file tablefunc.c.

Referenced by load_categories_hash().

◆ INT32_STRLEN

#define INT32_STRLEN   12

Definition at line 116 of file tablefunc.c.

Referenced by build_tuplestore_recursively().

◆ MAX_CATNAME_LEN

#define MAX_CATNAME_LEN   NAMEDATALEN

Definition at line 125 of file tablefunc.c.

Referenced by load_categories_hash().

◆ xpfree

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

Definition at line 94 of file tablefunc.c.

Referenced by build_tuplestore_recursively(), crosstab(), and get_crosstab_tuplestore().

◆ 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:1186

Definition at line 103 of file tablefunc.c.

Referenced by crosstab(), and get_crosstab_tuplestore().

◆ 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.

Referenced by crosstab(), and get_crosstab_tuplestore().

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 1201 of file tablefunc.c.

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(), 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().

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

◆ compatConnectbyTupleDescs()

static void compatConnectbyTupleDescs ( TupleDesc  tupdesc1,
TupleDesc  tupdesc2 
)
static

Definition at line 1495 of file tablefunc.c.

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

Referenced by build_tuplestore_recursively().

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

◆ compatCrosstabTupleDescs()

static bool compatCrosstabTupleDescs ( TupleDesc  tupdesc1,
TupleDesc  tupdesc2 
)
static

Definition at line 1550 of file tablefunc.c.

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

Referenced by crosstab().

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

◆ 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 1146 of file tablefunc.c.

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

Referenced by connectby_text(), and connectby_text_serial().

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

◆ connectby_text()

Datum connectby_text ( PG_FUNCTION_ARGS  )

Definition at line 984 of file tablefunc.c.

References ReturnSetInfo::allowedModes, connectby(), connectby_text_serial(), CreateTupleDescCopy(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, ereport, errcode(), errmsg(), ERROR, ReturnSetInfo::expectedDesc, IsA, MemoryContextSwitchTo(), PG_FUNCTION_INFO_V1(), 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().

Referenced by get_crosstab_tuplestore().

985 {
987  char *key_fld = text_to_cstring(PG_GETARG_TEXT_PP(1));
988  char *parent_key_fld = text_to_cstring(PG_GETARG_TEXT_PP(2));
989  char *start_with = text_to_cstring(PG_GETARG_TEXT_PP(3));
990  int max_depth = PG_GETARG_INT32(4);
991  char *branch_delim = NULL;
992  bool show_branch = false;
993  bool show_serial = false;
994  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
995  TupleDesc tupdesc;
996  AttInMetadata *attinmeta;
997  MemoryContext per_query_ctx;
998  MemoryContext oldcontext;
999 
1000  /* check to see if caller supports us returning a tuplestore */
1001  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1002  ereport(ERROR,
1003  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1004  errmsg("set-valued function called in context that cannot accept a set")));
1005  if (!(rsinfo->allowedModes & SFRM_Materialize) ||
1006  rsinfo->expectedDesc == NULL)
1007  ereport(ERROR,
1008  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1009  errmsg("materialize mode required, but it is not " \
1010  "allowed in this context")));
1011 
1012  if (fcinfo->nargs == 6)
1013  {
1014  branch_delim = text_to_cstring(PG_GETARG_TEXT_PP(5));
1015  show_branch = true;
1016  }
1017  else
1018  /* default is no show, tilde for the delimiter */
1019  branch_delim = pstrdup("~");
1020 
1021  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1022  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1023 
1024  /* get the requested return tuple description */
1025  tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1026 
1027  /* does it meet our needs */
1028  validateConnectbyTupleDesc(tupdesc, show_branch, show_serial);
1029 
1030  /* OK, use it then */
1031  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1032 
1033  /* OK, go to work */
1034  rsinfo->returnMode = SFRM_Materialize;
1035  rsinfo->setResult = connectby(relname,
1036  key_fld,
1037  parent_key_fld,
1038  NULL,
1039  branch_delim,
1040  start_with,
1041  max_depth,
1042  show_branch,
1043  show_serial,
1044  per_query_ctx,
1046  attinmeta);
1047  rsinfo->setDesc = tupdesc;
1048 
1049  MemoryContextSwitchTo(oldcontext);
1050 
1051  /*
1052  * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1053  * tuples are in our tuplestore and passed back through rsinfo->setResult.
1054  * rsinfo->setDesc is set to the tuple description that we actually used
1055  * to build our tuples with, so the caller can verify we did what it was
1056  * expecting.
1057  */
1058  return (Datum) 0;
1059 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:264
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:110
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static void validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial)
Definition: tablefunc.c:1420
char * pstrdup(const char *in)
Definition: mcxt.c:1186
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:608
NameData relname
Definition: pg_class.h:35
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
TupleDesc expectedDesc
Definition: execnodes.h:301
#define ERROR
Definition: elog.h:43
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:1146
#define ereport(elevel, rest)
Definition: elog.h:141
uintptr_t Datum
Definition: postgres.h:367
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2067
int allowedModes
Definition: execnodes.h:302
SetFunctionReturnMode returnMode
Definition: execnodes.h:304
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:230
Tuplestorestate * setResult
Definition: execnodes.h:307
char * text_to_cstring(const text *t)
Definition: varlena.c:204
ExprContext * econtext
Definition: execnodes.h:300
TupleDesc setDesc
Definition: execnodes.h:308
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ connectby_text_serial()

Datum connectby_text_serial ( PG_FUNCTION_ARGS  )

Definition at line 1063 of file tablefunc.c.

References ReturnSetInfo::allowedModes, connectby(), CreateTupleDescCopy(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, ereport, errcode(), errmsg(), ERROR, ReturnSetInfo::expectedDesc, 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().

Referenced by connectby_text().

1064 {
1066  char *key_fld = text_to_cstring(PG_GETARG_TEXT_PP(1));
1067  char *parent_key_fld = text_to_cstring(PG_GETARG_TEXT_PP(2));
1068  char *orderby_fld = text_to_cstring(PG_GETARG_TEXT_PP(3));
1069  char *start_with = text_to_cstring(PG_GETARG_TEXT_PP(4));
1070  int max_depth = PG_GETARG_INT32(5);
1071  char *branch_delim = NULL;
1072  bool show_branch = false;
1073  bool show_serial = true;
1074  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1075  TupleDesc tupdesc;
1076  AttInMetadata *attinmeta;
1077  MemoryContext per_query_ctx;
1078  MemoryContext oldcontext;
1079 
1080  /* check to see if caller supports us returning a tuplestore */
1081  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1082  ereport(ERROR,
1083  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1084  errmsg("set-valued function called in context that cannot accept a set")));
1085  if (!(rsinfo->allowedModes & SFRM_Materialize) ||
1086  rsinfo->expectedDesc == NULL)
1087  ereport(ERROR,
1088  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1089  errmsg("materialize mode required, but it is not " \
1090  "allowed in this context")));
1091 
1092  if (fcinfo->nargs == 7)
1093  {
1094  branch_delim = text_to_cstring(PG_GETARG_TEXT_PP(6));
1095  show_branch = true;
1096  }
1097  else
1098  /* default is no show, tilde for the delimiter */
1099  branch_delim = pstrdup("~");
1100 
1101  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1102  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1103 
1104  /* get the requested return tuple description */
1105  tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1106 
1107  /* does it meet our needs */
1108  validateConnectbyTupleDesc(tupdesc, show_branch, show_serial);
1109 
1110  /* OK, use it then */
1111  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1112 
1113  /* OK, go to work */
1114  rsinfo->returnMode = SFRM_Materialize;
1115  rsinfo->setResult = connectby(relname,
1116  key_fld,
1117  parent_key_fld,
1118  orderby_fld,
1119  branch_delim,
1120  start_with,
1121  max_depth,
1122  show_branch,
1123  show_serial,
1124  per_query_ctx,
1126  attinmeta);
1127  rsinfo->setDesc = tupdesc;
1128 
1129  MemoryContextSwitchTo(oldcontext);
1130 
1131  /*
1132  * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1133  * tuples are in our tuplestore and passed back through rsinfo->setResult.
1134  * rsinfo->setDesc is set to the tuple description that we actually used
1135  * to build our tuples with, so the caller can verify we did what it was
1136  * expecting.
1137  */
1138  return (Datum) 0;
1139 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:264
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:110
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static void validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial)
Definition: tablefunc.c:1420
char * pstrdup(const char *in)
Definition: mcxt.c:1186
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:608
NameData relname
Definition: pg_class.h:35
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
TupleDesc expectedDesc
Definition: execnodes.h:301
#define ERROR
Definition: elog.h:43
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:1146
#define ereport(elevel, rest)
Definition: elog.h:141
uintptr_t Datum
Definition: postgres.h:367
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2067
int allowedModes
Definition: execnodes.h:302
SetFunctionReturnMode returnMode
Definition: execnodes.h:304
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:230
Tuplestorestate * setResult
Definition: execnodes.h:307
char * text_to_cstring(const text *t)
Definition: varlena.c:204
ExprContext * econtext
Definition: execnodes.h:300
TupleDesc setDesc
Definition: execnodes.h:308
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ crosstab()

Datum crosstab ( PG_FUNCTION_ARGS  )

Definition at line 348 of file tablefunc.c.

References ReturnSetInfo::allowedModes, BuildTupleFromCStrings(), compatCrosstabTupleDescs(), CreateTupleDescCopy(), crosstab_hash(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, ExprEndResult, get_call_result_type(), heap_freetuple(), i, IsA, ReturnSetInfo::isDone, MemoryContextSwitchTo(), palloc0(), pfree(), PG_FUNCTION_INFO_V1(), 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.

Referenced by get_normal_pair().

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

◆ crosstab_hash()

Datum crosstab_hash ( PG_FUNCTION_ARGS  )

Definition at line 634 of file tablefunc.c.

References ReturnSetInfo::allowedModes, CreateTupleDescCopy(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, ereport, errcode(), errmsg(), ERROR, ReturnSetInfo::expectedDesc, get_crosstab_tuplestore(), 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 crosstab(), and load_categories_hash().

635 {
636  char *sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
637  char *cats_sql = text_to_cstring(PG_GETARG_TEXT_PP(1));
638  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
639  TupleDesc tupdesc;
640  MemoryContext per_query_ctx;
641  MemoryContext oldcontext;
643 
644  /* check to see if caller supports us returning a tuplestore */
645  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
646  ereport(ERROR,
647  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
648  errmsg("set-valued function called in context that cannot accept a set")));
649  if (!(rsinfo->allowedModes & SFRM_Materialize) ||
650  rsinfo->expectedDesc == NULL)
651  ereport(ERROR,
652  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
653  errmsg("materialize mode required, but it is not " \
654  "allowed in this context")));
655 
656  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
657  oldcontext = MemoryContextSwitchTo(per_query_ctx);
658 
659  /* get the requested return tuple description */
660  tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
661 
662  /*
663  * Check to make sure we have a reasonable tuple descriptor
664  *
665  * Note we will attempt to coerce the values into whatever the return
666  * attribute type is and depend on the "in" function to complain if
667  * needed.
668  */
669  if (tupdesc->natts < 2)
670  ereport(ERROR,
671  (errcode(ERRCODE_SYNTAX_ERROR),
672  errmsg("query-specified return tuple and " \
673  "crosstab function are not compatible")));
674 
675  /* load up the categories hash table */
676  crosstab_hash = load_categories_hash(cats_sql, per_query_ctx);
677 
678  /* let the caller know we're sending back a tuplestore */
679  rsinfo->returnMode = SFRM_Materialize;
680 
681  /* now go build it */
682  rsinfo->setResult = get_crosstab_tuplestore(sql,
684  tupdesc,
685  per_query_ctx,
687 
688  /*
689  * SFRM_Materialize mode expects us to return a NULL Datum. The actual
690  * tuples are in our tuplestore and passed back through rsinfo->setResult.
691  * rsinfo->setDesc is set to the tuple description that we actually used
692  * to build our tuples with, so the caller can verify we did what it was
693  * expecting.
694  */
695  rsinfo->setDesc = tupdesc;
696  MemoryContextSwitchTo(oldcontext);
697 
698  return (Datum) 0;
699 }
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:110
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
static HTAB * load_categories_hash(char *cats_sql, MemoryContext per_query_ctx)
Definition: tablefunc.c:705
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:608
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
Definition: dynahash.c:208
TupleDesc expectedDesc
Definition: execnodes.h:301
#define ERROR
Definition: elog.h:43
static Tuplestorestate * get_crosstab_tuplestore(char *sql, HTAB *crosstab_hash, TupleDesc tupdesc, MemoryContext per_query_ctx, bool randomAccess)
Definition: tablefunc.c:790
#define ereport(elevel, rest)
Definition: elog.h:141
uintptr_t Datum
Definition: postgres.h:367
int allowedModes
Definition: execnodes.h:302
Datum crosstab_hash(PG_FUNCTION_ARGS)
Definition: tablefunc.c:634
SetFunctionReturnMode returnMode
Definition: execnodes.h:304
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:230
Tuplestorestate * setResult
Definition: execnodes.h:307
char * text_to_cstring(const text *t)
Definition: varlena.c:204
ExprContext * econtext
Definition: execnodes.h:300
TupleDesc setDesc
Definition: execnodes.h:308
int errmsg(const char *fmt,...)
Definition: elog.c:822

◆ get_crosstab_tuplestore()

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

Definition at line 790 of file tablefunc.c.

References crosstab_cat_desc::attidx, BuildTupleFromCStrings(), crosstab_cat_desc::catname, connectby_text(), crosstab_HashTableLookup, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, hash_get_num_entries(), i, TupleDescData::natts, palloc0(), PG_FUNCTION_INFO_V1(), 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_donestoring, tuplestore_puttuple(), SPITupleTable::vals, values, work_mem, xpfree, xpstrdup, and xstreq.

Referenced by crosstab_hash().

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

◆ get_normal_pair()

static void get_normal_pair ( float8 x1,
float8 x2 
)
static

Definition at line 277 of file tablefunc.c.

References crosstab(), MAX_RANDOM_VALUE, PG_FUNCTION_INFO_V1(), and random().

Referenced by normal_rand().

278 {
279  float8 u1,
280  u2,
281  v1,
282  v2,
283  s;
284 
285  do
286  {
287  u1 = (float8) random() / (float8) MAX_RANDOM_VALUE;
288  u2 = (float8) random() / (float8) MAX_RANDOM_VALUE;
289 
290  v1 = (2.0 * u1) - 1.0;
291  v2 = (2.0 * u2) - 1.0;
292 
293  s = v1 * v1 + v2 * v2;
294  } while (s >= 1.0);
295 
296  if (s == 0)
297  {
298  *x1 = 0;
299  *x2 = 0;
300  }
301  else
302  {
303  s = sqrt((-2.0 * log(s)) / s);
304  *x1 = v1 * s;
305  *x2 = v2 * s;
306  }
307 }
long random(void)
Definition: random.c:22
double float8
Definition: c.h:492
#define MAX_RANDOM_VALUE

◆ load_categories_hash()

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

Definition at line 705 of file tablefunc.c.

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, HASHCTL::hcxt, i, INIT_CATS, HASHCTL::keysize, MAX_CATNAME_LEN, MemoryContextSwitchTo(), MemSet, 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().

706 {
708  HASHCTL ctl;
709  int ret;
710  uint64 proc;
711  MemoryContext SPIcontext;
712 
713  /* initialize the category hash table */
714  MemSet(&ctl, 0, sizeof(ctl));
715  ctl.keysize = MAX_CATNAME_LEN;
716  ctl.entrysize = sizeof(crosstab_HashEnt);
717  ctl.hcxt = per_query_ctx;
718 
719  /*
720  * use INIT_CATS, defined above as a guess of how many hash table entries
721  * to create, initially
722  */
723  crosstab_hash = hash_create("crosstab hash",
724  INIT_CATS,
725  &ctl,
727 
728  /* Connect to SPI manager */
729  if ((ret = SPI_connect()) < 0)
730  /* internal error */
731  elog(ERROR, "load_categories_hash: SPI_connect returned %d", ret);
732 
733  /* Retrieve the category name rows */
734  ret = SPI_execute(cats_sql, true, 0);
735  proc = SPI_processed;
736 
737  /* Check for qualifying tuples */
738  if ((ret == SPI_OK_SELECT) && (proc > 0))
739  {
740  SPITupleTable *spi_tuptable = SPI_tuptable;
741  TupleDesc spi_tupdesc = spi_tuptable->tupdesc;
742  uint64 i;
743 
744  /*
745  * The provided categories SQL query must always return one column:
746  * category - the label or identifier for each column
747  */
748  if (spi_tupdesc->natts != 1)
749  ereport(ERROR,
750  (errcode(ERRCODE_SYNTAX_ERROR),
751  errmsg("provided \"categories\" SQL must " \
752  "return 1 column of at least one row")));
753 
754  for (i = 0; i < proc; i++)
755  {
756  crosstab_cat_desc *catdesc;
757  char *catname;
758  HeapTuple spi_tuple;
759 
760  /* get the next sql result tuple */
761  spi_tuple = spi_tuptable->vals[i];
762 
763  /* get the category from the current sql result tuple */
764  catname = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
765 
766  SPIcontext = MemoryContextSwitchTo(per_query_ctx);
767 
768  catdesc = (crosstab_cat_desc *) palloc(sizeof(crosstab_cat_desc));
769  catdesc->catname = catname;
770  catdesc->attidx = i;
771 
772  /* Add the proc description block to the hashtable */
773  crosstab_HashTableInsert(crosstab_hash, catdesc);
774 
775  MemoryContextSwitchTo(SPIcontext);
776  }
777  }
778 
779  if (SPI_finish() != SPI_OK_FINISH)
780  /* internal error */
781  elog(ERROR, "load_categories_hash: SPI_finish() failed");
782 
783  return crosstab_hash;
784 }
#define MAX_CATNAME_LEN
Definition: tablefunc.c:125
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
MemoryContext hcxt
Definition: hsearch.h:78
int SPI_connect(void)
Definition: spi.c:89
int SPI_finish(void)
Definition: spi.c:176
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Size entrysize
Definition: hsearch.h:73
SPITupleTable * SPI_tuptable
Definition: spi.c:46
int errcode(int sqlerrcode)
Definition: elog.c:608
#define MemSet(start, val, len)
Definition: c.h:962
HeapTuple * vals
Definition: spi.h:26
uint64 SPI_processed
Definition: spi.c:45
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:996
Definition: dynahash.c:208
#define ERROR
Definition: elog.h:43
#define INIT_CATS
Definition: tablefunc.c:126
struct crosstab_hashent crosstab_HashEnt
#define ereport(elevel, rest)
Definition: elog.h:141
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
Size keysize
Definition: hsearch.h:72
TupleDesc tupdesc
Definition: spi.h:25
#define SPI_OK_SELECT
Definition: spi.h:57
Datum crosstab_hash(PG_FUNCTION_ARGS)
Definition: tablefunc.c:634
#define SPI_OK_FINISH
Definition: spi.h:54
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
int i
#define crosstab_HashTableInsert(HASHTAB, CATDESC)
Definition: tablefunc.c:142
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:496

◆ normal_rand()

Datum normal_rand ( PG_FUNCTION_ARGS  )

Definition at line 173 of file tablefunc.c.

References FuncCallContext::call_cntr, normal_rand_fctx::carry_val, Float8GetDatum(), get_normal_pair(), FuncCallContext::max_calls, normal_rand_fctx::mean, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, palloc(), PG_GETARG_FLOAT8, PG_GETARG_UINT32, 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.

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  /* create a function context for cross-call persistence */
189  funcctx = SRF_FIRSTCALL_INIT();
190 
191  /*
192  * switch to memory context appropriate for multiple function calls
193  */
194  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
195 
196  /* total number of tuples to be returned */
197  funcctx->max_calls = PG_GETARG_UINT32(0);
198 
199  /* allocate memory for user context */
200  fctx = (normal_rand_fctx *) palloc(sizeof(normal_rand_fctx));
201 
202  /*
203  * Use fctx to keep track of upper and lower bounds from call to call.
204  * It will also be used to carry over the spare value we get from the
205  * Box-Muller algorithm so that we only actually calculate a new value
206  * every other call.
207  */
208  fctx->mean = PG_GETARG_FLOAT8(1);
209  fctx->stddev = PG_GETARG_FLOAT8(2);
210  fctx->carry_val = 0;
211  fctx->use_carry = false;
212 
213  funcctx->user_fctx = fctx;
214 
215  MemoryContextSwitchTo(oldcontext);
216  }
217 
218  /* stuff done on every call of the function */
219  funcctx = SRF_PERCALL_SETUP();
220 
221  call_cntr = funcctx->call_cntr;
222  max_calls = funcctx->max_calls;
223  fctx = funcctx->user_fctx;
224  mean = fctx->mean;
225  stddev = fctx->stddev;
226  carry_val = fctx->carry_val;
227  use_carry = fctx->use_carry;
228 
229  if (call_cntr < max_calls) /* do when there is more left to send */
230  {
231  float8 result;
232 
233  if (use_carry)
234  {
235  /*
236  * reset use_carry and use second value obtained on last pass
237  */
238  fctx->use_carry = false;
239  result = carry_val;
240  }
241  else
242  {
243  float8 normval_1;
244  float8 normval_2;
245 
246  /* Get the next two normal values */
247  get_normal_pair(&normval_1, &normval_2);
248 
249  /* use the first */
250  result = mean + (stddev * normval_1);
251 
252  /* and save the second */
253  fctx->carry_val = mean + (stddev * normval_2);
254  fctx->use_carry = true;
255  }
256 
257  /* send the result */
258  SRF_RETURN_NEXT(funcctx, Float8GetDatum(result));
259  }
260  else
261  /* do when there is no more left */
262  SRF_RETURN_DONE(funcctx);
263 }
#define PG_GETARG_FLOAT8(n)
Definition: fmgr.h:276
uint64 call_cntr
Definition: funcapi.h:65
#define PG_GETARG_UINT32(n)
Definition: fmgr.h:265
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:282
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:286
Datum Float8GetDatum(float8 X)
Definition: fmgr.c:1708
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:288
static void get_normal_pair(float8 *x1, float8 *x2)
Definition: tablefunc.c:277
double float8
Definition: c.h:492
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
void * user_fctx
Definition: funcapi.h:82
void * palloc(Size size)
Definition: mcxt.c:949
uint64 max_calls
Definition: funcapi.h:74
float8 carry_val
Definition: tablefunc.c:90
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:306
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:284

◆ PG_FUNCTION_INFO_V1() [1/5]

PG_FUNCTION_INFO_V1 ( normal_rand  )

◆ PG_FUNCTION_INFO_V1() [2/5]

PG_FUNCTION_INFO_V1 ( crosstab  )

◆ PG_FUNCTION_INFO_V1() [3/5]

PG_FUNCTION_INFO_V1 ( crosstab_hash  )

◆ PG_FUNCTION_INFO_V1() [4/5]

PG_FUNCTION_INFO_V1 ( connectby_text  )

◆ PG_FUNCTION_INFO_V1() [5/5]

PG_FUNCTION_INFO_V1 ( connectby_text_serial  )

◆ validateConnectbyTupleDesc()

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

Definition at line 1420 of file tablefunc.c.

References atttypid, 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().

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

Variable Documentation

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 46 of file tablefunc.c.