PostgreSQL Source Code git master
Loading...
Searching...
No Matches
crosstabview.c
Go to the documentation of this file.
1/*
2 * psql - the PostgreSQL interactive terminal
3 *
4 * Copyright (c) 2000-2026, PostgreSQL Global Development Group
5 *
6 * src/bin/psql/crosstabview.c
7 */
8#include "postgres_fe.h"
9
10#include "catalog/pg_type_d.h"
11#include "common.h"
12#include "common/int.h"
13#include "common/logging.h"
14#include "crosstabview.h"
15#include "pqexpbuffer.h"
16#include "psqlscanslash.h"
17#include "settings.h"
18
19/*
20 * Value/position from the resultset that goes into the horizontal or vertical
21 * crosstabview header.
22 */
23typedef struct _pivot_field
24{
25 /*
26 * Pointer obtained from PQgetvalue() for colV or colH. Each distinct
27 * value becomes an entry in the vertical header (colV), or horizontal
28 * header (colH). A Null value is represented by a NULL pointer.
29 */
30 char *name;
31
32 /*
33 * When a sort is requested on an alternative column, this holds
34 * PQgetvalue() for the sort column corresponding to <name>. If <name>
35 * appear multiple times, it's the first value in the order of the results
36 * that is kept. A Null value is represented by a NULL pointer.
37 */
39
40 /*
41 * Rank of this value, starting at 0. Initially, it's the relative
42 * position of the first appearance of <name> in the resultset. For
43 * example, if successive rows contain B,A,C,A,D then it's B:0,A:1,C:2,D:3
44 * When a sort column is specified, ranks get updated in a final pass to
45 * reflect the desired order.
46 */
47 int rank;
49
50/* Node in avl_tree */
51typedef struct _avl_node
52{
53 /* Node contents */
55
56 /*
57 * Height of this node in the tree (number of nodes on the longest path to
58 * a leaf).
59 */
60 int height;
61
62 /*
63 * Child nodes. [0] points to left subtree, [1] to right subtree. Never
64 * NULL, points to the empty node avl_tree.end when no left or right
65 * value.
66 */
67 struct _avl_node *children[2];
69
70/*
71 * Control structure for the AVL tree (binary search tree kept
72 * balanced with the AVL algorithm)
73 */
74typedef struct _avl_tree
75{
76 int count; /* Total number of nodes */
77 avl_node *root; /* root of the tree */
78 avl_node *end; /* Immutable dereferenceable empty tree */
80
81
82static bool printCrosstab(const PGresult *result,
85 int field_for_data);
86static char *displayValue(char *value, Oid ftype, char *default_null);
87
88static void avlInit(avl_tree *tree);
89static void avlMergeValue(avl_tree *tree, char *name, char *sort_value);
90static int avlCollectFields(avl_tree *tree, avl_node *node,
91 pivot_field *fields, int idx);
92static void avlFree(avl_tree *tree, avl_node *node);
94static int indexOfColumn(char *arg, const PGresult *res);
95static int pivotFieldCompare(const void *a, const void *b);
96static int rankCompare(const void *a, const void *b);
97
98
99/*
100 * Main entry point to this module.
101 *
102 * Process the data from *res according to the options in pset (global),
103 * to generate the horizontal and vertical headers contents,
104 * then call printCrosstab() for the actual output.
105 */
106bool
108{
109 bool retval = false;
114 int num_columns = 0;
115 int num_rows = 0;
116 int field_for_rows;
118 int field_for_data;
120 int rn;
121
124
126 {
127 pg_log_error("\\crosstabview: statement did not return a result set");
128 goto error_return;
129 }
130
131 if (PQnfields(res) < 3)
132 {
133 pg_log_error("\\crosstabview: query must return at least three columns");
134 goto error_return;
135 }
136
137 /* Process first optional arg (vertical header column) */
138 if (pset.ctv_args[0] == NULL)
139 field_for_rows = 0;
140 else
141 {
143 if (field_for_rows < 0)
144 goto error_return;
145 }
146
147 /* Process second optional arg (horizontal header column) */
148 if (pset.ctv_args[1] == NULL)
150 else
151 {
153 if (field_for_columns < 0)
154 goto error_return;
155 }
156
157 /* Insist that header columns be distinct */
159 {
160 pg_log_error("\\crosstabview: vertical and horizontal headers must be different columns");
161 goto error_return;
162 }
163
164 /* Process third optional arg (data column) */
165 if (pset.ctv_args[2] == NULL)
166 {
167 int i;
168
169 /*
170 * If the data column was not specified, we search for the one not
171 * used as either vertical or horizontal headers. Must be exactly
172 * three columns, or this won't be unique.
173 */
174 if (PQnfields(res) != 3)
175 {
176 pg_log_error("\\crosstabview: data column must be specified when query returns more than three columns");
177 goto error_return;
178 }
179
180 field_for_data = -1;
181 for (i = 0; i < PQnfields(res); i++)
182 {
183 if (i != field_for_rows && i != field_for_columns)
184 {
186 break;
187 }
188 }
190 }
191 else
192 {
194 if (field_for_data < 0)
195 goto error_return;
196 }
197
198 /* Process fourth optional arg (horizontal header sort column) */
199 if (pset.ctv_args[3] == NULL)
200 sort_field_for_columns = -1; /* no sort column */
201 else
202 {
205 goto error_return;
206 }
207
208 /*
209 * First part: accumulate the names that go into the vertical and
210 * horizontal headers, each into an AVL binary tree to build the set of
211 * DISTINCT values.
212 */
213
214 for (rn = 0; rn < PQntuples(res); rn++)
215 {
216 char *val;
217 char *val1;
218
219 /* horizontal */
222 val1 = NULL;
223
224 if (sort_field_for_columns >= 0 &&
227
229
231 {
232 pg_log_error("\\crosstabview: maximum number of columns (%d) exceeded",
234 goto error_return;
235 }
236
237 /* vertical */
240
242 }
243
244 /*
245 * Second part: Generate sorted arrays from the AVL trees.
246 */
247
248 num_columns = piv_columns.count;
249 num_rows = piv_rows.count;
250
252
254
257
258 /*
259 * Third part: optionally, process the ranking data for the horizontal
260 * header
261 */
262 if (sort_field_for_columns >= 0)
264
265 /*
266 * Fourth part: print the crosstab'ed result.
267 */
268 retval = printCrosstab(res,
272
275 avlFree(&piv_rows, piv_rows.root);
278
279 return retval;
280}
281
282/*
283 * Output the pivoted resultset with the printTable* functions. Return true
284 * if successful, false otherwise.
285 */
286static bool
290 int field_for_data)
291{
292 printQueryOpt popt = pset.popt;
294 int rn;
295 char col_align;
296 int *horiz_map;
300 bool retval = false;
301
302 printTableInit(&cont, &popt.topt, popt.title, num_columns + 1, num_rows);
303
304 /* Step 1: set target column names (horizontal header) */
305
306 /* The name of the first column is kept unchanged by the pivoting */
309 false,
311
312 /*
313 * To iterate over piv_columns[] by piv_columns[].rank, create a reverse
314 * map associating each piv_columns[].rank to its index in piv_columns.
315 * This avoids an O(N^2) loop later.
316 */
318 for (int i = 0; i < num_columns; i++)
319 horiz_map[piv_columns[i].rank] = i;
320
321 /*
322 * The display alignment depends on its PQftype().
323 */
325
326 for (int i = 0; i < num_columns; i++)
327 {
328 char *colname;
329
331
332 printTableAddHeader(&cont, colname, false, col_align);
333 }
335
336 /* Step 2: set row names in the first output column (vertical header) */
337 for (int i = 0; i < num_rows; i++)
338 {
339 int k = piv_rows[i].rank;
340 int idx = k * (num_columns + 1);
341
342 cont.cells[idx] = displayValue(piv_rows[i].name, row_ftype, "");
343 }
344 cont.cellsadded = num_rows * (num_columns + 1);
345
346 /*
347 * Step 3: fill in the content cells.
348 */
349 for (rn = 0; rn < PQntuples(result); rn++)
350 {
351 int row_number;
352 int col_number;
354 *cp;
356
357 /* Find target row */
360 else
361 elt.name = NULL;
362 rp = (pivot_field *) bsearch(&elt,
363 piv_rows,
364 num_rows,
365 sizeof(pivot_field),
367 Assert(rp != NULL);
368 row_number = rp->rank;
369
370 /* Find target column */
373 else
374 elt.name = NULL;
375
376 cp = (pivot_field *) bsearch(&elt,
379 sizeof(pivot_field),
381 Assert(cp != NULL);
382 col_number = cp->rank;
383
384 /* Place value into cell */
385 if (col_number >= 0 && row_number >= 0)
386 {
387 int idx;
388 char *value;
389
390 /* index into the cont.cells array */
391 idx = 1 + col_number + row_number * (num_columns + 1);
392
393 /*
394 * If the cell already contains a value, raise an error.
395 */
396 if (cont.cells[idx] != NULL)
397 {
398 pg_log_error("\\crosstabview: query result contains multiple data values for row \"%s\", column \"%s\"",
399 displayValue(rp->name, row_ftype, "(null)"),
400 displayValue(cp->name, col_ftype, "(null)"));
401 goto error;
402 }
403
405 value = NULL;
406 else
408 cont.cells[idx] = displayValue(value, data_ftype, "");
409 }
410 }
411
412 /*
413 * The non-initialized cells must be set to an empty string for the print
414 * functions
415 */
416 for (uint64 i = 0; i < cont.cellsadded; i++)
417 {
418 if (cont.cells[i] == NULL)
419 cont.cells[i] = "";
420 }
421
423 retval = true;
424
425error:
427
428 return retval;
429}
430
431/*
432 * Return the display representation of one cell value in \crosstabview,
433 * following pset substitutions.
434 *
435 * The returned pointer is not to be freed.
436 */
437static char *
438displayValue(char *value, Oid ftype, char *default_null)
439{
440 printQueryOpt popt = pset.popt;
441
442 if (value == NULL)
443 value = popt.nullPrint ? popt.nullPrint : default_null;
444 else if (ftype == BOOLOID)
445 {
446 if (value[0] == 't' && popt.truePrint)
447 value = popt.truePrint;
448 else if (value[0] == 'f' && popt.falsePrint)
449 value = popt.falsePrint;
450 }
451
452 return value;
453}
454
455/*
456 * The avl* functions below provide a minimalistic implementation of AVL binary
457 * trees, to efficiently collect the distinct values that will form the horizontal
458 * and vertical headers. It only supports adding new values, no removal or even
459 * search.
460 */
461static void
463{
465 tree->end->children[0] = tree->end->children[1] = tree->end;
466 tree->count = 0;
467 tree->root = tree->end;
468}
469
470/* Deallocate recursively an AVL tree, starting from node */
471static void
473{
474 if (node->children[0] != tree->end)
475 {
476 avlFree(tree, node->children[0]);
477 pg_free(node->children[0]);
478 }
479 if (node->children[1] != tree->end)
480 {
481 avlFree(tree, node->children[1]);
482 pg_free(node->children[1]);
483 }
484 if (node == tree->root)
485 {
486 /* free the root separately as it's not child of anything */
487 if (node != tree->end)
488 pg_free(node);
489 /* free the tree->end struct only once and when all else is freed */
490 pg_free(tree->end);
491 }
492}
493
494/* Set the height to 1 plus the greatest of left and right heights */
495static void
497{
498 n->height = 1 + (n->children[0]->height > n->children[1]->height ?
499 n->children[0]->height :
500 n->children[1]->height);
501}
502
503/* Rotate a subtree left (dir=0) or right (dir=1). Not recursive */
504static avl_node *
505avlRotate(avl_node **current, int dir)
506{
507 avl_node *before = *current;
508 avl_node *after = (*current)->children[dir];
509
510 *current = after;
511 before->children[dir] = after->children[!dir];
513 after->children[!dir] = before;
514
515 return after;
516}
517
518static int
520{
521 return n->children[0]->height - n->children[1]->height;
522}
523
524/*
525 * After an insertion, possibly rebalance the tree so that the left and right
526 * node heights don't differ by more than 1.
527 * May update *node.
528 */
529static void
531{
532 avl_node *current = *node;
533 int b = avlBalance(current) / 2;
534
535 if (b != 0)
536 {
537 int dir = (1 - b) / 2;
538
539 if (avlBalance(current->children[dir]) == -b)
540 avlRotate(&current->children[dir], !dir);
541 current = avlRotate(node, dir);
542 }
543 if (current != tree->end)
544 avlUpdateHeight(current);
545}
546
547/*
548 * Insert a new value/field, starting from *node, reaching the correct position
549 * in the tree by recursion. Possibly rebalance the tree and possibly update
550 * *node. Do nothing if the value is already present in the tree.
551 */
552static void
554{
555 avl_node *current = *node;
556
557 if (current == tree->end)
558 {
560
561 new_node->height = 1;
562 new_node->field = field;
563 new_node->children[0] = new_node->children[1] = tree->end;
564 tree->count++;
565 *node = new_node;
566 }
567 else
568 {
569 int cmp = pivotFieldCompare(&field, &current->field);
570
571 if (cmp != 0)
572 {
574 cmp > 0 ? &current->children[1] : &current->children[0],
575 field);
576 avlAdjustBalance(tree, node);
577 }
578 }
579}
580
581/* Insert the value into the AVL tree, if it does not preexist */
582static void
583avlMergeValue(avl_tree *tree, char *name, char *sort_value)
584{
585 pivot_field field;
586
587 field.name = name;
588 field.rank = tree->count;
589 field.sort_value = sort_value;
590 avlInsertNode(tree, &tree->root, field);
591}
592
593/*
594 * Recursively extract node values into the names array, in sorted order with a
595 * left-to-right tree traversal.
596 * Return the next candidate offset to write into the names array.
597 * fields[] must be preallocated to hold tree->count entries
598 */
599static int
601{
602 if (node == tree->end)
603 return idx;
604
605 idx = avlCollectFields(tree, node->children[0], fields, idx);
606 fields[idx] = node->field;
607 return avlCollectFields(tree, node->children[1], fields, idx + 1);
608}
609
610static void
612{
613 int *hmap; /* [[offset in piv_columns, rank], ...for
614 * every header entry] */
615 int i;
616
617 hmap = pg_malloc_array(int, num_columns * 2);
618 for (i = 0; i < num_columns; i++)
619 {
620 char *val = piv_columns[i].sort_value;
621
622 /* ranking information is valid if non null and matches /^-?\d+$/ */
623 if (val &&
624 ((*val == '-' &&
625 strspn(val + 1, "0123456789") == strlen(val + 1)) ||
626 strspn(val, "0123456789") == strlen(val)))
627 {
628 hmap[i * 2] = atoi(val);
629 hmap[i * 2 + 1] = i;
630 }
631 else
632 {
633 /* invalid rank information ignored (equivalent to rank 0) */
634 hmap[i * 2] = 0;
635 hmap[i * 2 + 1] = i;
636 }
637 }
638
639 qsort(hmap, num_columns, sizeof(int) * 2, rankCompare);
640
641 for (i = 0; i < num_columns; i++)
642 {
643 piv_columns[hmap[i * 2 + 1]].rank = i;
644 }
645
646 pg_free(hmap);
647}
648
649/*
650 * Look up a column reference, which can be either:
651 * - a number from 1 to PQnfields(res)
652 * - a column name matching one of PQfname(res,...)
653 *
654 * Returns zero-based column number, or -1 if not found or ambiguous.
655 *
656 * Note: may modify contents of "arg" string.
657 */
658static int
659indexOfColumn(char *arg, const PGresult *res)
660{
661 int idx;
662
663 if (arg[0] && strspn(arg, "0123456789") == strlen(arg))
664 {
665 /* if arg contains only digits, it's a column number */
666 idx = atoi(arg) - 1;
667 if (idx < 0 || idx >= PQnfields(res))
668 {
669 pg_log_error("\\crosstabview: column number %d is out of range 1..%d",
670 idx + 1, PQnfields(res));
671 return -1;
672 }
673 }
674 else
675 {
676 int i;
677
678 /*
679 * Dequote and downcase the column name. By checking for all-digits
680 * before doing this, we can ensure that a quoted name is treated as a
681 * name even if it's all digits.
682 */
684
685 /* Now look for match(es) among res' column names */
686 idx = -1;
687 for (i = 0; i < PQnfields(res); i++)
688 {
689 if (strcmp(arg, PQfname(res, i)) == 0)
690 {
691 if (idx >= 0)
692 {
693 /* another idx was already found for the same name */
694 pg_log_error("\\crosstabview: ambiguous column name: \"%s\"", arg);
695 return -1;
696 }
697 idx = i;
698 }
699 }
700 if (idx == -1)
701 {
702 pg_log_error("\\crosstabview: column name not found: \"%s\"", arg);
703 return -1;
704 }
705 }
706
707 return idx;
708}
709
710/*
711 * Value comparator for vertical and horizontal headers
712 * used for deduplication only.
713 * - null values are considered equal
714 * - non-null < null
715 * - non-null values are compared with strcmp()
716 */
717static int
718pivotFieldCompare(const void *a, const void *b)
719{
720 const pivot_field *pa = (const pivot_field *) a;
721 const pivot_field *pb = (const pivot_field *) b;
722
723 /* test null values */
724 if (!pb->name)
725 return pa->name ? -1 : 0;
726 else if (!pa->name)
727 return 1;
728
729 /* non-null values */
730 return strcmp(pa->name, pb->name);
731}
732
733static int
734rankCompare(const void *a, const void *b)
735{
736 return pg_cmp_s32(*(const int *) a, *(const int *) b);
737}
Datum idx(PG_FUNCTION_ARGS)
Definition _int_op.c:263
#define Assert(condition)
Definition c.h:1002
uint64_t uint64
Definition c.h:684
uint32 result
static void avlUpdateHeight(avl_node *n)
static int avlCollectFields(avl_tree *tree, avl_node *node, pivot_field *fields, int idx)
static int pivotFieldCompare(const void *a, const void *b)
static void avlInsertNode(avl_tree *tree, avl_node **node, pivot_field field)
static int rankCompare(const void *a, const void *b)
struct _avl_tree avl_tree
static void avlFree(avl_tree *tree, avl_node *node)
static bool printCrosstab(const PGresult *result, int num_columns, pivot_field *piv_columns, int field_for_columns, int num_rows, pivot_field *piv_rows, int field_for_rows, int field_for_data)
static void rankSort(int num_columns, pivot_field *piv_columns)
bool PrintResultInCrosstab(const PGresult *res)
static char * displayValue(char *value, Oid ftype, char *default_null)
static int avlBalance(avl_node *n)
static int indexOfColumn(char *arg, const PGresult *res)
static avl_node * avlRotate(avl_node **current, int dir)
static void avlInit(avl_tree *tree)
static void avlMergeValue(avl_tree *tree, char *name, char *sort_value)
struct _avl_node avl_node
struct _pivot_field pivot_field
static void avlAdjustBalance(avl_tree *tree, avl_node **node)
#define CROSSTABVIEW_MAX_COLUMNS
Datum arg
Definition elog.c:1323
Oid PQftype(const PGresult *res, int field_num)
Definition fe-exec.c:3750
void pg_free(void *ptr)
#define pg_malloc_array(type, count)
Definition fe_memutils.h:66
#define pg_malloc0_object(type)
Definition fe_memutils.h:61
#define pg_malloc_object(type)
Definition fe_memutils.h:60
void printTableInit(printTableContent *const content, const printTableOpt *opt, const char *title, const int ncolumns, const int nrows)
Definition print.c:3209
void printTableCleanup(printTableContent *const content)
Definition print.c:3390
char column_type_alignment(Oid ftype)
Definition print.c:3829
void printTable(const printTableContent *cont, FILE *fout, bool is_pager, FILE *flog)
Definition print.c:3654
void printTableAddHeader(printTableContent *const content, char *header, const bool translate, const char align)
Definition print.c:3257
long val
Definition informix.c:689
static struct @175 value
static int pg_cmp_s32(int32 a, int32 b)
Definition int.h:713
int b
Definition isn.c:74
int a
Definition isn.c:73
int i
Definition isn.c:77
#define PQgetvalue
#define PQnfields
#define PQresultStatus
#define PQgetisnull
#define PQfname
#define PQntuples
@ PGRES_TUPLES_OK
Definition libpq-fe.h:134
#define pg_log_error(...)
Definition logging.h:108
#define qsort(a, b, c, d)
Definition port.h:496
unsigned int Oid
static int fb(int x)
void dequote_downcase_identifier(char *str, bool downcase, int encoding)
tree
Definition radixtree.h:1828
static int cmp(const chr *x, const chr *y, size_t len)
static int before(chr x, chr y)
PsqlSettings pset
Definition startup.c:33
static void error(void)
struct _avl_node * children[2]
pivot_field field
avl_node * root
avl_node * end
char * sort_value
printQueryOpt popt
Definition settings.h:112
FILE * logfile
Definition settings.h:149
char * ctv_args[4]
Definition settings.h:133
FILE * queryFout
Definition settings.h:105
printTableOpt topt
Definition print.h:185
char * nullPrint
Definition print.h:186
char * falsePrint
Definition print.h:188
char * title
Definition print.h:189
char * truePrint
Definition print.h:187
const char * name