PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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-2026, 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 "common/pg_prng.h"
40#include "executor/spi.h"
41#include "fmgr.h"
42#include "funcapi.h"
43#include "lib/stringinfo.h"
44#include "miscadmin.h"
45#include "utils/builtins.h"
46#include "utils/hsearch.h"
47#include "utils/tuplestore.h"
48
50 .name = "tablefunc",
51 .version = PG_VERSION
52);
53
57 TupleDesc tupdesc,
58 bool randomAccess);
62static void get_normal_pair(float8 *x1, float8 *x2);
64 char *key_fld,
65 char *parent_key_fld,
66 char *orderby_fld,
67 char *branch_delim,
68 char *start_with,
69 int max_depth,
70 bool show_branch,
71 bool show_serial,
73 bool randomAccess,
74 AttInMetadata *attinmeta);
76 char *parent_key_fld,
77 char *relname,
78 char *orderby_fld,
79 char *branch_delim,
80 char *start_with,
81 char *branch,
82 int level,
83 int *serial,
84 int max_depth,
85 bool show_branch,
86 bool show_serial,
88 AttInMetadata *attinmeta,
89 Tuplestorestate *tupstore);
90
91typedef struct
92{
93 float8 mean; /* mean of the distribution */
94 float8 stddev; /* stddev of the distribution */
95 float8 carry_val; /* hold second generated value */
96 bool use_carry; /* use second generated value */
98
99#define xpfree(var_) \
100 do { \
101 if (var_ != NULL) \
102 { \
103 pfree(var_); \
104 var_ = NULL; \
105 } \
106 } while (0)
107
108#define xpstrdup(tgtvar_, srcvar_) \
109 do { \
110 if (srcvar_) \
111 tgtvar_ = pstrdup(srcvar_); \
112 else \
113 tgtvar_ = NULL; \
114 } while (0)
115
116#define xstreq(tgtvar_, srcvar_) \
117 (((tgtvar_ == NULL) && (srcvar_ == NULL)) || \
118 ((tgtvar_ != NULL) && (srcvar_ != NULL) && (strcmp(tgtvar_, srcvar_) == 0)))
119
120/* sign, 10 digits, '\0' */
121#define INT32_STRLEN 12
122
123/* stored info for a crosstab category */
124typedef struct crosstab_cat_desc
125{
126 char *catname; /* full category name */
127 uint64 attidx; /* zero based */
129
130#define MAX_CATNAME_LEN NAMEDATALEN
131#define INIT_CATS 64
132
133#define crosstab_HashTableLookup(HASHTAB, CATNAME, CATDESC) \
134do { \
135 crosstab_HashEnt *hentry; char key[MAX_CATNAME_LEN]; \
136 \
137 MemSet(key, 0, MAX_CATNAME_LEN); \
138 snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATNAME); \
139 hentry = (crosstab_HashEnt*) hash_search(HASHTAB, \
140 key, HASH_FIND, NULL); \
141 if (hentry) \
142 CATDESC = hentry->catdesc; \
143 else \
144 CATDESC = NULL; \
145} while(0)
146
147#define crosstab_HashTableInsert(HASHTAB, CATDESC) \
148do { \
149 crosstab_HashEnt *hentry; bool found; char key[MAX_CATNAME_LEN]; \
150 \
151 MemSet(key, 0, MAX_CATNAME_LEN); \
152 snprintf(key, MAX_CATNAME_LEN - 1, "%s", CATDESC->catname); \
153 hentry = (crosstab_HashEnt*) hash_search(HASHTAB, \
154 key, HASH_ENTER, &found); \
155 if (found) \
156 ereport(ERROR, \
157 (errcode(ERRCODE_DUPLICATE_OBJECT), \
158 errmsg("duplicate category name"))); \
159 hentry->catdesc = CATDESC; \
160} while(0)
161
162/* hash table */
168
169/*
170 * normal_rand - return requested number of random values
171 * with a Gaussian (Normal) distribution.
172 *
173 * inputs are int numvals, float8 mean, and float8 stddev
174 * returns setof float8
175 */
177Datum
179{
181 uint64 call_cntr;
182 uint64 max_calls;
184 float8 mean;
185 float8 stddev;
186 float8 carry_val;
187 bool use_carry;
188 MemoryContext oldcontext;
189
190 /* stuff done only on the first call of the function */
191 if (SRF_IS_FIRSTCALL())
192 {
193 int32 num_tuples;
194
195 /* create a function context for cross-call persistence */
197
198 /*
199 * switch to memory context appropriate for multiple function calls
200 */
201 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
202
203 /* total number of tuples to be returned */
204 num_tuples = PG_GETARG_INT32(0);
205 if (num_tuples < 0)
208 errmsg("number of rows cannot be negative")));
209 funcctx->max_calls = num_tuples;
210
211 /* allocate memory for user context */
213
214 /*
215 * Use fctx to keep track of upper and lower bounds from call to call.
216 * It will also be used to carry over the spare value we get from the
217 * Box-Muller algorithm so that we only actually calculate a new value
218 * every other call.
219 */
220 fctx->mean = PG_GETARG_FLOAT8(1);
221 fctx->stddev = PG_GETARG_FLOAT8(2);
222 fctx->carry_val = 0;
223 fctx->use_carry = false;
224
225 funcctx->user_fctx = fctx;
226
227 MemoryContextSwitchTo(oldcontext);
228 }
229
230 /* stuff done on every call of the function */
232
233 call_cntr = funcctx->call_cntr;
234 max_calls = funcctx->max_calls;
235 fctx = funcctx->user_fctx;
236 mean = fctx->mean;
237 stddev = fctx->stddev;
238 carry_val = fctx->carry_val;
239 use_carry = fctx->use_carry;
240
241 if (call_cntr < max_calls) /* do when there is more left to send */
242 {
244
245 if (use_carry)
246 {
247 /*
248 * reset use_carry and use second value obtained on last pass
249 */
250 fctx->use_carry = false;
251 result = carry_val;
252 }
253 else
254 {
257
258 /* Get the next two normal values */
260
261 /* use the first */
262 result = mean + (stddev * normval_1);
263
264 /* and save the second */
265 fctx->carry_val = mean + (stddev * normval_2);
266 fctx->use_carry = true;
267 }
268
269 /* send the result */
271 }
272 else
273 /* do when there is no more left */
275}
276
277/*
278 * get_normal_pair()
279 * Assigns normally distributed (Gaussian) values to a pair of provided
280 * parameters, with mean 0, standard deviation 1.
281 *
282 * This routine implements Algorithm P (Polar method for normal deviates)
283 * from Knuth's _The_Art_of_Computer_Programming_, Volume 2, 3rd ed., pages
284 * 122-126. Knuth cites his source as "The polar method", G. E. P. Box, M. E.
285 * Muller, and G. Marsaglia, _Annals_Math,_Stat._ 29 (1958), 610-611.
286 *
287 */
288static void
290{
291 float8 u1,
292 u2,
293 v1,
294 v2,
295 s;
296
297 do
298 {
301
302 v1 = (2.0 * u1) - 1.0;
303 v2 = (2.0 * u2) - 1.0;
304
305 s = v1 * v1 + v2 * v2;
306 } while (s >= 1.0);
307
308 if (s == 0)
309 {
310 *x1 = 0;
311 *x2 = 0;
312 }
313 else
314 {
315 s = sqrt((-2.0 * log(s)) / s);
316 *x1 = v1 * s;
317 *x2 = v2 * s;
318 }
319}
320
321/*
322 * crosstab - create a crosstab of rowids and values columns from a
323 * SQL statement returning one rowid column, one category column,
324 * and one value column.
325 *
326 * e.g. given sql which produces:
327 *
328 * rowid cat value
329 * ------+-------+-------
330 * row1 cat1 val1
331 * row1 cat2 val2
332 * row1 cat3 val3
333 * row1 cat4 val4
334 * row2 cat1 val5
335 * row2 cat2 val6
336 * row2 cat3 val7
337 * row2 cat4 val8
338 *
339 * crosstab returns:
340 * <===== values columns =====>
341 * rowid cat1 cat2 cat3 cat4
342 * ------+-------+-------+-------+-------
343 * row1 val1 val2 val3 val4
344 * row2 val5 val6 val7 val8
345 *
346 * NOTES:
347 * 1. SQL result must be ordered by 1,2.
348 * 2. The number of values columns depends on the tuple description
349 * of the function's declared return type. The return type's columns
350 * must match the datatypes of the SQL query's result. The datatype
351 * of the category column can be anything, however.
352 * 3. Missing values (i.e. not enough adjacent rows of same rowid to
353 * fill the number of result values columns) are filled in with nulls.
354 * 4. Extra values (i.e. too many adjacent rows of same rowid to fill
355 * the number of result values columns) are skipped.
356 * 5. Rows with all nulls in the values columns are skipped.
357 */
359Datum
361{
362 char *sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
363 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
364 Tuplestorestate *tupstore;
365 TupleDesc tupdesc;
366 uint64 call_cntr;
367 uint64 max_calls;
368 AttInMetadata *attinmeta;
371 bool firstpass;
372 char *lastrowid;
373 int i;
374 int num_categories;
376 MemoryContext oldcontext;
377 int ret;
378 uint64 proc;
379
380 /* check to see if caller supports us returning a tuplestore */
381 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
384 errmsg("set-valued function called in context that cannot accept a set")));
385 if (!(rsinfo->allowedModes & SFRM_Materialize))
388 errmsg("materialize mode required, but it is not allowed in this context")));
389
390 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
391
392 /* Connect to SPI manager */
393 SPI_connect();
394
395 /* Retrieve the desired rows */
396 ret = SPI_execute(sql, true, 0);
397 proc = SPI_processed;
398
399 /* If no qualifying tuples, fall out early */
400 if (ret != SPI_OK_SELECT || proc == 0)
401 {
402 SPI_finish();
403 rsinfo->isDone = ExprEndResult;
405 }
406
409
410 /*----------
411 * The provided SQL query must always return three columns.
412 *
413 * 1. rowname
414 * the label or identifier for each row in the final result
415 * 2. category
416 * the label or identifier for each column in the final result
417 * 3. values
418 * the value for each column in the final result
419 *----------
420 */
421 if (spi_tupdesc->natts != 3)
424 errmsg("invalid crosstab source data query"),
425 errdetail("The query must return 3 columns: row_name, category, and value.")));
426
427 /* get a tuple descriptor for our result type */
428 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
429 {
431 /* success */
432 break;
433 case TYPEFUNC_RECORD:
434 /* failed to determine actual type of RECORD */
437 errmsg("function returning record called in context "
438 "that cannot accept type record")));
439 break;
440 default:
441 /* result type isn't composite */
444 errmsg("return type must be a row type")));
445 break;
446 }
447
448 /*
449 * Check that return tupdesc is compatible with the data we got from SPI,
450 * at least based on number and type of attributes
451 */
453
454 /*
455 * switch to long-lived memory context
456 */
458
459 /* make sure we have a persistent copy of the result tupdesc */
460 tupdesc = CreateTupleDescCopy(tupdesc);
461
462 /* initialize our tuplestore in long-lived context */
463 tupstore =
465 false, work_mem);
466
467 MemoryContextSwitchTo(oldcontext);
468
469 /*
470 * Generate attribute metadata needed later to produce tuples from raw C
471 * strings
472 */
473 attinmeta = TupleDescGetAttInMetadata(tupdesc);
474
475 /* total number of tuples to be examined */
476 max_calls = proc;
477
478 /* the return tuple always must have 1 rowid + num_categories columns */
479 num_categories = tupdesc->natts - 1;
480
481 firstpass = true;
482 lastrowid = NULL;
483
484 for (call_cntr = 0; call_cntr < max_calls; call_cntr++)
485 {
486 bool skip_tuple = false;
487 char **values;
488
489 /* allocate and zero space */
490 values = (char **) palloc0((1 + num_categories) * sizeof(char *));
491
492 /*
493 * now loop through the sql results and assign each value in sequence
494 * to the next category
495 */
496 for (i = 0; i < num_categories; i++)
497 {
499 char *rowid;
500
501 /* see if we've gone too far already */
502 if (call_cntr >= max_calls)
503 break;
504
505 /* get the next sql result tuple */
506 spi_tuple = spi_tuptable->vals[call_cntr];
507
508 /* get the rowid from the current sql result tuple */
510
511 /*
512 * If this is the first pass through the values for this rowid,
513 * set the first column to rowid
514 */
515 if (i == 0)
516 {
517 xpstrdup(values[0], rowid);
518
519 /*
520 * Check to see if the rowid is the same as that of the last
521 * tuple sent -- if so, skip this tuple entirely
522 */
524 {
525 xpfree(rowid);
526 skip_tuple = true;
527 break;
528 }
529 }
530
531 /*
532 * If rowid hasn't changed on us, continue building the output
533 * tuple.
534 */
535 if (xstreq(rowid, values[0]))
536 {
537 /*
538 * Get the next category item value, which is always attribute
539 * number three.
540 *
541 * Be careful to assign the value to the array index based on
542 * which category we are presently processing.
543 */
545
546 /*
547 * increment the counter since we consume a row for each
548 * category, but not for last pass because the outer loop will
549 * do that for us
550 */
551 if (i < (num_categories - 1))
552 call_cntr++;
553 xpfree(rowid);
554 }
555 else
556 {
557 /*
558 * We'll fill in NULLs for the missing values, but we need to
559 * decrement the counter since this sql result row doesn't
560 * belong to the current output tuple.
561 */
562 call_cntr--;
563 xpfree(rowid);
564 break;
565 }
566 }
567
568 if (!skip_tuple)
569 {
570 HeapTuple tuple;
571
572 /* build the tuple and store it */
573 tuple = BuildTupleFromCStrings(attinmeta, values);
574 tuplestore_puttuple(tupstore, tuple);
575 heap_freetuple(tuple);
576 }
577
578 /* Remember current rowid */
581 firstpass = false;
582
583 /* Clean up */
584 for (i = 0; i < num_categories + 1; i++)
585 if (values[i] != NULL)
586 pfree(values[i]);
587 pfree(values);
588 }
589
590 /* let the caller know we're sending back a tuplestore */
591 rsinfo->returnMode = SFRM_Materialize;
592 rsinfo->setResult = tupstore;
593 rsinfo->setDesc = tupdesc;
594
595 /* release SPI related resources (and return to caller's context) */
596 SPI_finish();
597
598 return (Datum) 0;
599}
600
601/*
602 * crosstab_hash - reimplement crosstab as materialized function and
603 * properly deal with missing values (i.e. don't pack remaining
604 * values to the left)
605 *
606 * crosstab - create a crosstab of rowids and values columns from a
607 * SQL statement returning one rowid column, one category column,
608 * and one value column.
609 *
610 * e.g. given sql which produces:
611 *
612 * rowid cat value
613 * ------+-------+-------
614 * row1 cat1 val1
615 * row1 cat2 val2
616 * row1 cat4 val4
617 * row2 cat1 val5
618 * row2 cat2 val6
619 * row2 cat3 val7
620 * row2 cat4 val8
621 *
622 * crosstab returns:
623 * <===== values columns =====>
624 * rowid cat1 cat2 cat3 cat4
625 * ------+-------+-------+-------+-------
626 * row1 val1 val2 null val4
627 * row2 val5 val6 val7 val8
628 *
629 * NOTES:
630 * 1. SQL result must be ordered by 1.
631 * 2. The number of values columns depends on the tuple description
632 * of the function's declared return type.
633 * 3. Missing values (i.e. missing category) are filled in with nulls.
634 * 4. Extra values (i.e. not in category results) are skipped.
635 */
637Datum
639{
640 char *sql = text_to_cstring(PG_GETARG_TEXT_PP(0));
642 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
643 TupleDesc tupdesc;
645 MemoryContext oldcontext;
647
648 /* check to see if caller supports us returning a tuplestore */
649 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
652 errmsg("set-valued function called in context that cannot accept a set")));
653 if (!(rsinfo->allowedModes & SFRM_Materialize) ||
654 rsinfo->expectedDesc == NULL)
657 errmsg("materialize mode required, but it is not allowed in this context")));
658
659 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
661
662 /* get the requested return tuple description */
663 tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
664
665 /*
666 * Check to make sure we have a reasonable tuple descriptor
667 *
668 * Note we will attempt to coerce the values into whatever the return
669 * attribute type is and depend on the "in" function to complain if
670 * needed.
671 */
672 if (tupdesc->natts < 2)
675 errmsg("invalid crosstab return type"),
676 errdetail("Return row must have at least two columns.")));
677
678 /* load up the categories hash table */
680
681 /* let the caller know we're sending back a tuplestore */
682 rsinfo->returnMode = SFRM_Materialize;
683
684 /* now go build it */
685 rsinfo->setResult = get_crosstab_tuplestore(sql,
687 tupdesc,
688 rsinfo->allowedModes & SFRM_Materialize_Random);
689
690 /*
691 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
692 * tuples are in our tuplestore and passed back through rsinfo->setResult.
693 * rsinfo->setDesc is set to the tuple description that we actually used
694 * to build our tuples with, so the caller can verify we did what it was
695 * expecting.
696 */
697 rsinfo->setDesc = tupdesc;
698 MemoryContextSwitchTo(oldcontext);
699
700 return (Datum) 0;
701}
702
703/*
704 * load up the categories hash table
705 */
706static HTAB *
708{
710 HASHCTL ctl;
711 int ret;
712 uint64 proc;
714
715 /* initialize the category hash table */
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 SPI_connect();
731
732 /* Retrieve the category name rows */
733 ret = SPI_execute(cats_sql, true, 0);
734 proc = SPI_processed;
735
736 /* Check for qualifying tuples */
737 if ((ret == SPI_OK_SELECT) && (proc > 0))
738 {
741 uint64 i;
742
743 /*
744 * The provided categories SQL query must always return one column:
745 * category - the label or identifier for each column
746 */
747 if (spi_tupdesc->natts != 1)
750 errmsg("invalid crosstab categories query"),
751 errdetail("The query must return one column.")));
752
753 for (i = 0; i < proc; i++)
754 {
755 crosstab_cat_desc *catdesc;
756 char *catname;
758
759 /* get the next sql result tuple */
760 spi_tuple = spi_tuptable->vals[i];
761
762 /* get the category from the current sql result tuple */
763 catname = SPI_getvalue(spi_tuple, spi_tupdesc, 1);
764 if (catname == NULL)
767 errmsg("crosstab category value must not be null")));
768
770
772 catdesc->catname = catname;
773 catdesc->attidx = i;
774
775 /* Add the proc description block to the hashtable */
777
779 }
780 }
781
782 if (SPI_finish() != SPI_OK_FINISH)
783 /* internal error */
784 elog(ERROR, "load_categories_hash: SPI_finish() failed");
785
786 return crosstab_hash;
787}
788
789/*
790 * create and populate the crosstab tuplestore using the provided source query
791 */
792static Tuplestorestate *
795 TupleDesc tupdesc,
796 bool randomAccess)
797{
798 Tuplestorestate *tupstore;
800 AttInMetadata *attinmeta = TupleDescGetAttInMetadata(tupdesc);
801 char **values;
802 HeapTuple tuple;
803 int ret;
804 uint64 proc;
805
806 /* initialize our tuplestore (while still in query context!) */
807 tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
808
809 /* Connect to SPI manager */
810 SPI_connect();
811
812 /* Now retrieve the crosstab source rows */
813 ret = SPI_execute(sql, true, 0);
814 proc = SPI_processed;
815
816 /* Check for qualifying tuples */
817 if ((ret == SPI_OK_SELECT) && (proc > 0))
818 {
821 int ncols = spi_tupdesc->natts;
822 char *rowid;
823 char *lastrowid = NULL;
824 bool firstpass = true;
825 uint64 i;
826 int j;
827 int result_ncols;
828
829 if (num_categories == 0)
830 {
831 /* no qualifying category tuples */
834 errmsg("crosstab categories query must return at least one row")));
835 }
836
837 /*
838 * The provided SQL query must always return at least three columns:
839 *
840 * 1. rowname the label for each row - column 1 in the final result
841 * 2. category the label for each value-column in the final result 3.
842 * value the values used to populate the value-columns
843 *
844 * If there are more than three columns, the last two are taken as
845 * "category" and "values". The first column is taken as "rowname".
846 * Additional columns (2 thru N-2) are assumed the same for the same
847 * "rowname", and are copied into the result tuple from the first time
848 * we encounter a particular rowname.
849 */
850 if (ncols < 3)
853 errmsg("invalid crosstab source data query"),
854 errdetail("The query must return at least 3 columns: row_name, category, and value.")));
855
856 result_ncols = (ncols - 2) + num_categories;
857
858 /* Recheck to make sure output tuple descriptor looks reasonable */
859 if (tupdesc->natts != result_ncols)
862 errmsg("invalid crosstab return type"),
863 errdetail("Return row must have %d columns, not %d.",
864 result_ncols, tupdesc->natts)));
865
866 /* allocate space and make sure it's clear */
867 values = (char **) palloc0(result_ncols * sizeof(char *));
868
869 for (i = 0; i < proc; i++)
870 {
872 crosstab_cat_desc *catdesc;
873 char *catname;
874
875 /* get the next sql result tuple */
876 spi_tuple = spi_tuptable->vals[i];
877
878 /* get the rowid from the current sql result tuple */
880
881 /*
882 * if we're on a new output row, grab the column values up to
883 * column N-2 now
884 */
886 {
887 /*
888 * a new row means we need to flush the old one first, unless
889 * we're on the very first row
890 */
891 if (!firstpass)
892 {
893 /* rowid changed, flush the previous output row */
894 tuple = BuildTupleFromCStrings(attinmeta, values);
895
896 tuplestore_puttuple(tupstore, tuple);
897
898 for (j = 0; j < result_ncols; j++)
899 xpfree(values[j]);
900 }
901
902 values[0] = rowid;
903 for (j = 1; j < ncols - 2; j++)
905
906 /* we're no longer on the first pass */
907 firstpass = false;
908 }
909
910 /* look up the category and fill in the appropriate column */
911 catname = SPI_getvalue(spi_tuple, spi_tupdesc, ncols - 1);
912
913 if (catname != NULL)
914 {
915 crosstab_HashTableLookup(crosstab_hash, catname, catdesc);
916
917 if (catdesc)
918 values[catdesc->attidx + ncols - 2] =
920 }
921
924 }
925
926 /* flush the last output row */
927 tuple = BuildTupleFromCStrings(attinmeta, values);
928
929 tuplestore_puttuple(tupstore, tuple);
930 }
931
932 if (SPI_finish() != SPI_OK_FINISH)
933 /* internal error */
934 elog(ERROR, "get_crosstab_tuplestore: SPI_finish() failed");
935
936 return tupstore;
937}
938
939/*
940 * connectby_text - produce a result set from a hierarchical (parent/child)
941 * table.
942 *
943 * e.g. given table foo:
944 *
945 * keyid parent_keyid pos
946 * ------+------------+--
947 * row1 NULL 0
948 * row2 row1 0
949 * row3 row1 0
950 * row4 row2 1
951 * row5 row2 0
952 * row6 row4 0
953 * row7 row3 0
954 * row8 row6 0
955 * row9 row5 0
956 *
957 *
958 * connectby(text relname, text keyid_fld, text parent_keyid_fld
959 * [, text orderby_fld], text start_with, int max_depth
960 * [, text branch_delim])
961 * connectby('foo', 'keyid', 'parent_keyid', 'pos', 'row2', 0, '~') returns:
962 *
963 * keyid parent_id level branch serial
964 * ------+-----------+--------+-----------------------
965 * row2 NULL 0 row2 1
966 * row5 row2 1 row2~row5 2
967 * row9 row5 2 row2~row5~row9 3
968 * row4 row2 1 row2~row4 4
969 * row6 row4 2 row2~row4~row6 5
970 * row8 row6 3 row2~row4~row6~row8 6
971 *
972 */
974
975#define CONNECTBY_NCOLS 4
976#define CONNECTBY_NCOLS_NOBRANCH 3
977
978Datum
980{
985 int max_depth = PG_GETARG_INT32(4);
986 char *branch_delim = NULL;
987 bool show_branch = false;
988 bool show_serial = false;
989 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
990 TupleDesc tupdesc;
991 AttInMetadata *attinmeta;
993 MemoryContext oldcontext;
994
995 /* check to see if caller supports us returning a tuplestore */
996 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
999 errmsg("set-valued function called in context that cannot accept a set")));
1000 if (!(rsinfo->allowedModes & SFRM_Materialize) ||
1001 rsinfo->expectedDesc == NULL)
1002 ereport(ERROR,
1004 errmsg("materialize mode required, but it is not allowed in this context")));
1005
1006 if (fcinfo->nargs == 6)
1007 {
1009 show_branch = true;
1010 }
1011 else
1012 /* default is no show, tilde for the delimiter */
1013 branch_delim = pstrdup("~");
1014
1015 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1017
1018 /* get the requested return tuple description */
1019 tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1020
1021 /* does it meet our needs */
1023
1024 /* OK, use it then */
1025 attinmeta = TupleDescGetAttInMetadata(tupdesc);
1026
1027 /* OK, go to work */
1028 rsinfo->returnMode = SFRM_Materialize;
1029 rsinfo->setResult = connectby(relname,
1030 key_fld,
1032 NULL,
1034 start_with,
1035 max_depth,
1039 rsinfo->allowedModes & SFRM_Materialize_Random,
1040 attinmeta);
1041 rsinfo->setDesc = tupdesc;
1042
1043 MemoryContextSwitchTo(oldcontext);
1044
1045 /*
1046 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1047 * tuples are in our tuplestore and passed back through rsinfo->setResult.
1048 * rsinfo->setDesc is set to the tuple description that we actually used
1049 * to build our tuples with, so the caller can verify we did what it was
1050 * expecting.
1051 */
1052 return (Datum) 0;
1053}
1054
1056Datum
1058{
1064 int max_depth = PG_GETARG_INT32(5);
1065 char *branch_delim = NULL;
1066 bool show_branch = false;
1067 bool show_serial = true;
1068 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1069 TupleDesc tupdesc;
1070 AttInMetadata *attinmeta;
1072 MemoryContext oldcontext;
1073
1074 /* check to see if caller supports us returning a tuplestore */
1075 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1076 ereport(ERROR,
1078 errmsg("set-valued function called in context that cannot accept a set")));
1079 if (!(rsinfo->allowedModes & SFRM_Materialize) ||
1080 rsinfo->expectedDesc == NULL)
1081 ereport(ERROR,
1083 errmsg("materialize mode required, but it is not allowed in this context")));
1084
1085 if (fcinfo->nargs == 7)
1086 {
1088 show_branch = true;
1089 }
1090 else
1091 /* default is no show, tilde for the delimiter */
1092 branch_delim = pstrdup("~");
1093
1094 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1096
1097 /* get the requested return tuple description */
1098 tupdesc = CreateTupleDescCopy(rsinfo->expectedDesc);
1099
1100 /* does it meet our needs */
1102
1103 /* OK, use it then */
1104 attinmeta = TupleDescGetAttInMetadata(tupdesc);
1105
1106 /* OK, go to work */
1107 rsinfo->returnMode = SFRM_Materialize;
1108 rsinfo->setResult = connectby(relname,
1109 key_fld,
1113 start_with,
1114 max_depth,
1118 rsinfo->allowedModes & SFRM_Materialize_Random,
1119 attinmeta);
1120 rsinfo->setDesc = tupdesc;
1121
1122 MemoryContextSwitchTo(oldcontext);
1123
1124 /*
1125 * SFRM_Materialize mode expects us to return a NULL Datum. The actual
1126 * tuples are in our tuplestore and passed back through rsinfo->setResult.
1127 * rsinfo->setDesc is set to the tuple description that we actually used
1128 * to build our tuples with, so the caller can verify we did what it was
1129 * expecting.
1130 */
1131 return (Datum) 0;
1132}
1133
1134
1135/*
1136 * connectby - does the real work for connectby_text()
1137 */
1138static Tuplestorestate *
1140 char *key_fld,
1141 char *parent_key_fld,
1142 char *orderby_fld,
1143 char *branch_delim,
1144 char *start_with,
1145 int max_depth,
1146 bool show_branch,
1147 bool show_serial,
1149 bool randomAccess,
1150 AttInMetadata *attinmeta)
1151{
1152 Tuplestorestate *tupstore = NULL;
1153 MemoryContext oldcontext;
1154 int serial = 1;
1155
1156 /* Connect to SPI manager */
1157 SPI_connect();
1158
1159 /* switch to longer term context to create the tuple store */
1161
1162 /* initialize our tuplestore */
1163 tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
1164
1165 MemoryContextSwitchTo(oldcontext);
1166
1167 /* now go get the whole tree */
1170 relname,
1173 start_with,
1174 start_with, /* current_branch */
1175 0, /* initial level is 0 */
1176 &serial, /* initial serial is 1 */
1177 max_depth,
1181 attinmeta,
1182 tupstore);
1183
1184 SPI_finish();
1185
1186 return tupstore;
1187}
1188
1189static void
1191 char *parent_key_fld,
1192 char *relname,
1193 char *orderby_fld,
1194 char *branch_delim,
1195 char *start_with,
1196 char *branch,
1197 int level,
1198 int *serial,
1199 int max_depth,
1200 bool show_branch,
1201 bool show_serial,
1203 AttInMetadata *attinmeta,
1204 Tuplestorestate *tupstore)
1205{
1206 TupleDesc tupdesc = attinmeta->tupdesc;
1207 int ret;
1208 uint64 proc;
1209 int serial_column;
1210 StringInfoData sql;
1211 char **values;
1212 char *current_key;
1213 char *current_key_parent;
1216 char *current_branch;
1217 HeapTuple tuple;
1218
1219 if (max_depth > 0 && level > max_depth)
1220 return;
1221
1222 initStringInfo(&sql);
1223
1224 /* Build initial sql statement */
1225 if (!show_serial)
1226 {
1227 appendStringInfo(&sql, "SELECT %s, %s FROM %s WHERE %s = %s AND %s IS NOT NULL AND %s <> %s",
1228 key_fld,
1230 relname,
1234 serial_column = 0;
1235 }
1236 else
1237 {
1238 appendStringInfo(&sql, "SELECT %s, %s FROM %s WHERE %s = %s AND %s IS NOT NULL AND %s <> %s ORDER BY %s",
1239 key_fld,
1241 relname,
1245 orderby_fld);
1246 serial_column = 1;
1247 }
1248
1249 if (show_branch)
1250 values = (char **) palloc((CONNECTBY_NCOLS + serial_column) * sizeof(char *));
1251 else
1252 values = (char **) palloc((CONNECTBY_NCOLS_NOBRANCH + serial_column) * sizeof(char *));
1253
1254 /* First time through, do a little setup */
1255 if (level == 0)
1256 {
1257 /* root value is the one we initially start with */
1258 values[0] = start_with;
1259
1260 /* root value has no parent */
1261 values[1] = NULL;
1262
1263 /* root level is 0 */
1264 sprintf(current_level, "%d", level);
1265 values[2] = current_level;
1266
1267 /* root branch is just starting root value */
1268 if (show_branch)
1269 values[3] = start_with;
1270
1271 /* root starts the serial with 1 */
1272 if (show_serial)
1273 {
1274 sprintf(serial_str, "%d", (*serial)++);
1275 if (show_branch)
1276 values[4] = serial_str;
1277 else
1278 values[3] = serial_str;
1279 }
1280
1281 /* construct the tuple */
1282 tuple = BuildTupleFromCStrings(attinmeta, values);
1283
1284 /* now store it */
1285 tuplestore_puttuple(tupstore, tuple);
1286
1287 /* increment level */
1288 level++;
1289 }
1290
1291 /* Retrieve the desired rows */
1292 ret = SPI_execute(sql.data, true, 0);
1293 proc = SPI_processed;
1294
1295 /* Check for qualifying tuples */
1296 if ((ret == SPI_OK_SELECT) && (proc > 0))
1297 {
1299 SPITupleTable *tuptable = SPI_tuptable;
1300 TupleDesc spi_tupdesc = tuptable->tupdesc;
1301 uint64 i;
1305
1306 /*
1307 * Check that return tupdesc is compatible with the one we got from
1308 * the query.
1309 */
1311
1315
1316 for (i = 0; i < proc; i++)
1317 {
1318 /* initialize branch for this pass */
1321
1322 /* get the next sql result tuple */
1323 spi_tuple = tuptable->vals[i];
1324
1325 /* get the current key (might be NULL) */
1327
1328 /* get the parent key (might be NULL) */
1330
1331 /* get the current level */
1332 sprintf(current_level, "%d", level);
1333
1334 /* check to see if this key is also an ancestor */
1335 if (current_key)
1336 {
1339 if (strstr(chk_branchstr.data, chk_current_key.data))
1340 ereport(ERROR,
1342 errmsg("infinite recursion detected")));
1343 }
1344
1345 /* OK, extend the branch */
1346 if (current_key)
1349
1350 /* build a tuple */
1351 values[0] = current_key;
1353 values[2] = current_level;
1354 if (show_branch)
1356 if (show_serial)
1357 {
1358 sprintf(serial_str, "%d", (*serial)++);
1359 if (show_branch)
1360 values[4] = serial_str;
1361 else
1362 values[3] = serial_str;
1363 }
1364
1365 tuple = BuildTupleFromCStrings(attinmeta, values);
1366
1367 /* store the tuple for later use */
1368 tuplestore_puttuple(tupstore, tuple);
1369
1370 heap_freetuple(tuple);
1371
1372 /* recurse using current_key as the new start_with */
1373 if (current_key)
1376 relname,
1381 level + 1,
1382 serial,
1383 max_depth,
1387 attinmeta,
1388 tupstore);
1389
1392
1393 /* reset branch for next pass */
1397 }
1398
1399 xpfree(branchstr.data);
1400 xpfree(chk_branchstr.data);
1401 xpfree(chk_current_key.data);
1402 }
1403}
1404
1405/*
1406 * Check expected (query runtime) tupdesc suitable for Connectby
1407 */
1408static void
1410{
1411 int expected_cols;
1412
1413 /* are there the correct number of columns */
1414 if (show_branch)
1416 else
1418 if (show_serial)
1419 expected_cols++;
1420
1421 if (td->natts != expected_cols)
1422 ereport(ERROR,
1424 errmsg("invalid connectby return type"),
1425 errdetail("Return row must have %d columns, not %d.",
1426 expected_cols, td->natts)));
1427
1428 /* the first two columns will be checked against the input tuples later */
1429
1430 /* check that the type of the third column is INT4 */
1431 if (TupleDescAttr(td, 2)->atttypid != INT4OID)
1432 ereport(ERROR,
1434 errmsg("invalid connectby return type"),
1435 errdetail("Third return column (depth) must be type %s.",
1437
1438 /* check that the type of the branch column is TEXT if applicable */
1439 if (show_branch && TupleDescAttr(td, 3)->atttypid != TEXTOID)
1440 ereport(ERROR,
1442 errmsg("invalid connectby return type"),
1443 errdetail("Fourth return column (branch) must be type %s.",
1445
1446 /* check that the type of the serial column is INT4 if applicable */
1447 if (show_branch && show_serial &&
1448 TupleDescAttr(td, 4)->atttypid != INT4OID)
1449 ereport(ERROR,
1451 errmsg("invalid connectby return type"),
1452 errdetail("Fifth return column (serial) must be type %s.",
1454 if (!show_branch && show_serial &&
1455 TupleDescAttr(td, 3)->atttypid != INT4OID)
1456 ereport(ERROR,
1458 errmsg("invalid connectby return type"),
1459 errdetail("Fourth return column (serial) must be type %s.",
1461
1462 /* OK, the tupdesc is valid for our purposes */
1463}
1464
1465/*
1466 * Check if output tupdesc and SQL query's tupdesc are compatible
1467 */
1468static void
1470{
1475
1476 /*
1477 * Query result must have at least 2 columns.
1478 */
1479 if (sql_tupdesc->natts < 2)
1480 ereport(ERROR,
1482 errmsg("invalid connectby source data query"),
1483 errdetail("The query must return at least two columns.")));
1484
1485 /*
1486 * These columns must match the result type indicated by the calling
1487 * query.
1488 */
1489 ret_atttypid = TupleDescAttr(ret_tupdesc, 0)->atttypid;
1490 sql_atttypid = TupleDescAttr(sql_tupdesc, 0)->atttypid;
1491 ret_atttypmod = TupleDescAttr(ret_tupdesc, 0)->atttypmod;
1492 sql_atttypmod = TupleDescAttr(sql_tupdesc, 0)->atttypmod;
1493 if (ret_atttypid != sql_atttypid ||
1495 ereport(ERROR,
1497 errmsg("invalid connectby return type"),
1498 errdetail("Source key type %s does not match return key type %s.",
1501
1502 ret_atttypid = TupleDescAttr(ret_tupdesc, 1)->atttypid;
1503 sql_atttypid = TupleDescAttr(sql_tupdesc, 1)->atttypid;
1504 ret_atttypmod = TupleDescAttr(ret_tupdesc, 1)->atttypmod;
1505 sql_atttypmod = TupleDescAttr(sql_tupdesc, 1)->atttypmod;
1506 if (ret_atttypid != sql_atttypid ||
1508 ereport(ERROR,
1510 errmsg("invalid connectby return type"),
1511 errdetail("Source parent key type %s does not match return parent key type %s.",
1514
1515 /* OK, the two tupdescs are compatible for our purposes */
1516}
1517
1518/*
1519 * Check if crosstab output tupdesc agrees with input tupdesc
1520 */
1521static void
1523{
1524 int i;
1529
1530 if (ret_tupdesc->natts < 2)
1531 ereport(ERROR,
1533 errmsg("invalid crosstab return type"),
1534 errdetail("Return row must have at least two columns.")));
1535 Assert(sql_tupdesc->natts == 3); /* already checked by caller */
1536
1537 /* check the row_name types match */
1538 ret_atttypid = TupleDescAttr(ret_tupdesc, 0)->atttypid;
1539 sql_atttypid = TupleDescAttr(sql_tupdesc, 0)->atttypid;
1540 ret_atttypmod = TupleDescAttr(ret_tupdesc, 0)->atttypmod;
1541 sql_atttypmod = TupleDescAttr(sql_tupdesc, 0)->atttypmod;
1542 if (ret_atttypid != sql_atttypid ||
1544 ereport(ERROR,
1546 errmsg("invalid crosstab return type"),
1547 errdetail("Source row_name datatype %s does not match return row_name datatype %s.",
1550
1551 /*
1552 * attribute [1] of sql tuple is the category; no need to check it
1553 * attribute [2] of sql tuple should match attributes [1] to [natts - 1]
1554 * of the return tuple
1555 */
1556 sql_atttypid = TupleDescAttr(sql_tupdesc, 2)->atttypid;
1557 sql_atttypmod = TupleDescAttr(sql_tupdesc, 2)->atttypmod;
1558 for (i = 1; i < ret_tupdesc->natts; i++)
1559 {
1560 ret_atttypid = TupleDescAttr(ret_tupdesc, i)->atttypid;
1561 ret_atttypmod = TupleDescAttr(ret_tupdesc, i)->atttypmod;
1562
1563 if (ret_atttypid != sql_atttypid ||
1565 ereport(ERROR,
1567 errmsg("invalid crosstab return type"),
1568 errdetail("Source value datatype %s does not match return value datatype %s in column %d.",
1571 i + 1)));
1572 }
1573
1574 /* OK, the two tupdescs are compatible for our purposes */
1575}
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define Assert(condition)
Definition c.h:943
double float8
Definition c.h:714
int32_t int32
Definition c.h:620
uint64_t uint64
Definition c.h:625
uint32 result
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
int64 hash_get_num_entries(HTAB *hashp)
Definition dynahash.c:1273
int errcode(int sqlerrcode)
Definition elog.c:874
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
@ ExprEndResult
Definition execnodes.h:343
@ SFRM_Materialize_Random
Definition execnodes.h:356
@ SFRM_Materialize
Definition execnodes.h:355
#define palloc_object(type)
Definition fe_memutils.h:74
#define PG_GETARG_TEXT_PP(n)
Definition fmgr.h:310
#define PG_GETARG_FLOAT8(n)
Definition fmgr.h:283
#define PG_MODULE_MAGIC_EXT(...)
Definition fmgr.h:540
#define PG_RETURN_NULL()
Definition fmgr.h:346
#define PG_FUNCTION_INFO_V1(funcname)
Definition fmgr.h:417
#define PG_GETARG_INT32(n)
Definition fmgr.h:269
#define PG_FUNCTION_ARGS
Definition fmgr.h:193
char * format_type_with_typemod(Oid type_oid, int32 typemod)
char * format_type_be(Oid type_oid)
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition funcapi.c:276
#define SRF_IS_FIRSTCALL()
Definition funcapi.h:304
#define SRF_PERCALL_SETUP()
Definition funcapi.h:308
@ TYPEFUNC_COMPOSITE
Definition funcapi.h:149
@ TYPEFUNC_RECORD
Definition funcapi.h:151
#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
int work_mem
Definition globals.c:133
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
#define HASH_STRINGS
Definition hsearch.h:91
#define HASH_CONTEXT
Definition hsearch.h:97
#define HASH_ELEM
Definition hsearch.h:90
int j
Definition isn.c:78
int i
Definition isn.c:77
char * pstrdup(const char *in)
Definition mcxt.c:1781
void pfree(void *pointer)
Definition mcxt.c:1616
void * palloc0(Size size)
Definition mcxt.c:1417
void * palloc(Size size)
Definition mcxt.c:1387
#define IsA(nodeptr, _type_)
Definition nodes.h:164
static char * errmsg
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
NameData relname
Definition pg_class.h:40
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
#define sprintf
Definition port.h:262
uint64_t Datum
Definition postgres.h:70
static Datum Float8GetDatum(float8 X)
Definition postgres.h:502
unsigned int Oid
static int fb(int x)
char * quote_literal_cstr(const char *rawstr)
Definition quote.c:101
tree ctl
Definition radixtree.h:1838
uint64 SPI_processed
Definition spi.c:45
SPITupleTable * SPI_tuptable
Definition spi.c:46
int SPI_connect(void)
Definition spi.c:95
int SPI_finish(void)
Definition spi.c:183
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_FINISH
Definition spi.h:83
#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
crosstab_cat_desc * catdesc
Definition tablefunc.c:166
char internal_catname[MAX_CATNAME_LEN]
Definition tablefunc.c:165
#define crosstab_HashTableInsert(HASHTAB, CATDESC)
Definition tablefunc.c:147
#define xpstrdup(tgtvar_, srcvar_)
Definition tablefunc.c:108
static void compatCrosstabTupleDescs(TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
Definition tablefunc.c:1522
Datum connectby_text(PG_FUNCTION_ARGS)
Definition tablefunc.c:979
Datum normal_rand(PG_FUNCTION_ARGS)
Definition tablefunc.c:178
Datum crosstab(PG_FUNCTION_ARGS)
Definition tablefunc.c:360
#define MAX_CATNAME_LEN
Definition tablefunc.c:130
#define INIT_CATS
Definition tablefunc.c:131
#define CONNECTBY_NCOLS_NOBRANCH
Definition tablefunc.c:976
static void get_normal_pair(float8 *x1, float8 *x2)
Definition tablefunc.c:289
#define crosstab_HashTableLookup(HASHTAB, CATNAME, CATDESC)
Definition tablefunc.c:133
#define INT32_STRLEN
Definition tablefunc.c:121
static Tuplestorestate * get_crosstab_tuplestore(char *sql, HTAB *crosstab_hash, TupleDesc tupdesc, bool randomAccess)
Definition tablefunc.c:793
Datum connectby_text_serial(PG_FUNCTION_ARGS)
Definition tablefunc.c:1057
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:1190
#define CONNECTBY_NCOLS
Definition tablefunc.c:975
Datum crosstab_hash(PG_FUNCTION_ARGS)
Definition tablefunc.c:638
static void compatConnectbyTupleDescs(TupleDesc ret_tupdesc, TupleDesc sql_tupdesc)
Definition tablefunc.c:1469
#define xpfree(var_)
Definition tablefunc.c:99
#define xstreq(tgtvar_, srcvar_)
Definition tablefunc.c:116
static void validateConnectbyTupleDesc(TupleDesc td, bool show_branch, bool show_serial)
Definition tablefunc.c:1409
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:1139
struct crosstab_hashent crosstab_HashEnt
static HTAB * load_categories_hash(char *cats_sql, MemoryContext per_query_ctx)
Definition tablefunc.c:707
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition tupdesc.c:242
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition tuplestore.c:331
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition tuplestore.c:765
char * text_to_cstring(const text *t)
Definition varlena.c:217
const char * name