PostgreSQL Source Code  git master
tablefunc.c
Go to the documentation of this file.
1 /*
2  * contrib/tablefunc/tablefunc.c
3  *
4  *
5  * tablefunc
6  *
7  * Sample to demonstrate C functions which return setof scalar
8  * and setof composite.
9  * Joe Conway <mail@joeconway.com>
10  * And contributors:
11  * Nabil Sayegh <postgresql@e-trolley.de>
12  *
13  * Copyright (c) 2002-2019, PostgreSQL Global Development Group
14  *
15  * Permission to use, copy, modify, and distribute this software and its
16  * documentation for any purpose, without fee, and without a written agreement
17  * is hereby granted, provided that the above copyright notice and this
18  * paragraph and the following two paragraphs appear in all copies.
19  *
20  * IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
21  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
22  * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
23  * DOCUMENTATION, EVEN IF THE AUTHOR OR DISTRIBUTORS HAVE BEEN ADVISED OF THE
24  * POSSIBILITY OF SUCH DAMAGE.
25  *
26  * THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
27  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
28  * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
29  * ON AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAS NO OBLIGATIONS TO
30  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
31  *
32  */
33 #include "postgres.h"
34 
35 #include <math.h>
36 
37 #include "access/htup_details.h"
38 #include "catalog/pg_type.h"
39 #include "executor/spi.h"
40 #include "funcapi.h"
41 #include "lib/stringinfo.h"
42 #include "miscadmin.h"
43 #include "utils/builtins.h"
44 
45 #include "tablefunc.h"
46 
48 
49 static HTAB *load_categories_hash(char *cats_sql, MemoryContext per_query_ctx);
52  TupleDesc tupdesc,
53  MemoryContext per_query_ctx,
54  bool randomAccess);
55 static void validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial);
56 static bool compatCrosstabTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2);
57 static void compatConnectbyTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2);
58 static void get_normal_pair(float8 *x1, float8 *x2);
59 static Tuplestorestate *connectby(char *relname,
60  char *key_fld,
61  char *parent_key_fld,
62  char *orderby_fld,
63  char *branch_delim,
64  char *start_with,
65  int max_depth,
66  bool show_branch,
67  bool show_serial,
68  MemoryContext per_query_ctx,
69  bool randomAccess,
70  AttInMetadata *attinmeta);
71 static void build_tuplestore_recursively(char *key_fld,
72  char *parent_key_fld,
73  char *relname,
74  char *orderby_fld,
75  char *branch_delim,
76  char *start_with,
77  char *branch,
78  int level,
79  int *serial,
80  int max_depth,
81  bool show_branch,
82  bool show_serial,
83  MemoryContext per_query_ctx,
84  AttInMetadata *attinmeta,
85  Tuplestorestate *tupstore);
86 
87 typedef struct
88 {
89  float8 mean; /* mean of the distribution */
90  float8 stddev; /* stddev of the distribution */
91  float8 carry_val; /* hold second generated value */
92  bool use_carry; /* use second generated value */
94 
95 #define xpfree(var_) \
96  do { \
97  if (var_ != NULL) \
98  { \
99  pfree(var_); \
100  var_ = NULL; \
101  } \
102  } while (0)
103 
104 #define xpstrdup(tgtvar_, srcvar_) \
105  do { \
106  if (srcvar_) \
107  tgtvar_ = pstrdup(srcvar_); \
108  else \
109  tgtvar_ = NULL; \
110  } while (0)
111 
112 #define xstreq(tgtvar_, srcvar_) \
113  (((tgtvar_ == NULL) && (srcvar_ == NULL)) || \
114  ((tgtvar_ != NULL) && (srcvar_ != NULL) && (strcmp(tgtvar_, srcvar_) == 0)))
115 
116 /* sign, 10 digits, '\0' */
117 #define INT32_STRLEN 12
118 
119 /* stored info for a crosstab category */
120 typedef struct crosstab_cat_desc
121 {
122  char *catname; /* full category name */
123  uint64 attidx; /* zero based */
125 
126 #define MAX_CATNAME_LEN NAMEDATALEN
127 #define INIT_CATS 64
128 
129 #define crosstab_HashTableLookup(HASHTAB, CATNAME, CATDESC) \
130 do { \
131  crosstab_HashEnt *hentry; char key[MAX_CATNAME_LEN]; \
132  \
133  MemSet(key, 0, MAX_CATNAME_LEN); \
134  snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATNAME); \
135  hentry = (crosstab_HashEnt*) hash_search(HASHTAB, \
136  key, HASH_FIND, NULL); \
137  if (hentry) \
138  CATDESC = hentry->catdesc; \
139  else \
140  CATDESC = NULL; \
141 } while(0)
142 
143 #define crosstab_HashTableInsert(HASHTAB, CATDESC) \
144 do { \
145  crosstab_HashEnt *hentry; bool found; char key[MAX_CATNAME_LEN]; \
146  \
147  MemSet(key, 0, MAX_CATNAME_LEN); \
148  snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATDESC->catname); \
149  hentry = (crosstab_HashEnt*) hash_search(HASHTAB, \
150  key, HASH_ENTER, &found); \
151  if (found) \
152  ereport(ERROR, \
153  (errcode(ERRCODE_DUPLICATE_OBJECT), \
154  errmsg("duplicate category name"))); \
155  hentry->catdesc = CATDESC; \
156 } while(0)
157 
158 /* hash table */
159 typedef struct crosstab_hashent
160 {
161  char internal_catname[MAX_CATNAME_LEN];
164 
165 /*
166  * normal_rand - return requested number of random values
167  * with a Gaussian (Normal) distribution.
168  *
169  * inputs are int numvals, float8 mean, and float8 stddev
170  * returns setof float8
171  */
173 Datum
175 {
176  FuncCallContext *funcctx;
177  uint64 call_cntr;
178  uint64 max_calls;
179  normal_rand_fctx *fctx;
180  float8 mean;
181  float8 stddev;
182  float8 carry_val;
183  bool use_carry;
184  MemoryContext oldcontext;
185 
186  /* stuff done only on the first call of the function */
187  if (SRF_IS_FIRSTCALL())
188  {
189  /* create a function context for cross-call persistence */
190  funcctx = SRF_FIRSTCALL_INIT();
191 
192  /*
193  * switch to memory context appropriate for multiple function calls
194  */
195  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
196 
197  /* total number of tuples to be returned */
198  funcctx->max_calls = PG_GETARG_UINT32(0);
199 
200  /* allocate memory for user context */
201  fctx = (normal_rand_fctx *) palloc(sizeof(normal_rand_fctx));
202 
203  /*
204  * Use fctx to keep track of upper and lower bounds from call to call.
205  * It will also be used to carry over the spare value we get from the
206  * Box-Muller algorithm so that we only actually calculate a new value
207  * every other call.
208  */
209  fctx->mean = PG_GETARG_FLOAT8(1);
210  fctx->stddev = PG_GETARG_FLOAT8(2);
211  fctx->carry_val = 0;
212  fctx->use_carry = false;
213 
214  funcctx->user_fctx = fctx;
215 
216  MemoryContextSwitchTo(oldcontext);
217  }
218 
219  /* stuff done on every call of the function */
220  funcctx = SRF_PERCALL_SETUP();
221 
222  call_cntr = funcctx->call_cntr;
223  max_calls = funcctx->max_calls;
224  fctx = funcctx->user_fctx;
225  mean = fctx->mean;
226  stddev = fctx->stddev;
227  carry_val = fctx->carry_val;
228  use_carry = fctx->use_carry;
229 
230  if (call_cntr < max_calls) /* do when there is more left to send */
231  {
232  float8 result;
233 
234  if (use_carry)
235  {
236  /*
237  * reset use_carry and use second value obtained on last pass
238  */
239  fctx->use_carry = false;
240  result = carry_val;
241  }
242  else
243  {
244  float8 normval_1;
245  float8 normval_2;
246 
247  /* Get the next two normal values */
248  get_normal_pair(&normval_1, &normval_2);
249 
250  /* use the first */
251  result = mean + (stddev * normval_1);
252 
253  /* and save the second */
254  fctx->carry_val = mean + (stddev * normval_2);
255  fctx->use_carry = true;
256  }
257 
258  /* send the result */
259  SRF_RETURN_NEXT(funcctx, Float8GetDatum(result));
260  }
261  else
262  /* do when there is no more left */
263  SRF_RETURN_DONE(funcctx);
264 }
265 
266 /*
267  * get_normal_pair()
268  * Assigns normally distributed (Gaussian) values to a pair of provided
269  * parameters, with mean 0, standard deviation 1.
270  *
271  * This routine implements Algorithm P (Polar method for normal deviates)
272  * from Knuth's _The_Art_of_Computer_Programming_, Volume 2, 3rd ed., pages
273  * 122-126. Knuth cites his source as "The polar method", G. E. P. Box, M. E.
274  * Muller, and G. Marsaglia, _Annals_Math,_Stat._ 29 (1958), 610-611.
275  *
276  */
277 static void
279 {
280  float8 u1,
281  u2,
282  v1,
283  v2,
284  s;
285 
286  do
287  {
288  u1 = (float8) random() / (float8) MAX_RANDOM_VALUE;
289  u2 = (float8) random() / (float8) MAX_RANDOM_VALUE;
290 
291  v1 = (2.0 * u1) - 1.0;
292  v2 = (2.0 * u2) - 1.0;
293 
294  s = v1 * v1 + v2 * v2;
295  } while (s >= 1.0);
296 
297  if (s == 0)
298  {
299  *x1 = 0;
300  *x2 = 0;
301  }
302  else
303  {
304  s = sqrt((-2.0 * log(s)) / s);
305  *x1 = v1 * s;
306  *x2 = v2 * s;
307  }
308 }
309 
310 /*
311  * crosstab - create a crosstab of rowids and values columns from a
312  * SQL statement returning one rowid column, one category column,
313  * and one value column.
314  *
315  * e.g. given sql which produces:
316  *
317  * rowid cat value
318  * ------+-------+-------
319  * row1 cat1 val1
320  * row1 cat2 val2
321  * row1 cat3 val3
322  * row1 cat4 val4
323  * row2 cat1 val5
324  * row2 cat2 val6
325  * row2 cat3 val7
326  * row2 cat4 val8
327  *
328  * crosstab returns:
329  * <===== values columns =====>
330  * rowid cat1 cat2 cat3 cat4
331  * ------+-------+-------+-------+-------
332  * row1 val1 val2 val3 val4
333  * row2 val5 val6 val7 val8
334  *
335  * NOTES:
336  * 1. SQL result must be ordered by 1,2.
337  * 2. The number of values columns depends on the tuple description
338  * of the function's declared return type. The return type's columns
339  * must match the datatypes of the SQL query's result. The datatype
340  * of the category column can be anything, however.
341  * 3. Missing values (i.e. not enough adjacent rows of same rowid to
342  * fill the number of result values columns) are filled in with nulls.
343  * 4. Extra values (i.e. too many adjacent rows of same rowid to fill
344  * the number of result values columns) are skipped.
345  * 5. Rows with all nulls in the values columns are skipped.
346  */
348 Datum
350 {
351  char *sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
352  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
353  Tuplestorestate *tupstore;
354  TupleDesc tupdesc;
355  uint64 call_cntr;
356  uint64 max_calls;
357  AttInMetadata *attinmeta;
358  SPITupleTable *spi_tuptable;
359  TupleDesc spi_tupdesc;
360  bool firstpass;
361  char *lastrowid;
362  int i;
363  int num_categories;
364  MemoryContext per_query_ctx;
365  MemoryContext oldcontext;
366  int ret;
367  uint64 proc;
368 
369  /* check to see if caller supports us returning a tuplestore */
370  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
371  ereport(ERROR,
372  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
373  errmsg("set-valued function called in context that cannot accept a set")));
374  if (!(rsinfo->allowedModes & SFRM_Materialize))
375  ereport(ERROR,
376  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
377  errmsg("materialize mode required, but it is not " \
378  "allowed in this context")));
379 
380  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
381 
382  /* Connect to SPI manager */
383  if ((ret = SPI_connect()) < 0)
384  /* internal error */
385  elog(ERROR, "crosstab: SPI_connect returned %d", ret);
386 
387  /* Retrieve the desired rows */
388  ret = SPI_execute(sql, true, 0);
389  proc = SPI_processed;
390 
391  /* If no qualifying tuples, fall out early */
392  if (ret != SPI_OK_SELECT || proc == 0)
393  {
394  SPI_finish();
395  rsinfo->isDone = ExprEndResult;
396  PG_RETURN_NULL();
397  }
398 
399  spi_tuptable = SPI_tuptable;
400  spi_tupdesc = spi_tuptable->tupdesc;
401 
402  /*----------
403  * The provided SQL query must always return three columns.
404  *
405  * 1. rowname
406  * the label or identifier for each row in the final result
407  * 2. category
408  * the label or identifier for each column in the final result
409  * 3. values
410  * the value for each column in the final result
411  *----------
412  */
413  if (spi_tupdesc->natts != 3)
414  ereport(ERROR,
415  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
416  errmsg("invalid source data SQL statement"),
417  errdetail("The provided SQL must return 3 "
418  "columns: rowid, category, and values.")));
419 
420  /* get a tuple descriptor for our result type */
421  switch (get_call_result_type(fcinfo, NULL, &tupdesc))
422  {
423  case TYPEFUNC_COMPOSITE:
424  /* success */
425  break;
426  case TYPEFUNC_RECORD:
427  /* failed to determine actual type of RECORD */
428  ereport(ERROR,
429  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
430  errmsg("function returning record called in context "
431  "that cannot accept type record")));
432  break;
433  default:
434  /* result type isn't composite */
435  ereport(ERROR,
436  (errcode(ERRCODE_DATATYPE_MISMATCH),
437  errmsg("return type must be a row type")));
438  break;
439  }
440 
441  /*
442  * Check that return tupdesc is compatible with the data we got from SPI,
443  * at least based on number and type of attributes
444  */
445  if (!compatCrosstabTupleDescs(tupdesc, spi_tupdesc))
446  ereport(ERROR,
447  (errcode(ERRCODE_SYNTAX_ERROR),
448  errmsg("return and sql tuple descriptions are " \
449  "incompatible")));
450 
451  /*
452  * switch to long-lived memory context
453  */
454  oldcontext = MemoryContextSwitchTo(per_query_ctx);
455 
456  /* make sure we have a persistent copy of the result tupdesc */
457  tupdesc = CreateTupleDescCopy(tupdesc);
458 
459  /* initialize our tuplestore in long-lived context */
460  tupstore =
462  false, work_mem);
463 
464  MemoryContextSwitchTo(oldcontext);
465 
466  /*
467  * Generate attribute metadata needed later to produce tuples from raw C
468  * strings
469  */
470  attinmeta = TupleDescGetAttInMetadata(tupdesc);
471 
472  /* total number of tuples to be examined */
473  max_calls = proc;
474 
475  /* the return tuple always must have 1 rowid + num_categories columns */
476  num_categories = tupdesc->natts - 1;
477 
478  firstpass = true;
479  lastrowid = NULL;
480 
481  for (call_cntr = 0; call_cntr < max_calls; call_cntr++)
482  {
483  bool skip_tuple = false;
484  char **values;
485 
486  /* allocate and zero space */
487  values = (char **) palloc0((1 + num_categories) * sizeof(char *));
488 
489  /*
490  * now loop through the sql results and assign each value in sequence
491  * to the next category
492  */
493  for (i = 0; i < num_categories; i++)
494  {
495  HeapTuple spi_tuple;
496  char *rowid;
497 
498  /* see if we've gone too far already */
499  if (call_cntr >= max_calls)
500  break;
501 
502  /* get the next sql result tuple */
503  spi_tuple = spi_tuptable->vals[call_cntr];
504 
505  /* get the rowid from the current sql result tuple */
506  rowid = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
507 
508  /*
509  * If this is the first pass through the values for this rowid,
510  * set the first column to rowid
511  */
512  if (i == 0)
513  {
514  xpstrdup(values[0], rowid);
515 
516  /*
517  * Check to see if the rowid is the same as that of the last
518  * tuple sent -- if so, skip this tuple entirely
519  */
520  if (!firstpass && xstreq(lastrowid, rowid))
521  {
522  xpfree(rowid);
523  skip_tuple = true;
524  break;
525  }
526  }
527 
528  /*
529  * If rowid hasn't changed on us, continue building the output
530  * tuple.
531  */
532  if (xstreq(rowid, values[0]))
533  {
534  /*
535  * Get the next category item value, which is always attribute
536  * number three.
537  *
538  * Be careful to assign the value to the array index based on
539  * which category we are presently processing.
540  */
541  values[1 + i] = SPI_getvalue(spi_tuple, spi_tupdesc, 3);
542 
543  /*
544  * increment the counter since we consume a row for each
545  * category, but not for last pass because the outer loop will
546  * do that for us
547  */
548  if (i < (num_categories - 1))
549  call_cntr++;
550  xpfree(rowid);
551  }
552  else
553  {
554  /*
555  * We'll fill in NULLs for the missing values, but we need to
556  * decrement the counter since this sql result row doesn't
557  * belong to the current output tuple.
558  */
559  call_cntr--;
560  xpfree(rowid);
561  break;
562  }
563  }
564 
565  if (!skip_tuple)
566  {
567  HeapTuple tuple;
568 
569  /* build the tuple and store it */
570  tuple = BuildTupleFromCStrings(attinmeta, values);
571  tuplestore_puttuple(tupstore, tuple);
572  heap_freetuple(tuple);
573  }
574 
575  /* Remember current rowid */
576  xpfree(lastrowid);
577  xpstrdup(lastrowid, values[0]);
578  firstpass = false;
579 
580  /* Clean up */
581  for (i = 0; i < num_categories + 1; i++)
582  if (values[i] != NULL)
583  pfree(values[i]);
584  pfree(values);
585  }
586 
587  /* let the caller know we're sending back a tuplestore */
588  rsinfo->returnMode = SFRM_Materialize;
589  rsinfo->setResult = tupstore;
590  rsinfo->setDesc = tupdesc;
591 
592  /* release SPI related resources (and return to caller's context) */
593  SPI_finish();
594 
595  return (Datum) 0;
596 }
597 
598 /*
599  * crosstab_hash - reimplement crosstab as materialized function and
600  * properly deal with missing values (i.e. don't pack remaining
601  * values to the left)
602  *
603  * crosstab - create a crosstab of rowids and values columns from a
604  * SQL statement returning one rowid column, one category column,
605  * and one value column.
606  *
607  * e.g. given sql which produces:
608  *
609  * rowid cat value
610  * ------+-------+-------
611  * row1 cat1 val1
612  * row1 cat2 val2
613  * row1 cat4 val4
614  * row2 cat1 val5
615  * row2 cat2 val6
616  * row2 cat3 val7
617  * row2 cat4 val8
618  *
619  * crosstab returns:
620  * <===== values columns =====>
621  * rowid cat1 cat2 cat3 cat4
622  * ------+-------+-------+-------+-------
623  * row1 val1 val2 null val4
624  * row2 val5 val6 val7 val8
625  *
626  * NOTES:
627  * 1. SQL result must be ordered by 1.
628  * 2. The number of values columns depends on the tuple description
629  * of the function's declared return type.
630  * 3. Missing values (i.e. missing category) are filled in with nulls.
631  * 4. Extra values (i.e. not in category results) are skipped.
632  */
634 Datum
636 {
637  char *sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
638  char *cats_sql = text_to_cstring(PG_GETARG_TEXT_PP(1));
639  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
640  TupleDesc tupdesc;
641  MemoryContext per_query_ctx;
642  MemoryContext oldcontext;
644 
645  /* check to see if caller supports us returning a tuplestore */
646  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
647  ereport(ERROR,
648  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
649  errmsg("set-valued function called in context that cannot accept a set")));
650  if (!(rsinfo->allowedModes & SFRM_Materialize) ||
651  rsinfo->expectedDesc == NULL)
652  ereport(ERROR,
653  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
654  errmsg("materialize mode required, but it is not " \
655  "allowed in this context")));
656 
657  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
658  oldcontext = MemoryContextSwitchTo(per_query_ctx);
659 
660  /* get the requested return tuple description */
661  tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
662 
663  /*
664  * Check to make sure we have a reasonable tuple descriptor
665  *
666  * Note we will attempt to coerce the values into whatever the return
667  * attribute type is and depend on the "in" function to complain if
668  * needed.
669  */
670  if (tupdesc->natts < 2)
671  ereport(ERROR,
672  (errcode(ERRCODE_SYNTAX_ERROR),
673  errmsg("query-specified return tuple and " \
674  "crosstab function are not compatible")));
675 
676  /* load up the categories hash table */
677  crosstab_hash = load_categories_hash(cats_sql, per_query_ctx);
678 
679  /* let the caller know we're sending back a tuplestore */
680  rsinfo->returnMode = SFRM_Materialize;
681 
682  /* now go build it */
683  rsinfo->setResult = get_crosstab_tuplestore(sql,
685  tupdesc,
686  per_query_ctx,
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 }
701 
702 /*
703  * load up the categories hash table
704  */
705 static HTAB *
706 load_categories_hash(char *cats_sql, MemoryContext per_query_ctx)
707 {
709  HASHCTL ctl;
710  int ret;
711  uint64 proc;
712  MemoryContext SPIcontext;
713 
714  /* initialize the category hash table */
715  MemSet(&ctl, 0, sizeof(ctl));
716  ctl.keysize = MAX_CATNAME_LEN;
717  ctl.entrysize = sizeof(crosstab_HashEnt);
718  ctl.hcxt = per_query_ctx;
719 
720  /*
721  * use INIT_CATS, defined above as a guess of how many hash table entries
722  * to create, initially
723  */
724  crosstab_hash = hash_create("crosstab hash",
725  INIT_CATS,
726  &ctl,
728 
729  /* Connect to SPI manager */
730  if ((ret = SPI_connect()) < 0)
731  /* internal error */
732  elog(ERROR, "load_categories_hash: SPI_connect returned %d", ret);
733 
734  /* Retrieve the category name rows */
735  ret = SPI_execute(cats_sql, true, 0);
736  proc = SPI_processed;
737 
738  /* Check for qualifying tuples */
739  if ((ret == SPI_OK_SELECT) && (proc > 0))
740  {
741  SPITupleTable *spi_tuptable = SPI_tuptable;
742  TupleDesc spi_tupdesc = spi_tuptable->tupdesc;
743  uint64 i;
744 
745  /*
746  * The provided categories SQL query must always return one column:
747  * category - the label or identifier for each column
748  */
749  if (spi_tupdesc->natts != 1)
750  ereport(ERROR,
751  (errcode(ERRCODE_SYNTAX_ERROR),
752  errmsg("provided \"categories\" SQL must " \
753  "return 1 column of at least one row")));
754 
755  for (i = 0; i < proc; i++)
756  {
757  crosstab_cat_desc *catdesc;
758  char *catname;
759  HeapTuple spi_tuple;
760 
761  /* get the next sql result tuple */
762  spi_tuple = spi_tuptable->vals[i];
763 
764  /* get the category from the current sql result tuple */
765  catname = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
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 }
786 
787 /*
788  * create and populate the crosstab tuplestore using the provided source query
789  */
790 static Tuplestorestate *
793  TupleDesc tupdesc,
794  MemoryContext per_query_ctx,
795  bool randomAccess)
796 {
797  Tuplestorestate *tupstore;
798  int num_categories = hash_get_num_entries(crosstab_hash);
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  if ((ret = SPI_connect()) < 0)
810  /* internal error */
811  elog(ERROR, "get_crosstab_tuplestore: SPI_connect returned %d", ret);
812 
813  /* Now retrieve the crosstab source rows */
814  ret = SPI_execute(sql, true, 0);
815  proc = SPI_processed;
816 
817  /* Check for qualifying tuples */
818  if ((ret == SPI_OK_SELECT) && (proc > 0))
819  {
820  SPITupleTable *spi_tuptable = SPI_tuptable;
821  TupleDesc spi_tupdesc = spi_tuptable->tupdesc;
822  int ncols = spi_tupdesc->natts;
823  char *rowid;
824  char *lastrowid = NULL;
825  bool firstpass = true;
826  uint64 i;
827  int j;
828  int result_ncols;
829 
830  if (num_categories == 0)
831  {
832  /* no qualifying category tuples */
833  ereport(ERROR,
834  (errcode(ERRCODE_SYNTAX_ERROR),
835  errmsg("provided \"categories\" SQL must " \
836  "return 1 column of at least one row")));
837  }
838 
839  /*
840  * The provided SQL query must always return at least three columns:
841  *
842  * 1. rowname the label for each row - column 1 in the final result
843  * 2. category the label for each value-column in the final result 3.
844  * value the values used to populate the value-columns
845  *
846  * If there are more than three columns, the last two are taken as
847  * "category" and "values". The first column is taken as "rowname".
848  * Additional columns (2 thru N-2) are assumed the same for the same
849  * "rowname", and are copied into the result tuple from the first time
850  * we encounter a particular rowname.
851  */
852  if (ncols < 3)
853  ereport(ERROR,
854  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
855  errmsg("invalid source data SQL statement"),
856  errdetail("The provided SQL must return 3 " \
857  " columns; rowid, category, and values.")));
858 
859  result_ncols = (ncols - 2) + num_categories;
860 
861  /* Recheck to make sure we tuple descriptor still looks reasonable */
862  if (tupdesc->natts != result_ncols)
863  ereport(ERROR,
864  (errcode(ERRCODE_SYNTAX_ERROR),
865  errmsg("invalid return type"),
866  errdetail("Query-specified return " \
867  "tuple has %d columns but crosstab " \
868  "returns %d.", tupdesc->natts, result_ncols)));
869 
870  /* allocate space and make sure it's clear */
871  values = (char **) palloc0(result_ncols * sizeof(char *));
872 
873  for (i = 0; i < proc; i++)
874  {
875  HeapTuple spi_tuple;
876  crosstab_cat_desc *catdesc;
877  char *catname;
878 
879  /* get the next sql result tuple */
880  spi_tuple = spi_tuptable->vals[i];
881 
882  /* get the rowid from the current sql result tuple */
883  rowid = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
884 
885  /*
886  * if we're on a new output row, grab the column values up to
887  * column N-2 now
888  */
889  if (firstpass || !xstreq(lastrowid, rowid))
890  {
891  /*
892  * a new row means we need to flush the old one first, unless
893  * we're on the very first row
894  */
895  if (!firstpass)
896  {
897  /* rowid changed, flush the previous output row */
898  tuple = BuildTupleFromCStrings(attinmeta, values);
899 
900  tuplestore_puttuple(tupstore, tuple);
901 
902  for (j = 0; j < result_ncols; j++)
903  xpfree(values[j]);
904  }
905 
906  values[0] = rowid;
907  for (j = 1; j < ncols - 2; j++)
908  values[j] = SPI_getvalue(spi_tuple, spi_tupdesc, j + 1);
909 
910  /* we're no longer on the first pass */
911  firstpass = false;
912  }
913 
914  /* look up the category and fill in the appropriate column */
915  catname = SPI_getvalue(spi_tuple, spi_tupdesc, ncols - 1);
916 
917  if (catname != NULL)
918  {
919  crosstab_HashTableLookup(crosstab_hash, catname, catdesc);
920 
921  if (catdesc)
922  values[catdesc->attidx + ncols - 2] =
923  SPI_getvalue(spi_tuple, spi_tupdesc, ncols);
924  }
925 
926  xpfree(lastrowid);
927  xpstrdup(lastrowid, rowid);
928  }
929 
930  /* flush the last output row */
931  tuple = BuildTupleFromCStrings(attinmeta, values);
932 
933  tuplestore_puttuple(tupstore, tuple);
934  }
935 
936  if (SPI_finish() != SPI_OK_FINISH)
937  /* internal error */
938  elog(ERROR, "get_crosstab_tuplestore: SPI_finish() failed");
939 
940  tuplestore_donestoring(tupstore);
941 
942  return tupstore;
943 }
944 
945 /*
946  * connectby_text - produce a result set from a hierarchical (parent/child)
947  * table.
948  *
949  * e.g. given table foo:
950  *
951  * keyid parent_keyid pos
952  * ------+------------+--
953  * row1 NULL 0
954  * row2 row1 0
955  * row3 row1 0
956  * row4 row2 1
957  * row5 row2 0
958  * row6 row4 0
959  * row7 row3 0
960  * row8 row6 0
961  * row9 row5 0
962  *
963  *
964  * connectby(text relname, text keyid_fld, text parent_keyid_fld
965  * [, text orderby_fld], text start_with, int max_depth
966  * [, text branch_delim])
967  * connectby('foo', 'keyid', 'parent_keyid', 'pos', 'row2', 0, '~') returns:
968  *
969  * keyid parent_id level branch serial
970  * ------+-----------+--------+-----------------------
971  * row2 NULL 0 row2 1
972  * row5 row2 1 row2~row5 2
973  * row9 row5 2 row2~row5~row9 3
974  * row4 row2 1 row2~row4 4
975  * row6 row4 2 row2~row4~row6 5
976  * row8 row6 3 row2~row4~row6~row8 6
977  *
978  */
980 
981 #define CONNECTBY_NCOLS 4
982 #define CONNECTBY_NCOLS_NOBRANCH 3
983 
984 Datum
986 {
988  char *key_fld = text_to_cstring(PG_GETARG_TEXT_PP(1));
989  char *parent_key_fld = text_to_cstring(PG_GETARG_TEXT_PP(2));
990  char *start_with = text_to_cstring(PG_GETARG_TEXT_PP(3));
991  int max_depth = PG_GETARG_INT32(4);
992  char *branch_delim = NULL;
993  bool show_branch = false;
994  bool show_serial = false;
995  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
996  TupleDesc tupdesc;
997  AttInMetadata *attinmeta;
998  MemoryContext per_query_ctx;
999  MemoryContext oldcontext;
1000 
1001  /* check to see if caller supports us returning a tuplestore */
1002  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1003  ereport(ERROR,
1004  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1005  errmsg("set-valued function called in context that cannot accept a set")));
1006  if (!(rsinfo->allowedModes & SFRM_Materialize) ||
1007  rsinfo->expectedDesc == NULL)
1008  ereport(ERROR,
1009  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1010  errmsg("materialize mode required, but it is not " \
1011  "allowed in this context")));
1012 
1013  if (fcinfo->nargs == 6)
1014  {
1015  branch_delim = text_to_cstring(PG_GETARG_TEXT_PP(5));
1016  show_branch = true;
1017  }
1018  else
1019  /* default is no show, tilde for the delimiter */
1020  branch_delim = pstrdup("~");
1021 
1022  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1023  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1024 
1025  /* get the requested return tuple description */
1026  tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1027 
1028  /* does it meet our needs */
1029  validateConnectbyTupleDesc(tupdesc, show_branch, show_serial);
1030 
1031  /* OK, use it then */
1032  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1033 
1034  /* OK, go to work */
1035  rsinfo->returnMode = SFRM_Materialize;
1036  rsinfo->setResult = connectby(relname,
1037  key_fld,
1038  parent_key_fld,
1039  NULL,
1040  branch_delim,
1041  start_with,
1042  max_depth,
1043  show_branch,
1044  show_serial,
1045  per_query_ctx,
1047  attinmeta);
1048  rsinfo->setDesc = tupdesc;
1049 
1050  MemoryContextSwitchTo(oldcontext);
1051 
1052  /*
1053  * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1054  * tuples are in our tuplestore and passed back through rsinfo->setResult.
1055  * rsinfo->setDesc is set to the tuple description that we actually used
1056  * to build our tuples with, so the caller can verify we did what it was
1057  * expecting.
1058  */
1059  return (Datum) 0;
1060 }
1061 
1063 Datum
1065 {
1067  char *key_fld = text_to_cstring(PG_GETARG_TEXT_PP(1));
1068  char *parent_key_fld = text_to_cstring(PG_GETARG_TEXT_PP(2));
1069  char *orderby_fld = text_to_cstring(PG_GETARG_TEXT_PP(3));
1070  char *start_with = text_to_cstring(PG_GETARG_TEXT_PP(4));
1071  int max_depth = PG_GETARG_INT32(5);
1072  char *branch_delim = NULL;
1073  bool show_branch = false;
1074  bool show_serial = true;
1075  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1076  TupleDesc tupdesc;
1077  AttInMetadata *attinmeta;
1078  MemoryContext per_query_ctx;
1079  MemoryContext oldcontext;
1080 
1081  /* check to see if caller supports us returning a tuplestore */
1082  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1083  ereport(ERROR,
1084  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1085  errmsg("set-valued function called in context that cannot accept a set")));
1086  if (!(rsinfo->allowedModes & SFRM_Materialize) ||
1087  rsinfo->expectedDesc == NULL)
1088  ereport(ERROR,
1089  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1090  errmsg("materialize mode required, but it is not " \
1091  "allowed in this context")));
1092 
1093  if (fcinfo->nargs == 7)
1094  {
1095  branch_delim = text_to_cstring(PG_GETARG_TEXT_PP(6));
1096  show_branch = true;
1097  }
1098  else
1099  /* default is no show, tilde for the delimiter */
1100  branch_delim = pstrdup("~");
1101 
1102  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1103  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1104 
1105  /* get the requested return tuple description */
1106  tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1107 
1108  /* does it meet our needs */
1109  validateConnectbyTupleDesc(tupdesc, show_branch, show_serial);
1110 
1111  /* OK, use it then */
1112  attinmeta = TupleDescGetAttInMetadata(tupdesc);
1113 
1114  /* OK, go to work */
1115  rsinfo->returnMode = SFRM_Materialize;
1116  rsinfo->setResult = connectby(relname,
1117  key_fld,
1118  parent_key_fld,
1119  orderby_fld,
1120  branch_delim,
1121  start_with,
1122  max_depth,
1123  show_branch,
1124  show_serial,
1125  per_query_ctx,
1127  attinmeta);
1128  rsinfo->setDesc = tupdesc;
1129 
1130  MemoryContextSwitchTo(oldcontext);
1131 
1132  /*
1133  * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1134  * tuples are in our tuplestore and passed back through rsinfo->setResult.
1135  * rsinfo->setDesc is set to the tuple description that we actually used
1136  * to build our tuples with, so the caller can verify we did what it was
1137  * expecting.
1138  */
1139  return (Datum) 0;
1140 }
1141 
1142 
1143 /*
1144  * connectby - does the real work for connectby_text()
1145  */
1146 static Tuplestorestate *
1148  char *key_fld,
1149  char *parent_key_fld,
1150  char *orderby_fld,
1151  char *branch_delim,
1152  char *start_with,
1153  int max_depth,
1154  bool show_branch,
1155  bool show_serial,
1156  MemoryContext per_query_ctx,
1157  bool randomAccess,
1158  AttInMetadata *attinmeta)
1159 {
1160  Tuplestorestate *tupstore = NULL;
1161  int ret;
1162  MemoryContext oldcontext;
1163 
1164  int serial = 1;
1165 
1166  /* Connect to SPI manager */
1167  if ((ret = SPI_connect()) < 0)
1168  /* internal error */
1169  elog(ERROR, "connectby: SPI_connect returned %d", ret);
1170 
1171  /* switch to longer term context to create the tuple store */
1172  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1173 
1174  /* initialize our tuplestore */
1175  tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
1176 
1177  MemoryContextSwitchTo(oldcontext);
1178 
1179  /* now go get the whole tree */
1181  parent_key_fld,
1182  relname,
1183  orderby_fld,
1184  branch_delim,
1185  start_with,
1186  start_with, /* current_branch */
1187  0, /* initial level is 0 */
1188  &serial, /* initial serial is 1 */
1189  max_depth,
1190  show_branch,
1191  show_serial,
1192  per_query_ctx,
1193  attinmeta,
1194  tupstore);
1195 
1196  SPI_finish();
1197 
1198  return tupstore;
1199 }
1200 
1201 static void
1203  char *parent_key_fld,
1204  char *relname,
1205  char *orderby_fld,
1206  char *branch_delim,
1207  char *start_with,
1208  char *branch,
1209  int level,
1210  int *serial,
1211  int max_depth,
1212  bool show_branch,
1213  bool show_serial,
1214  MemoryContext per_query_ctx,
1215  AttInMetadata *attinmeta,
1216  Tuplestorestate *tupstore)
1217 {
1218  TupleDesc tupdesc = attinmeta->tupdesc;
1219  int ret;
1220  uint64 proc;
1221  int serial_column;
1222  StringInfoData sql;
1223  char **values;
1224  char *current_key;
1225  char *current_key_parent;
1226  char current_level[INT32_STRLEN];
1227  char serial_str[INT32_STRLEN];
1228  char *current_branch;
1229  HeapTuple tuple;
1230 
1231  if (max_depth > 0 && level > max_depth)
1232  return;
1233 
1234  initStringInfo(&sql);
1235 
1236  /* Build initial sql statement */
1237  if (!show_serial)
1238  {
1239  appendStringInfo(&sql, "SELECT %s, %s FROM %s WHERE %s = %s AND %s IS NOT NULL AND %s <> %s",
1240  key_fld,
1241  parent_key_fld,
1242  relname,
1243  parent_key_fld,
1244  quote_literal_cstr(start_with),
1245  key_fld, key_fld, parent_key_fld);
1246  serial_column = 0;
1247  }
1248  else
1249  {
1250  appendStringInfo(&sql, "SELECT %s, %s FROM %s WHERE %s = %s AND %s IS NOT NULL AND %s <> %s ORDER BY %s",
1251  key_fld,
1252  parent_key_fld,
1253  relname,
1254  parent_key_fld,
1255  quote_literal_cstr(start_with),
1256  key_fld, key_fld, parent_key_fld,
1257  orderby_fld);
1258  serial_column = 1;
1259  }
1260 
1261  if (show_branch)
1262  values = (char **) palloc((CONNECTBY_NCOLS + serial_column) * sizeof(char *));
1263  else
1264  values = (char **) palloc((CONNECTBY_NCOLS_NOBRANCH + serial_column) * sizeof(char *));
1265 
1266  /* First time through, do a little setup */
1267  if (level == 0)
1268  {
1269  /* root value is the one we initially start with */
1270  values[0] = start_with;
1271 
1272  /* root value has no parent */
1273  values[1] = NULL;
1274 
1275  /* root level is 0 */
1276  sprintf(current_level, "%d", level);
1277  values[2] = current_level;
1278 
1279  /* root branch is just starting root value */
1280  if (show_branch)
1281  values[3] = start_with;
1282 
1283  /* root starts the serial with 1 */
1284  if (show_serial)
1285  {
1286  sprintf(serial_str, "%d", (*serial)++);
1287  if (show_branch)
1288  values[4] = serial_str;
1289  else
1290  values[3] = serial_str;
1291  }
1292 
1293  /* construct the tuple */
1294  tuple = BuildTupleFromCStrings(attinmeta, values);
1295 
1296  /* now store it */
1297  tuplestore_puttuple(tupstore, tuple);
1298 
1299  /* increment level */
1300  level++;
1301  }
1302 
1303  /* Retrieve the desired rows */
1304  ret = SPI_execute(sql.data, true, 0);
1305  proc = SPI_processed;
1306 
1307  /* Check for qualifying tuples */
1308  if ((ret == SPI_OK_SELECT) && (proc > 0))
1309  {
1310  HeapTuple spi_tuple;
1311  SPITupleTable *tuptable = SPI_tuptable;
1312  TupleDesc spi_tupdesc = tuptable->tupdesc;
1313  uint64 i;
1314  StringInfoData branchstr;
1315  StringInfoData chk_branchstr;
1316  StringInfoData chk_current_key;
1317 
1318  /*
1319  * Check that return tupdesc is compatible with the one we got from
1320  * the query.
1321  */
1322  compatConnectbyTupleDescs(tupdesc, spi_tupdesc);
1323 
1324  initStringInfo(&branchstr);
1325  initStringInfo(&chk_branchstr);
1326  initStringInfo(&chk_current_key);
1327 
1328  for (i = 0; i < proc; i++)
1329  {
1330  /* initialize branch for this pass */
1331  appendStringInfoString(&branchstr, branch);
1332  appendStringInfo(&chk_branchstr, "%s%s%s", branch_delim, branch, branch_delim);
1333 
1334  /* get the next sql result tuple */
1335  spi_tuple = tuptable->vals[i];
1336 
1337  /* get the current key (might be NULL) */
1338  current_key = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
1339 
1340  /* get the parent key (might be NULL) */
1341  current_key_parent = SPI_getvalue(spi_tuple, spi_tupdesc, 2);
1342 
1343  /* get the current level */
1344  sprintf(current_level, "%d", level);
1345 
1346  /* check to see if this key is also an ancestor */
1347  if (current_key)
1348  {
1349  appendStringInfo(&chk_current_key, "%s%s%s",
1350  branch_delim, current_key, branch_delim);
1351  if (strstr(chk_branchstr.data, chk_current_key.data))
1352  ereport(ERROR,
1353  (errcode(ERRCODE_INVALID_RECURSION),
1354  errmsg("infinite recursion detected")));
1355  }
1356 
1357  /* OK, extend the branch */
1358  if (current_key)
1359  appendStringInfo(&branchstr, "%s%s", branch_delim, current_key);
1360  current_branch = branchstr.data;
1361 
1362  /* build a tuple */
1363  values[0] = current_key;
1364  values[1] = current_key_parent;
1365  values[2] = current_level;
1366  if (show_branch)
1367  values[3] = current_branch;
1368  if (show_serial)
1369  {
1370  sprintf(serial_str, "%d", (*serial)++);
1371  if (show_branch)
1372  values[4] = serial_str;
1373  else
1374  values[3] = serial_str;
1375  }
1376 
1377  tuple = BuildTupleFromCStrings(attinmeta, values);
1378 
1379  /* store the tuple for later use */
1380  tuplestore_puttuple(tupstore, tuple);
1381 
1382  heap_freetuple(tuple);
1383 
1384  /* recurse using current_key as the new start_with */
1385  if (current_key)
1387  parent_key_fld,
1388  relname,
1389  orderby_fld,
1390  branch_delim,
1391  current_key,
1392  current_branch,
1393  level + 1,
1394  serial,
1395  max_depth,
1396  show_branch,
1397  show_serial,
1398  per_query_ctx,
1399  attinmeta,
1400  tupstore);
1401 
1402  xpfree(current_key);
1403  xpfree(current_key_parent);
1404 
1405  /* reset branch for next pass */
1406  resetStringInfo(&branchstr);
1407  resetStringInfo(&chk_branchstr);
1408  resetStringInfo(&chk_current_key);
1409  }
1410 
1411  xpfree(branchstr.data);
1412  xpfree(chk_branchstr.data);
1413  xpfree(chk_current_key.data);
1414  }
1415 }
1416 
1417 /*
1418  * Check expected (query runtime) tupdesc suitable for Connectby
1419  */
1420 static void
1421 validateConnectbyTupleDesc(TupleDesc td, bool show_branch, bool show_serial)
1422 {
1423  int serial_column = 0;
1424 
1425  if (show_serial)
1426  serial_column = 1;
1427 
1428  /* are there the correct number of columns */
1429  if (show_branch)
1430  {
1431  if (td->natts != (CONNECTBY_NCOLS + serial_column))
1432  ereport(ERROR,
1433  (errcode(ERRCODE_DATATYPE_MISMATCH),
1434  errmsg("invalid return type"),
1435  errdetail("Query-specified return tuple has " \
1436  "wrong number of columns.")));
1437  }
1438  else
1439  {
1440  if (td->natts != CONNECTBY_NCOLS_NOBRANCH + serial_column)
1441  ereport(ERROR,
1442  (errcode(ERRCODE_DATATYPE_MISMATCH),
1443  errmsg("invalid return type"),
1444  errdetail("Query-specified return tuple has " \
1445  "wrong number of columns.")));
1446  }
1447 
1448  /* check that the types of the first two columns match */
1449  if (TupleDescAttr(td, 0)->atttypid != TupleDescAttr(td, 1)->atttypid)
1450  ereport(ERROR,
1451  (errcode(ERRCODE_DATATYPE_MISMATCH),
1452  errmsg("invalid return type"),
1453  errdetail("First two columns must be the same type.")));
1454 
1455  /* check that the type of the third column is INT4 */
1456  if (TupleDescAttr(td, 2)->atttypid != INT4OID)
1457  ereport(ERROR,
1458  (errcode(ERRCODE_DATATYPE_MISMATCH),
1459  errmsg("invalid return type"),
1460  errdetail("Third column must be type %s.",
1461  format_type_be(INT4OID))));
1462 
1463  /* check that the type of the fourth column is TEXT if applicable */
1464  if (show_branch && TupleDescAttr(td, 3)->atttypid != TEXTOID)
1465  ereport(ERROR,
1466  (errcode(ERRCODE_DATATYPE_MISMATCH),
1467  errmsg("invalid return type"),
1468  errdetail("Fourth column must be type %s.",
1469  format_type_be(TEXTOID))));
1470 
1471  /* check that the type of the fifth column is INT4 */
1472  if (show_branch && show_serial &&
1473  TupleDescAttr(td, 4)->atttypid != INT4OID)
1474  ereport(ERROR,
1475  (errcode(ERRCODE_DATATYPE_MISMATCH),
1476  errmsg("query-specified return tuple not valid for Connectby: "
1477  "fifth column must be type %s",
1478  format_type_be(INT4OID))));
1479 
1480  /* check that the type of the fifth column is INT4 */
1481  if (!show_branch && show_serial &&
1482  TupleDescAttr(td, 3)->atttypid != INT4OID)
1483  ereport(ERROR,
1484  (errcode(ERRCODE_DATATYPE_MISMATCH),
1485  errmsg("query-specified return tuple not valid for Connectby: "
1486  "fourth column must be type %s",
1487  format_type_be(INT4OID))));
1488 
1489  /* OK, the tupdesc is valid for our purposes */
1490 }
1491 
1492 /*
1493  * Check if spi sql tupdesc and return tupdesc are compatible
1494  */
1495 static void
1497 {
1498  Oid ret_atttypid;
1499  Oid sql_atttypid;
1500  int32 ret_atttypmod;
1501  int32 sql_atttypmod;
1502 
1503  /*
1504  * Result must have at least 2 columns.
1505  */
1506  if (sql_tupdesc->natts < 2)
1507  ereport(ERROR,
1508  (errcode(ERRCODE_DATATYPE_MISMATCH),
1509  errmsg("invalid return type"),
1510  errdetail("Query must return at least two columns.")));
1511 
1512  /*
1513  * These columns must match the result type indicated by the calling
1514  * query.
1515  */
1516  ret_atttypid = TupleDescAttr(ret_tupdesc, 0)->atttypid;
1517  sql_atttypid = TupleDescAttr(sql_tupdesc, 0)->atttypid;
1518  ret_atttypmod = TupleDescAttr(ret_tupdesc, 0)->atttypmod;
1519  sql_atttypmod = TupleDescAttr(sql_tupdesc, 0)->atttypmod;
1520  if (ret_atttypid != sql_atttypid ||
1521  (ret_atttypmod >= 0 && ret_atttypmod != sql_atttypmod))
1522  ereport(ERROR,
1523  (errcode(ERRCODE_DATATYPE_MISMATCH),
1524  errmsg("invalid return type"),
1525  errdetail("SQL key field type %s does " \
1526  "not match return key field type %s.",
1527  format_type_with_typemod(ret_atttypid, ret_atttypmod),
1528  format_type_with_typemod(sql_atttypid, sql_atttypmod))));
1529 
1530  ret_atttypid = TupleDescAttr(ret_tupdesc, 1)->atttypid;
1531  sql_atttypid = TupleDescAttr(sql_tupdesc, 1)->atttypid;
1532  ret_atttypmod = TupleDescAttr(ret_tupdesc, 1)->atttypmod;
1533  sql_atttypmod = TupleDescAttr(sql_tupdesc, 1)->atttypmod;
1534  if (ret_atttypid != sql_atttypid ||
1535  (ret_atttypmod >= 0 && ret_atttypmod != sql_atttypmod))
1536  ereport(ERROR,
1537  (errcode(ERRCODE_DATATYPE_MISMATCH),
1538  errmsg("invalid return type"),
1539  errdetail("SQL parent key field type %s does " \
1540  "not match return parent key field type %s.",
1541  format_type_with_typemod(ret_atttypid, ret_atttypmod),
1542  format_type_with_typemod(sql_atttypid, sql_atttypmod))));
1543 
1544  /* OK, the two tupdescs are compatible for our purposes */
1545 }
1546 
1547 /*
1548  * Check if two tupdescs match in type of attributes
1549  */
1550 static bool
1552 {
1553  int i;
1554  Form_pg_attribute ret_attr;
1555  Oid ret_atttypid;
1556  Form_pg_attribute sql_attr;
1557  Oid sql_atttypid;
1558 
1559  if (ret_tupdesc->natts < 2 ||
1560  sql_tupdesc->natts < 3)
1561  return false;
1562 
1563  /* check the rowid types match */
1564  ret_atttypid = TupleDescAttr(ret_tupdesc, 0)->atttypid;
1565  sql_atttypid = TupleDescAttr(sql_tupdesc, 0)->atttypid;
1566  if (ret_atttypid != sql_atttypid)
1567  ereport(ERROR,
1568  (errcode(ERRCODE_DATATYPE_MISMATCH),
1569  errmsg("invalid return type"),
1570  errdetail("SQL rowid datatype does not match " \
1571  "return rowid datatype.")));
1572 
1573  /*
1574  * - attribute [1] of the sql tuple is the category; no need to check it -
1575  * attribute [2] of the sql tuple should match attributes [1] to [natts]
1576  * of the return tuple
1577  */
1578  sql_attr = TupleDescAttr(sql_tupdesc, 2);
1579  for (i = 1; i < ret_tupdesc->natts; i++)
1580  {
1581  ret_attr = TupleDescAttr(ret_tupdesc, i);
1582 
1583  if (ret_attr->atttypid != sql_attr->atttypid)
1584  return false;
1585  }
1586 
1587  /* OK, the two tupdescs are compatible for our purposes */
1588  return true;
1589 }
#define PG_GETARG_FLOAT8(n)
Definition: fmgr.h:276
uint64 call_cntr
Definition: funcapi.h:66
#define PG_GETARG_UINT32(n)
Definition: fmgr.h:265
Datum crosstab(PG_FUNCTION_ARGS)
Definition: tablefunc.c:349
PG_FUNCTION_INFO_V1(normal_rand)
#define PG_GETARG_INT32(n)
Definition: fmgr.h:264
#define MAX_CATNAME_LEN
Definition: tablefunc.c:126
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:110
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:196
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:1202
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
#define HASH_CONTEXT
Definition: hsearch.h:93
#define HASH_ELEM
Definition: hsearch.h:87
#define CONNECTBY_NCOLS_NOBRANCH
Definition: tablefunc.c:982
MemoryContext hcxt
Definition: hsearch.h:78
#define CONNECTBY_NCOLS
Definition: tablefunc.c:981
int SPI_connect(void)
Definition: spi.c:89
static void validateConnectbyTupleDesc(TupleDesc tupdesc, bool show_branch, bool show_serial)
Definition: tablefunc.c:1421
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:283
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
long random(void)
Definition: random.c:22
char * pstrdup(const char *in)
Definition: mcxt.c:1186
static HTAB * load_categories_hash(char *cats_sql, MemoryContext per_query_ctx)
Definition: tablefunc.c:706
Datum connectby_text_serial(PG_FUNCTION_ARGS)
Definition: tablefunc.c:1064
int SPI_finish(void)
Definition: spi.c:176
#define tuplestore_donestoring(state)
Definition: tuplestore.h:60
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Size entrysize
Definition: hsearch.h:73
SPITupleTable * SPI_tuptable
Definition: spi.c:46
int errcode(int sqlerrcode)
Definition: elog.c:570
#define MemSet(start, val, len)
Definition: c.h:955
char * format_type_be(Oid type_oid)
Definition: format_type.c:326
long hash_get_num_entries(HTAB *hashp)
Definition: dynahash.c:1335
#define xpfree(var_)
Definition: tablefunc.c:95
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
NameData relname
Definition: pg_class.h:35
unsigned int Oid
Definition: postgres_ext.h:31
HeapTuple * vals
Definition: spi.h:26
Datum normal_rand(PG_FUNCTION_ARGS)
Definition: tablefunc.c:174
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:287
uint64 SPI_processed
Definition: spi.c:45
signed int int32
Definition: c.h:346
Datum Float8GetDatum(float8 X)
Definition: fmgr.c:1723
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2112
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:303
struct crosstab_cat_desc crosstab_cat_desc
static void compatConnectbyTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
Definition: tablefunc.c:1496
char * SPI_getvalue(HeapTuple tuple, TupleDesc tupdesc, int fnumber)
Definition: spi.c:996
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:289
static void get_normal_pair(float8 *x1, float8 *x2)
Definition: tablefunc.c:278
#define sprintf
Definition: port.h:194
Definition: dynahash.c:208
TupleDesc expectedDesc
Definition: execnodes.h:302
void pfree(void *pointer)
Definition: mcxt.c:1056
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
double float8
Definition: c.h:491
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:1147
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:730
#define INIT_CATS
Definition: tablefunc.c:127
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:163
#define xstreq(tgtvar_, srcvar_)
Definition: tablefunc.c:112
static Tuplestorestate * get_crosstab_tuplestore(char *sql, HTAB *crosstab_hash, TupleDesc tupdesc, MemoryContext per_query_ctx, bool randomAccess)
Definition: tablefunc.c:791
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define MAX_RANDOM_VALUE
TupleDesc tupdesc
Definition: funcapi.h:39
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:62
struct crosstab_hashent crosstab_HashEnt
Oid atttypid
Definition: pg_attribute.h:49
#define ereport(elevel, rest)
Definition: elog.h:141
#define crosstab_HashTableLookup(HASHTAB, CATNAME, CATDESC)
Definition: tablefunc.c:129
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
char * format_type_with_typemod(Oid type_oid, int32 typemod)
Definition: format_type.c:345
#define INT32_STRLEN
Definition: tablefunc.c:117
void * palloc0(Size size)
Definition: mcxt.c:980
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
uintptr_t Datum
Definition: postgres.h:367
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2063
Size keysize
Definition: hsearch.h:72
int work_mem
Definition: globals.c:121
TupleDesc tupdesc
Definition: spi.h:25
#define SPI_OK_SELECT
Definition: spi.h:57
int allowedModes
Definition: execnodes.h:303
Datum crosstab_hash(PG_FUNCTION_ARGS)
Definition: tablefunc.c:635
SetFunctionReturnMode returnMode
Definition: execnodes.h:305
static bool compatCrosstabTupleDescs(TupleDesc tupdesc1, TupleDesc tupdesc2)
Definition: tablefunc.c:1551
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:102
PG_MODULE_MAGIC
Definition: tablefunc.c:47
#define SPI_OK_FINISH
Definition: spi.h:54
crosstab_cat_desc * catdesc
Definition: tablefunc.c:162
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:231
Tuplestorestate * setResult
Definition: execnodes.h:308
static Datum values[MAXATTR]
Definition: bootstrap.c:167
char * text_to_cstring(const text *t)
Definition: varlena.c:204
ExprContext * econtext
Definition: execnodes.h:301
void * user_fctx
Definition: funcapi.h:83
TupleDesc setDesc
Definition: execnodes.h:309
void * palloc(Size size)
Definition: mcxt.c:949
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
int i
Datum connectby_text(PG_FUNCTION_ARGS)
Definition: tablefunc.c:985
#define crosstab_HashTableInsert(HASHTAB, CATDESC)
Definition: tablefunc.c:143
#define PG_FUNCTION_ARGS
Definition: fmgr.h:188
ExprDoneCond isDone
Definition: execnodes.h:306
#define xpstrdup(tgtvar_, srcvar_)
Definition: tablefunc.c:104
#define PG_RETURN_NULL()
Definition: fmgr.h:335
uint64 max_calls
Definition: funcapi.h:75
float8 carry_val
Definition: tablefunc.c:91
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:496
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:307
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:285