PostgreSQL Source Code git master
Loading...
Searching...
No Matches
tablefunc.c File Reference
#include "postgres.h"
#include <math.h>
#include "access/htup_details.h"
#include "catalog/pg_type.h"
#include "common/pg_prng.h"
#include "executor/spi.h"
#include "fmgr.h"
#include "funcapi.h"
#include "lib/stringinfo.h"
#include "miscadmin.h"
#include "utils/builtins.h"
#include "utils/tuplestore.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

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

Macro Definition Documentation

◆ CONNECTBY_NCOLS

#define CONNECTBY_NCOLS   4

Definition at line 974 of file tablefunc.c.

◆ CONNECTBY_NCOLS_NOBRANCH

#define CONNECTBY_NCOLS_NOBRANCH   3

Definition at line 975 of file tablefunc.c.

◆ crosstab_HashTableInsert

#define crosstab_HashTableInsert (   HASHTAB,
  CATDESC 
)
Value:
do { \
crosstab_HashEnt *hentry; bool found; char key[MAX_CATNAME_LEN]; \
snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATDESC->catname); \
key, HASH_ENTER, &found); \
if (found) \
errmsg("duplicate category name"))); \
hentry->catdesc = CATDESC; \
} while(0)
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:952
int errcode(int sqlerrcode)
Definition elog.c:874
#define ERROR
Definition elog.h:39
@ HASH_ENTER
Definition hsearch.h:114
static char * errmsg
static int fb(int x)
#define ERRCODE_DUPLICATE_OBJECT
Definition streamutil.c:30
#define MAX_CATNAME_LEN
Definition tablefunc.c:129

Definition at line 146 of file tablefunc.c.

147 { \
148 crosstab_HashEnt *hentry; bool found; char key[MAX_CATNAME_LEN]; \
149 \
150 MemSet(key, 0, MAX_CATNAME_LEN); \
151 snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATDESC->catname); \
153 key, HASH_ENTER, &found); \
154 if (found) \
157 errmsg("duplicate category name"))); \
158 hentry->catdesc = CATDESC; \
159} while(0)

◆ crosstab_HashTableLookup

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

Definition at line 132 of file tablefunc.c.

133 { \
135 \
136 MemSet(key, 0, MAX_CATNAME_LEN); \
137 snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATNAME); \
139 key, HASH_FIND, NULL); \
140 if (hentry) \
141 CATDESC = hentry->catdesc; \
142 else \
143 CATDESC = NULL; \
144} while(0)

◆ INIT_CATS

#define INIT_CATS   64

Definition at line 130 of file tablefunc.c.

◆ INT32_STRLEN

#define INT32_STRLEN   12

Definition at line 120 of file tablefunc.c.

◆ MAX_CATNAME_LEN

#define MAX_CATNAME_LEN   NAMEDATALEN

Definition at line 129 of file tablefunc.c.

◆ xpfree

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

Definition at line 98 of file tablefunc.c.

99 { \
100 if (var_ != NULL) \
101 { \
102 pfree(var_); \
103 var_ = NULL; \
104 } \
105 } while (0)

◆ xpstrdup

#define xpstrdup (   tgtvar_,
  srcvar_ 
)
Value:
do { \
} while (0)
char * pstrdup(const char *in)
Definition mcxt.c:1781

Definition at line 107 of file tablefunc.c.

108 { \
109 if (srcvar_) \
111 else \
112 tgtvar_ = NULL; \
113 } while (0)

◆ xstreq

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

Definition at line 115 of file tablefunc.c.

Typedef Documentation

◆ crosstab_cat_desc

◆ crosstab_HashEnt

Function Documentation

◆ build_tuplestore_recursively()

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

Definition at line 1189 of file tablefunc.c.

