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, 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:124
int errcode(int sqlerrcode)
Definition: elog.c:610
#define MemSet(start, val, len)
Definition: c.h:950
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919
#define ERROR
Definition: elog.h:43
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32

Definition at line 141 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:124
#define MemSet(start, val, len)
Definition: c.h:950
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:919

Definition at line 127 of file tablefunc.c.

Referenced by get_crosstab_tuplestore().

◆ INIT_CATS

#define INIT_CATS   64

Definition at line 125 of file tablefunc.c.

Referenced by load_categories_hash().

◆ INT32_STRLEN

#define INT32_STRLEN   12

Definition at line 115 of file tablefunc.c.

Referenced by build_tuplestore_recursively().

◆ MAX_CATNAME_LEN

#define MAX_CATNAME_LEN   NAMEDATALEN

Definition at line 124 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 93 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:1187

Definition at line 102 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 110 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 1199 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().

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

◆ compatConnectbyTupleDescs()

static void compatConnectbyTupleDescs ( TupleDesc  tupdesc1,
TupleDesc  tupdesc2 
)
static

Definition at line 1493 of file tablefunc.c.

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

Referenced by build_tuplestore_recursively().

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

◆ compatCrosstabTupleDescs()

static bool compatCrosstabTupleDescs ( TupleDesc  tupdesc1,
TupleDesc  tupdesc2 
)
static

Definition at line 1548 of file tablefunc.c.

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

Referenced by crosstab().

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

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

◆ 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 allowed in this context")));
1010 
1011  if (fcinfo->nargs == 6)
1012  {
1013  branch_delim = text_to_cstring(PG_GETARG_TEXT_PP(5));
1014  show_branch = true;
1015  }
1016  else
1017  /* default is no show, tilde for the delimiter */
1018  branch_delim = pstrdup("~");
1019 
1020  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1021  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1022 
1023  /* get the requested return tuple description */
1024  tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1025 
1026  /* does it meet our needs */
1027  validateConnectbyTupleDesc(tupdesc, show_branch, show_serial);
1028 
1029  /* OK, use it then */
1030  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1031 
1032  /* OK, go to work */
1033  rsinfo->returnMode = SFRM_Materialize;
1034  rsinfo->setResult = connectby(relname,
1035  key_fld,
1036  parent_key_fld,
1037  NULL,
1038  branch_delim,
1039  start_with,
1040  max_depth,
1041  show_branch,
1042  show_serial,
1043  per_query_ctx,
1045  attinmeta);
1046  rsinfo->setDesc = tupdesc;
1047 
1048  MemoryContextSwitchTo(oldcontext);
1049 
1050  /*
1051  * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1052  * tuples are in our tuplestore and passed back through rsinfo->setResult.
1053  * rsinfo->setDesc is set to the tuple description that we actually used
1054  * to build our tuples with, so the caller can verify we did what it was
1055  * expecting.
1056  */
1057  return (Datum) 0;
1058 }
#define PG_GETARG_INT32(n)
Definition: fmgr.h:269
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:110
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
static void validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial)
Definition: tablefunc.c:1418
char * pstrdup(const char *in)
Definition: mcxt.c:1187
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:610
NameData relname
Definition: pg_class.h:38
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:308
TupleDesc expectedDesc
Definition: execnodes.h:303
#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:1144
uintptr_t Datum
Definition: postgres.h:367
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2067
#define ereport(elevel,...)
Definition: elog.h:144
int allowedModes
Definition: execnodes.h:304
SetFunctionReturnMode returnMode
Definition: execnodes.h:306
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:232
Tuplestorestate * setResult
Definition: execnodes.h:309
char * text_to_cstring(const text *t)
Definition: varlena.c:221
ExprContext * econtext
Definition: execnodes.h:302
TupleDesc setDesc
Definition: execnodes.h:310
int errmsg(const char *fmt,...)
Definition: elog.c:821

◆ connectby_text_serial()

Datum connectby_text_serial ( PG_FUNCTION_ARGS  )

Definition at line 1062 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().

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

◆ crosstab()

Datum crosstab ( PG_FUNCTION_ARGS  )

Definition at line 347 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().

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

◆ crosstab_hash()

Datum crosstab_hash ( PG_FUNCTION_ARGS  )

Definition at line 632 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().

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

◆ get_crosstab_tuplestore()

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

Definition at line 791 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:90
int SPI_finish(void)
Definition: spi.c:177
#define tuplestore_donestoring(state)
Definition: tuplestore.h:60
SPITupleTable * SPI_tuptable
Definition: spi.c:46
int errcode(int sqlerrcode)
Definition: elog.c:610
long hash_get_num_entries(HTAB *hashp)
Definition: dynahash.c:1347
#define xpfree(var_)
Definition: tablefunc.c:93
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:1069
#define ERROR
Definition: elog.h:43
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:730
#define xstreq(tgtvar_, srcvar_)
Definition: tablefunc.c:110
int errdetail(const char *fmt,...)
Definition: elog.c:954
#define crosstab_HashTableLookup(HASHTAB, CATNAME, CATDESC)
Definition: tablefunc.c:127
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
void * palloc0(Size size)
Definition: mcxt.c:981
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 ereport(elevel,...)
Definition: elog.h:144
#define SPI_OK_FINISH
Definition: spi.h:54
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
int i
#define xpstrdup(tgtvar_, srcvar_)
Definition: tablefunc.c:102
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:497

◆ get_normal_pair()

static void get_normal_pair ( float8 x1,
float8 x2 
)
static

Definition at line 276 of file tablefunc.c.

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

Referenced by normal_rand().

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

◆ load_categories_hash()

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

Definition at line 701 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().

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

◆ normal_rand()

Datum normal_rand ( PG_FUNCTION_ARGS  )

Definition at line 172 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.

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

◆ 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 1418 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().

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

Variable Documentation

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 46 of file tablefunc.c.