1204{
1205 TupleDesc tupdesc = attinmeta->tupdesc;
1206 int ret;
1207 uint64 proc;
1208 int serial_column;
1209 StringInfoData sql;
1210 char **values;
1211 char *current_key;
1212 char *current_key_parent;
1215 char *current_branch;
1216 HeapTuple tuple;
1217
1218 if (max_depth > 0 && level > max_depth)
1219 return;
1220
1221 initStringInfo(&sql);
1222
1223 /* Build initial sql statement */
1224 if (!show_serial)
1225 {
1226 appendStringInfo(&sql, "SELECT %s, %s FROM %s WHERE %s = %s AND %s IS NOT NULL AND %s <> %s",
1227 key_fld,
1229 relname,
1233 serial_column = 0;
1234 }
1235 else
1236 {
1237 appendStringInfo(&sql, "SELECT %s, %s FROM %s WHERE %s = %s AND %s IS NOT NULL AND %s <> %s ORDER BY %s",
1238 key_fld,
1240 relname,
1244 orderby_fld);
1245 serial_column = 1;
1246 }
1247
1248 if (show_branch)
1249 values = (char **) palloc((CONNECTBY_NCOLS + serial_column) * sizeof(char *));
1250 else
1251 values = (char **) palloc((CONNECTBY_NCOLS_NOBRANCH + serial_column) * sizeof(char *));
1252
1253 /* First time through, do a little setup */
1254 if (level == 0)
1255 {
1256 /* root value is the one we initially start with */
1257 values[0] = start_with;
1258
1259 /* root value has no parent */
1260 values[1] = NULL;
1261
1262 /* root level is 0 */
1263 sprintf(current_level, "%d", level);
1264 values[2] = current_level;
1265
1266 /* root branch is just starting root value */
1267 if (show_branch)
1268 values[3] = start_with;
1269
1270 /* root starts the serial with 1 */
1271 if (show_serial)
1272 {
1273 sprintf(serial_str, "%d", (*serial)++);
1274 if (show_branch)
1275 values[4] = serial_str;
1276 else
1277 values[3] = serial_str;
1278 }
1279
1280 /* construct the tuple */
1281 tuple = BuildTupleFromCStrings(attinmeta, values);
1282
1283 /* now store it */
1284 tuplestore_puttuple(tupstore, tuple);
1285
1286 /* increment level */
1287 level++;
1288 }
1289
1290 /* Retrieve the desired rows */
1291 ret = SPI_execute(sql.data, true, 0);
1292 proc = SPI_processed;
1293
1294 /* Check for qualifying tuples */
1295 if ((ret == SPI_OK_SELECT) && (proc > 0))
1296 {
1298 SPITupleTable *tuptable = SPI_tuptable;
1299 TupleDesc spi_tupdesc = tuptable->tupdesc;
1300 uint64 i;
1304
1305 /*
1306 * Check that return tupdesc is compatible with the one we got from
1307 * the query.
1308 */
1310
1314
1315 for (i = 0; i < proc; i++)
1316 {
1317 /* initialize branch for this pass */
1320
1321 /* get the next sql result tuple */
1322 spi_tuple = tuptable->vals[i];
1323
1324 /* get the current key (might be NULL) */
1326
1327 /* get the parent key (might be NULL) */
1329
1330 /* get the current level */
1331 sprintf(current_level, "%d", level);
1332
1333 /* check to see if this key is also an ancestor */
1334 if (current_key)
1335 {
1338 if (strstr(chk_branchstr.data, chk_current_key.data))
1339 ereport(ERROR,
1341 errmsg("infinite recursion detected")));
1342 }
1343
1344 /* OK, extend the branch */
1345 if (current_key)
1348
1349 /* build a tuple */
1350 values[0] = current_key;
1352 values[2] = current_level;
1353 if (show_branch)
1355 if (show_serial)
1356 {
1357 sprintf(serial_str, "%d", (*serial)++);
1358 if (show_branch)
1359 values[4] = serial_str;
1360 else
1361 values[3] = serial_str;
1362 }
1363
1364 tuple = BuildTupleFromCStrings(attinmeta, values);
1365
1366 /* store the tuple for later use */
1367 tuplestore_puttuple(tupstore, tuple);
1368
1369 heap_freetuple(tuple);
1370
1371 /* recurse using current_key as the new start_with */
1372 if (current_key)
1375 relname,
1380 level + 1,
1381 serial,
1382 max_depth,
1386 attinmeta,
1387 tupstore);
1388
1391
1392 /* reset branch for next pass */
1396 }
1397
1398 xpfree(branchstr.data);
1399 xpfree(chk_branchstr.data);
1400 xpfree(chk_current_key.data);
1401 }
1402}
static Datum values[MAXATTR]
Definition bootstrap.c:188
uint64_t uint64
Definition c.h:619
#define ereport(elevel,...)
Definition elog.h:150
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1384
int i
Definition isn.c:77
void * palloc(Size size)
Definition mcxt.c:1387
NameData relname
Definition pg_class.h:40
#define sprintf
Definition port.h:262
char * quote_literal_cstr(const char *rawstr)
Definition quote.c:101
uint64 SPI_processed
Definition spi.c:45
SPITupleTable * SPI_tuptable
Definition spi.c:46
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition spi.c:1221
int SPI_execute(const char *src, bool read_only, long tcount)
Definition spi.c:597
#define SPI_OK_SELECT
Definition spi.h:86
void resetStringInfo(StringInfo str)
Definition stringinfo.c:126
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
TupleDesc tupdesc
Definition funcapi.h:38
TupleDesc tupdesc
Definition spi.h:25
HeapTuple * vals
Definition spi.h:26
#define CONNECTBY_NCOLS_NOBRANCH
Definition tablefunc.c:975
#define INT32_STRLEN
Definition tablefunc.c:120
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:1189
#define CONNECTBY_NCOLS
Definition tablefunc.c:974
static void compatConnectbyTupleDescs(TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
Definition tablefunc.c:1468
#define xpfree(var_)
Definition tablefunc.c:98
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition tuplestore.c:765

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

Referenced by build_tuplestore_recursively(), and connectby().

◆ compatConnectbyTupleDescs()

static void compatConnectbyTupleDescs ( TupleDesc  ret_tupdesc,
TupleDesc  sql_tupdesc 
)
static

Definition at line 1468 of file tablefunc.c.

1469{
1474
1475 /*
1476 * Query result must have at least 2 columns.
1477 */
1478 if (sql_tupdesc->natts < 2)
1479 ereport(ERROR,
1481 errmsg("invalid connectby source data query"),
1482 errdetail("The query must return at least two columns.")));
1483
1484 /*
1485 * These columns must match the result type indicated by the calling
1486 * query.
1487 */
1488 ret_atttypid = TupleDescAttr(ret_tupdesc, 0)->atttypid;
1489 sql_atttypid = TupleDescAttr(sql_tupdesc, 0)->atttypid;
1490 ret_atttypmod = TupleDescAttr(ret_tupdesc, 0)->atttypmod;
1491 sql_atttypmod = TupleDescAttr(sql_tupdesc, 0)->atttypmod;
1492 if (ret_atttypid != sql_atttypid ||
1494 ereport(ERROR,
1496 errmsg("invalid connectby return type"),
1497 errdetail("Source key type %s does not match return key type %s.",
1500
1501 ret_atttypid = TupleDescAttr(ret_tupdesc, 1)->atttypid;
1502 sql_atttypid = TupleDescAttr(sql_tupdesc, 1)->atttypid;
1503 ret_atttypmod = TupleDescAttr(ret_tupdesc, 1)->atttypmod;
1504 sql_atttypmod = TupleDescAttr(sql_tupdesc, 1)->atttypmod;
1505 if (ret_atttypid != sql_atttypid ||
1507 ereport(ERROR,
1509 errmsg("invalid connectby return type"),
1510 errdetail("Source parent key type %s does not match return parent key type %s.",
1513
1514 /* OK, the two tupdescs are compatible for our purposes */
1515}
int32_t int32
Definition c.h:614
int errdetail(const char *fmt,...) pg_attribute_printf(1
char * format_type_with_typemod(Oid type_oid, int32 typemod)
unsigned int Oid
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178

References ereport, errcode(), errdetail(), errmsg, ERROR, fb(), format_type_with_typemod(), and TupleDescAttr().

Referenced by build_tuplestore_recursively().

◆ compatCrosstabTupleDescs()

static void compatCrosstabTupleDescs ( TupleDesc  ret_tupdesc,
TupleDesc  sql_tupdesc 
)
static

Definition at line 1521 of file tablefunc.c.

1522{
1523 int i;
1528
1529 if (ret_tupdesc->natts < 2)
1530 ereport(ERROR,
1532 errmsg("invalid crosstab return type"),
1533 errdetail("Return row must have at least two columns.")));
1534 Assert(sql_tupdesc->natts == 3); /* already checked by caller */
1535
1536 /* check the row_name types match */
1537 ret_atttypid = TupleDescAttr(ret_tupdesc, 0)->atttypid;
1538 sql_atttypid = TupleDescAttr(sql_tupdesc, 0)->atttypid;
1539 ret_atttypmod = TupleDescAttr(ret_tupdesc, 0)->atttypmod;
1540 sql_atttypmod = TupleDescAttr(sql_tupdesc, 0)->atttypmod;
1541 if (ret_atttypid != sql_atttypid ||
1543 ereport(ERROR,
1545 errmsg("invalid crosstab return type"),
1546 errdetail("Source row_name datatype %s does not match return row_name datatype %s.",
1549
1550 /*
1551 * attribute [1] of sql tuple is the category; no need to check it
1552 * attribute [2] of sql tuple should match attributes [1] to [natts - 1]
1553 * of the return tuple
1554 */
1555 sql_atttypid = TupleDescAttr(sql_tupdesc, 2)->atttypid;
1556 sql_atttypmod = TupleDescAttr(sql_tupdesc, 2)->atttypmod;
1557 for (i = 1; i < ret_tupdesc->natts; i++)
1558 {
1559 ret_atttypid = TupleDescAttr(ret_tupdesc, i)->atttypid;
1560 ret_atttypmod = TupleDescAttr(ret_tupdesc, i)->atttypmod;
1561
1562 if (ret_atttypid != sql_atttypid ||
1564 ereport(ERROR,
1566 errmsg("invalid crosstab return type"),
1567 errdetail("Source value datatype %s does not match return value datatype %s in column %d.",
1570 i + 1)));
1571 }
1572
1573 /* OK, the two tupdescs are compatible for our purposes */
1574}
#define Assert(condition)
Definition c.h:945

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

Referenced by crosstab().

◆ connectby()

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

Definition at line 1138 of file tablefunc.c.

1150{
1151 Tuplestorestate *tupstore = NULL;
1152 MemoryContext oldcontext;
1153 int serial = 1;
1154
1155 /* Connect to SPI manager */
1156 SPI_connect();
1157
1158 /* switch to longer term context to create the tuple store */
1160
1161 /* initialize our tuplestore */
1162 tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
1163
1164 MemoryContextSwitchTo(oldcontext);
1165
1166 /* now go get the whole tree */
1169 relname,
1172 start_with,
1173 start_with, /* current_branch */
1174 0, /* initial level is 0 */
1175 &serial, /* initial serial is 1 */
1176 max_depth,
1180 attinmeta,
1181 tupstore);
1182
1183 SPI_finish();
1184
1185 return tupstore;
1186}
int work_mem
Definition globals.c:131
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
int SPI_connect(void)
Definition spi.c:95
int SPI_finish(void)
Definition spi.c:183
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition tuplestore.c:331

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

Referenced by connectby_text(), and connectby_text_serial().

◆ connectby_text()

Datum connectby_text ( PG_FUNCTION_ARGS  )

Definition at line 978 of file tablefunc.c.

979{
984 int max_depth = PG_GETARG_INT32(4);
985 char *branch_delim = NULL;
986 bool show_branch = false;
987 bool show_serial = false;
988 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
989 TupleDesc tupdesc;
990 AttInMetadata *attinmeta;
992 MemoryContext oldcontext;
993
994 /* check to see if caller supports us returning a tuplestore */
995 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
998 errmsg("set-valued function called in context that cannot accept a set")));
999 if (!(rsinfo->allowedModes & SFRM_Materialize) ||
1000 rsinfo->expectedDesc == NULL)
1001 ereport(ERROR,
1003 errmsg("materialize mode required, but it is not allowed in this context")));
1004
1005 if (fcinfo->nargs == 6)
1006 {
1008 show_branch = true;
1009 }
1010 else
1011 /* default is no show, tilde for the delimiter */
1012 branch_delim = pstrdup("~");
1013
1014 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1016
1017 /* get the requested return tuple description */
1018 tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1019
1020 /* does it meet our needs */
1022
1023 /* OK, use it then */
1024 attinmeta = TupleDescGetAttInMetadata(tupdesc);
1025
1026 /* OK, go to work */
1027 rsinfo->returnMode = SFRM_Materialize;
1028 rsinfo->setResult = connectby(relname,
1029 key_fld,
1031 NULL,
1033 start_with,
1034 max_depth,
1038 rsinfo->allowedModes & SFRM_Materialize_Random,
1039 attinmeta);
1040 rsinfo->setDesc = tupdesc;
1041
1042 MemoryContextSwitchTo(oldcontext);
1043
1044 /*
1045 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1046 * tuples are in our tuplestore and passed back through rsinfo->setResult.
1047 * rsinfo->setDesc is set to the tuple description that we actually used
1048 * to build our tuples with, so the caller can verify we did what it was
1049 * expecting.
1050 */
1051 return (Datum) 0;
1052}
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
@ SFRM_Materialize_Random
Definition execnodes.h:353
@ SFRM_Materialize
Definition execnodes.h:352
#define PG_GETARG_TEXT_PP(n)
Definition fmgr.h:310
#define PG_GETARG_INT32(n)
Definition fmgr.h:269
#define IsA(nodeptr, _type_)
Definition nodes.h:164
uint64_t Datum
Definition postgres.h:70
static void validateConnectbyTupleDesc(TupleDesc td, bool show_branch, bool show_serial)
Definition tablefunc.c:1408
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:1138
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition tupdesc.c:242
char * text_to_cstring(const text *t)
Definition varlena.c:217

References connectby(), CreateTupleDescCopy(), ereport, errcode(), errmsg, ERROR, fb(), IsA, MemoryContextSwitchTo(), PG_GETARG_INT32, PG_GETARG_TEXT_PP, pstrdup(), relname, SFRM_Materialize, SFRM_Materialize_Random, text_to_cstring(), TupleDescGetAttInMetadata(), and validateConnectbyTupleDesc().

◆ connectby_text_serial()

Datum connectby_text_serial ( PG_FUNCTION_ARGS  )

Definition at line 1056 of file tablefunc.c.

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

References connectby(), CreateTupleDescCopy(), ereport, errcode(), errmsg, ERROR, fb(), IsA, MemoryContextSwitchTo(), PG_GETARG_INT32, PG_GETARG_TEXT_PP, pstrdup(), relname, SFRM_Materialize, SFRM_Materialize_Random, text_to_cstring(), TupleDescGetAttInMetadata(), and validateConnectbyTupleDesc().

◆ crosstab()

Datum crosstab ( PG_FUNCTION_ARGS  )

Definition at line 359 of file tablefunc.c.

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

References BuildTupleFromCStrings(), compatCrosstabTupleDescs(), CreateTupleDescCopy(), ereport, errcode(), errdetail(), errmsg, ERROR, ExprEndResult, fb(), get_call_result_type(), heap_freetuple(), i, IsA, MemoryContextSwitchTo(), TupleDescData::natts, palloc0(), pfree(), PG_GETARG_TEXT_PP, PG_RETURN_NULL, SFRM_Materialize, SFRM_Materialize_Random, SPI_connect(), SPI_execute(), SPI_finish(), SPI_getvalue(), SPI_OK_SELECT, SPI_processed, SPI_tuptable, text_to_cstring(), SPITupleTable::tupdesc, TupleDescGetAttInMetadata(), tuplestore_begin_heap(), tuplestore_puttuple(), TYPEFUNC_COMPOSITE, TYPEFUNC_RECORD, values, work_mem, xpfree, xpstrdup, and xstreq.

◆ crosstab_hash()

Datum crosstab_hash ( PG_FUNCTION_ARGS  )

Definition at line 637 of file tablefunc.c.

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

References CreateTupleDescCopy(), crosstab_hash(), ereport, errcode(), errdetail(), errmsg, ERROR, fb(), get_crosstab_tuplestore(), IsA, load_categories_hash(), MemoryContextSwitchTo(), TupleDescData::natts, PG_GETARG_TEXT_PP, SFRM_Materialize, SFRM_Materialize_Random, and text_to_cstring().

Referenced by crosstab_hash(), get_crosstab_tuplestore(), and load_categories_hash().

◆ get_crosstab_tuplestore()

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

Definition at line 792 of file tablefunc.c.

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

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

Referenced by crosstab_hash().

◆ get_normal_pair()

static void get_normal_pair ( float8 x1,
float8 x2 
)
static

Definition at line 288 of file tablefunc.c.

289{
290 float8 u1,
291 u2,
292 v1,
293 v2,
294 s;
295
296 do
297 {
300
301 v1 = (2.0 * u1) - 1.0;
302 v2 = (2.0 * u2) - 1.0;
303
304 s = v1 * v1 + v2 * v2;
305 } while (s >= 1.0);
306
307 if (s == 0)
308 {
309 *x1 = 0;
310 *x2 = 0;
311 }
312 else
313 {
314 s = sqrt((-2.0 * log(s)) / s);
315 *x1 = v1 * s;
316 *x2 = v2 * s;
317 }
318}
double float8
Definition c.h:716
double pg_prng_double(pg_prng_state *state)
Definition pg_prng.c:268
pg_prng_state pg_global_prng_state
Definition pg_prng.c:34

References fb(), pg_global_prng_state, and pg_prng_double().

Referenced by normal_rand().

◆ load_categories_hash()

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

Definition at line 706 of file tablefunc.c.

707{
709 HASHCTL ctl;
710 int ret;
711 uint64 proc;
713
714 /* initialize the category hash table */
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 SPI_connect();
730
731 /* Retrieve the category name rows */
732 ret = SPI_execute(cats_sql, true, 0);
733 proc = SPI_processed;
734
735 /* Check for qualifying tuples */
736 if ((ret == SPI_OK_SELECT) && (proc > 0))
737 {
740 uint64 i;
741
742 /*
743 * The provided categories SQL query must always return one column:
744 * category - the label or identifier for each column
745 */
746 if (spi_tupdesc->natts != 1)
749 errmsg("invalid crosstab categories query"),
750 errdetail("The query must return one column.")));
751
752 for (i = 0; i < proc; i++)
753 {
754 crosstab_cat_desc *catdesc;
755 char *catname;
757
758 /* get the next sql result tuple */
759 spi_tuple = spi_tuptable->vals[i];
760
761 /* get the category from the current sql result tuple */
762 catname = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
763 if (catname == NULL)
766 errmsg("crosstab category value must not be null")));
767
769
771 catdesc->catname = catname;
772 catdesc->attidx = i;
773
774 /* Add the proc description block to the hashtable */
776
778 }
779 }
780
781 if (SPI_finish() != SPI_OK_FINISH)
782 /* internal error */
783 elog(ERROR, "load_categories_hash: SPI_finish() failed");
784
785 return crosstab_hash;
786}
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:358
#define palloc_object(type)
Definition fe_memutils.h:74
#define HASH_STRINGS
Definition hsearch.h:96
#define HASH_CONTEXT
Definition hsearch.h:102
#define HASH_ELEM
Definition hsearch.h:95
tree ctl
Definition radixtree.h:1838
#define crosstab_HashTableInsert(HASHTAB, CATDESC)
Definition tablefunc.c:146
#define INIT_CATS
Definition tablefunc.c:130
struct crosstab_hashent crosstab_HashEnt

References crosstab_cat_desc::attidx, crosstab_cat_desc::catname, crosstab_hash(), crosstab_HashTableInsert, ctl, elog, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_STRINGS, i, INIT_CATS, MAX_CATNAME_LEN, MemoryContextSwitchTo(), palloc_object, SPI_connect(), SPI_execute(), SPI_finish(), SPI_getvalue(), SPI_OK_FINISH, SPI_OK_SELECT, SPI_processed, and SPI_tuptable.

Referenced by crosstab_hash().

◆ normal_rand()

Datum normal_rand ( PG_FUNCTION_ARGS  )

Definition at line 177 of file tablefunc.c.

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

References ereport, errcode(), errmsg, ERROR, fb(), Float8GetDatum(), get_normal_pair(), MemoryContextSwitchTo(), palloc_object, PG_GETARG_FLOAT8, PG_GETARG_INT32, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, and SRF_RETURN_NEXT.

◆ PG_FUNCTION_INFO_V1() [1/5]

PG_FUNCTION_INFO_V1 ( connectby_text  )

◆ PG_FUNCTION_INFO_V1() [2/5]

PG_FUNCTION_INFO_V1 ( connectby_text_serial  )

◆ PG_FUNCTION_INFO_V1() [3/5]

PG_FUNCTION_INFO_V1 ( crosstab  )

◆ PG_FUNCTION_INFO_V1() [4/5]

PG_FUNCTION_INFO_V1 ( crosstab_hash  )

◆ PG_FUNCTION_INFO_V1() [5/5]

PG_FUNCTION_INFO_V1 ( normal_rand  )

◆ PG_MODULE_MAGIC_EXT()

PG_MODULE_MAGIC_EXT ( name = "tablefunc",
version = PG_VERSION 
)

◆ validateConnectbyTupleDesc()

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

Definition at line 1408 of file tablefunc.c.

1409{
1410 int expected_cols;
1411
1412 /* are there the correct number of columns */
1413 if (show_branch)
1415 else
1417 if (show_serial)
1418 expected_cols++;
1419
1420 if (td->natts != expected_cols)
1421 ereport(ERROR,
1423 errmsg("invalid connectby return type"),
1424 errdetail("Return row must have %d columns, not %d.",
1425 expected_cols, td->natts)));
1426
1427 /* the first two columns will be checked against the input tuples later */
1428
1429 /* check that the type of the third column is INT4 */
1430 if (TupleDescAttr(td, 2)->atttypid != INT4OID)
1431 ereport(ERROR,
1433 errmsg("invalid connectby return type"),
1434 errdetail("Third return column (depth) must be type %s.",
1436
1437 /* check that the type of the branch column is TEXT if applicable */
1438 if (show_branch && TupleDescAttr(td, 3)->atttypid != TEXTOID)
1439 ereport(ERROR,
1441 errmsg("invalid connectby return type"),
1442 errdetail("Fourth return column (branch) must be type %s.",
1444
1445 /* check that the type of the serial column is INT4 if applicable */
1446 if (show_branch && show_serial &&
1447 TupleDescAttr(td, 4)->atttypid != INT4OID)
1448 ereport(ERROR,
1450 errmsg("invalid connectby return type"),
1451 errdetail("Fifth return column (serial) must be type %s.",
1453 if (!show_branch && show_serial &&
1454 TupleDescAttr(td, 3)->atttypid != INT4OID)
1455 ereport(ERROR,
1457 errmsg("invalid connectby return type"),
1458 errdetail("Fourth return column (serial) must be type %s.",
1460
1461 /* OK, the tupdesc is valid for our purposes */
1462}
char * format_type_be(Oid type_oid)

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

Referenced by connectby_text(), and connectby_text_serial().