postgresql/src/backend/nodes/print.c

507 lines
9.7 KiB
C
Raw Normal View History

/*-------------------------------------------------------------------------
*
* print.c
* various print routines (used mostly for debugging)
*
* Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
2010-09-20 22:08:53 +02:00
* src/backend/nodes/print.c
*
* HISTORY
* AUTHOR DATE MAJOR EVENT
* Andrew Yu Oct 26, 1994 file creation
*
*-------------------------------------------------------------------------
*/
1996-11-06 09:54:17 +01:00
#include "postgres.h"
1996-11-06 09:54:17 +01:00
#include "access/printtup.h"
#include "lib/stringinfo.h"
#include "nodes/nodeFuncs.h"
#include "nodes/pathnodes.h"
#include "nodes/print.h"
#include "parser/parsetree.h"
#include "utils/lsyscache.h"
/*
* print
* print contents of Node to stdout
*/
void
print(const void *obj)
{
char *s;
char *f;
s = nodeToString(obj);
f = format_node_dump(s);
pfree(s);
printf("%s\n", f);
fflush(stdout);
pfree(f);
}
/*
* pprint
* pretty-print contents of Node to stdout
*/
void
pprint(const void *obj)
{
char *s;
char *f;
s = nodeToString(obj);
f = pretty_format_node_dump(s);
pfree(s);
printf("%s\n", f);
fflush(stdout);
pfree(f);
}
/*
* elog_node_display
* send pretty-printed contents of Node to postmaster log
*/
void
elog_node_display(int lev, const char *title, const void *obj, bool pretty)
{
char *s;
char *f;
s = nodeToString(obj);
if (pretty)
f = pretty_format_node_dump(s);
else
f = format_node_dump(s);
pfree(s);
ereport(lev,
(errmsg_internal("%s:", title),
errdetail_internal("%s", f)));
pfree(f);
}
/*
* Format a nodeToString output for display on a terminal.
*
* The result is a palloc'd string.
*
* This version just tries to break at whitespace.
*/
char *
format_node_dump(const char *dump)
{
#define LINELEN 78
2002-09-04 22:31:48 +02:00
char line[LINELEN + 1];
StringInfoData str;
int i;
int j;
int k;
initStringInfo(&str);
i = 0;
for (;;)
{
for (j = 0; j < LINELEN && dump[i] != '\0'; i++, j++)
line[j] = dump[i];
if (dump[i] == '\0')
break;
if (dump[i] == ' ')
{
/* ok to break at adjacent space */
i++;
}
else
{
2002-09-04 22:31:48 +02:00
for (k = j - 1; k > 0; k--)
if (line[k] == ' ')
break;
if (k > 0)
{
/* back up; will reprint all after space */
2002-09-04 22:31:48 +02:00
i -= (j - k - 1);
j = k;
}
}
line[j] = '\0';
appendStringInfo(&str, "%s\n", line);
}
if (j > 0)
{
line[j] = '\0';
appendStringInfo(&str, "%s\n", line);
}
return str.data;
#undef LINELEN
}
/*
* Format a nodeToString output for display on a terminal.
*
* The result is a palloc'd string.
*
* This version tries to indent intelligently.
*/
char *
pretty_format_node_dump(const char *dump)
{
#define INDENTSTOP 3
#define MAXINDENT 60
#define LINELEN 78
2002-09-04 22:31:48 +02:00
char line[LINELEN + 1];
StringInfoData str;
int indentLev;
int indentDist;
int i;
int j;
initStringInfo(&str);
indentLev = 0; /* logical indent level */
indentDist = 0; /* physical indent distance */
i = 0;
for (;;)
{
for (j = 0; j < indentDist; j++)
line[j] = ' ';
for (; j < LINELEN && dump[i] != '\0'; i++, j++)
{
line[j] = dump[i];
switch (line[j])
{
case '}':
if (j != indentDist)
{
/* print data before the } */
line[j] = '\0';
appendStringInfo(&str, "%s\n", line);
}
/* print the } at indentDist */
line[indentDist] = '}';
2002-09-04 22:31:48 +02:00
line[indentDist + 1] = '\0';
appendStringInfo(&str, "%s\n", line);
/* outdent */
if (indentLev > 0)
{
indentLev--;
2001-12-20 03:39:26 +01:00
indentDist = Min(indentLev * INDENTSTOP, MAXINDENT);
}
j = indentDist - 1;
/* j will equal indentDist on next loop iteration */
/* suppress whitespace just after } */
2004-08-29 07:07:03 +02:00
while (dump[i + 1] == ' ')
i++;
break;
case ')':
/* force line break after ), unless another ) follows */
2004-08-29 07:07:03 +02:00
if (dump[i + 1] != ')')
{
line[j + 1] = '\0';
appendStringInfo(&str, "%s\n", line);
j = indentDist - 1;
2004-08-29 07:07:03 +02:00
while (dump[i + 1] == ' ')
i++;
}
break;
case '{':
/* force line break before { */
if (j != indentDist)
{
line[j] = '\0';
appendStringInfo(&str, "%s\n", line);
}
/* indent */
indentLev++;
2001-12-20 03:39:26 +01:00
indentDist = Min(indentLev * INDENTSTOP, MAXINDENT);
for (j = 0; j < indentDist; j++)
line[j] = ' ';
line[j] = dump[i];
break;
case ':':
/* force line break before : */
if (j != indentDist)
{
line[j] = '\0';
appendStringInfo(&str, "%s\n", line);
}
j = indentDist;
line[j] = dump[i];
break;
}
}
line[j] = '\0';
if (dump[i] == '\0')
break;
appendStringInfo(&str, "%s\n", line);
}
if (j > 0)
appendStringInfo(&str, "%s\n", line);
return str.data;
#undef INDENTSTOP
#undef MAXINDENT
#undef LINELEN
}
/*
* print_rt
* print contents of range table
*/
void
print_rt(const List *rtable)
{
const ListCell *l;
int i = 1;
printf("resno\trefname \trelid\tinFromCl\n");
printf("-----\t---------\t-----\t--------\n");
foreach(l, rtable)
{
RangeTblEntry *rte = lfirst(l);
switch (rte->rtekind)
{
case RTE_RELATION:
printf("%d\t%s\t%u\t%c",
i, rte->eref->aliasname, rte->relid, rte->relkind);
break;
case RTE_SUBQUERY:
printf("%d\t%s\t[subquery]",
i, rte->eref->aliasname);
break;
case RTE_JOIN:
printf("%d\t%s\t[join]",
i, rte->eref->aliasname);
break;
case RTE_FUNCTION:
printf("%d\t%s\t[rangefunction]",
i, rte->eref->aliasname);
break;
case RTE_TABLEFUNC:
printf("%d\t%s\t[table function]",
i, rte->eref->aliasname);
break;
case RTE_VALUES:
printf("%d\t%s\t[values list]",
i, rte->eref->aliasname);
break;
case RTE_CTE:
printf("%d\t%s\t[cte]",
i, rte->eref->aliasname);
break;
case RTE_NAMEDTUPLESTORE:
printf("%d\t%s\t[tuplestore]",
i, rte->eref->aliasname);
break;
In the planner, replace an empty FROM clause with a dummy RTE. The fact that "SELECT expression" has no base relations has long been a thorn in the side of the planner. It makes it hard to flatten a sub-query that looks like that, or is a trivial VALUES() item, because the planner generally uses relid sets to identify sub-relations, and such a sub-query would have an empty relid set if we flattened it. prepjointree.c contains some baroque logic that works around this in certain special cases --- but there is a much better answer. We can replace an empty FROM clause with a dummy RTE that acts like a table of one row and no columns, and then there are no such corner cases to worry about. Instead we need some logic to get rid of useless dummy RTEs, but that's simpler and covers more cases than what was there before. For really trivial cases, where the query is just "SELECT expression" and nothing else, there's a hazard that adding the extra RTE makes for a noticeable slowdown; even though it's not much processing, there's not that much for the planner to do overall. However testing says that the penalty is very small, close to the noise level. In more complex queries, this is able to find optimizations that we could not find before. The new RTE type is called RTE_RESULT, since the "scan" plan type it gives rise to is a Result node (the same plan we produced for a "SELECT expression" query before). To avoid confusion, rename the old ResultPath path type to GroupResultPath, reflecting that it's only used in degenerate grouping cases where we know the query produces just one grouped row. (It wouldn't work to unify the two cases, because there are different rules about where the associated quals live during query_planner.) Note: although this touches readfuncs.c, I don't think a catversion bump is required, because the added case can't occur in stored rules, only plans. Patch by me, reviewed by David Rowley and Mark Dilger Discussion: https://postgr.es/m/15944.1521127664@sss.pgh.pa.us
2019-01-28 23:54:10 +01:00
case RTE_RESULT:
printf("%d\t%s\t[result]",
i, rte->eref->aliasname);
break;
default:
printf("%d\t%s\t[unknown rtekind]",
i, rte->eref->aliasname);
}
printf("\t%s\t%s\n",
(rte->inh ? "inh" : ""),
(rte->inFromCl ? "inFromCl" : ""));
i++;
}
}
/*
* print_expr
* print an expression
*/
void
print_expr(const Node *expr, const List *rtable)
{
if (expr == NULL)
{
1998-01-07 16:32:47 +01:00
printf("<>");
return;
}
if (IsA(expr, Var))
{
const Var *var = (const Var *) expr;
char *relname,
*attname;
switch (var->varno)
{
case INNER_VAR:
relname = "INNER";
attname = "?";
break;
case OUTER_VAR:
relname = "OUTER";
attname = "?";
break;
case INDEX_VAR:
relname = "INDEX";
attname = "?";
break;
default:
{
RangeTblEntry *rte;
Assert(var->varno > 0 &&
(int) var->varno <= list_length(rtable));
rte = rt_fetch(var->varno, rtable);
relname = rte->eref->aliasname;
attname = get_rte_attribute_name(rte, var->varattno);
}
break;
}
printf("%s.%s", relname, attname);
}
else if (IsA(expr, Const))
{
const Const *c = (const Const *) expr;
Oid typoutput;
bool typIsVarlena;
char *outputstr;
if (c->constisnull)
{
printf("NULL");
return;
}
getTypeOutputInfo(c->consttype,
&typoutput, &typIsVarlena);
outputstr = OidOutputFunctionCall(typoutput, c->constvalue);
printf("%s", outputstr);
pfree(outputstr);
}
else if (IsA(expr, OpExpr))
{
const OpExpr *e = (const OpExpr *) expr;
char *opname;
opname = get_opname(e->opno);
if (list_length(e->args) > 1)
{
print_expr(get_leftop((const Expr *) e), rtable);
printf(" %s ", ((opname != NULL) ? opname : "(invalid operator)"));
print_expr(get_rightop((const Expr *) e), rtable);
}
else
{
printf("%s ", ((opname != NULL) ? opname : "(invalid operator)"));
print_expr(get_leftop((const Expr *) e), rtable);
}
}
else if (IsA(expr, FuncExpr))
{
const FuncExpr *e = (const FuncExpr *) expr;
char *funcname;
ListCell *l;
funcname = get_func_name(e->funcid);
printf("%s(", ((funcname != NULL) ? funcname : "(invalid function)"));
foreach(l, e->args)
{
print_expr(lfirst(l), rtable);
Represent Lists as expansible arrays, not chains of cons-cells. Originally, Postgres Lists were a more or less exact reimplementation of Lisp lists, which consist of chains of separately-allocated cons cells, each having a value and a next-cell link. We'd hacked that once before (commit d0b4399d8) to add a separate List header, but the data was still in cons cells. That makes some operations -- notably list_nth() -- O(N), and it's bulky because of the next-cell pointers and per-cell palloc overhead, and it's very cache-unfriendly if the cons cells end up scattered around rather than being adjacent. In this rewrite, we still have List headers, but the data is in a resizable array of values, with no next-cell links. Now we need at most two palloc's per List, and often only one, since we can allocate some values in the same palloc call as the List header. (Of course, extending an existing List may require repalloc's to enlarge the array. But this involves just O(log N) allocations not O(N).) Of course this is not without downsides. The key difficulty is that addition or deletion of a list entry may now cause other entries to move, which it did not before. For example, that breaks foreach() and sister macros, which historically used a pointer to the current cons-cell as loop state. We can repair those macros transparently by making their actual loop state be an integer list index; the exposed "ListCell *" pointer is no longer state carried across loop iterations, but is just a derived value. (In practice, modern compilers can optimize things back to having just one loop state value, at least for simple cases with inline loop bodies.) In principle, this is a semantics change for cases where the loop body inserts or deletes list entries ahead of the current loop index; but I found no such cases in the Postgres code. The change is not at all transparent for code that doesn't use foreach() but chases lists "by hand" using lnext(). The largest share of such code in the backend is in loops that were maintaining "prev" and "next" variables in addition to the current-cell pointer, in order to delete list cells efficiently using list_delete_cell(). However, we no longer need a previous-cell pointer to delete a list cell efficiently. Keeping a next-cell pointer doesn't work, as explained above, but we can improve matters by changing such code to use a regular foreach() loop and then using the new macro foreach_delete_current() to delete the current cell. (This macro knows how to update the associated foreach loop's state so that no cells will be missed in the traversal.) There remains a nontrivial risk of code assuming that a ListCell * pointer will remain good over an operation that could now move the list contents. To help catch such errors, list.c can be compiled with a new define symbol DEBUG_LIST_MEMORY_USAGE that forcibly moves list contents whenever that could possibly happen. This makes list operations significantly more expensive so it's not normally turned on (though it is on by default if USE_VALGRIND is on). There are two notable API differences from the previous code: * lnext() now requires the List's header pointer in addition to the current cell's address. * list_delete_cell() no longer requires a previous-cell argument. These changes are somewhat unfortunate, but on the other hand code using either function needs inspection to see if it is assuming anything it shouldn't, so it's not all bad. Programmers should be aware of these significant performance changes: * list_nth() and related functions are now O(1); so there's no major access-speed difference between a list and an array. * Inserting or deleting a list element now takes time proportional to the distance to the end of the list, due to moving the array elements. (However, it typically *doesn't* require palloc or pfree, so except in long lists it's probably still faster than before.) Notably, lcons() used to be about the same cost as lappend(), but that's no longer true if the list is long. Code that uses lcons() and list_delete_first() to maintain a stack might usefully be rewritten to push and pop at the end of the list rather than the beginning. * There are now list_insert_nth...() and list_delete_nth...() functions that add or remove a list cell identified by index. These have the data-movement penalty explained above, but there's no search penalty. * list_concat() and variants now copy the second list's data into storage belonging to the first list, so there is no longer any sharing of cells between the input lists. The second argument is now declared "const List *" to reflect that it isn't changed. This patch just does the minimum needed to get the new implementation in place and fix bugs exposed by the regression tests. As suggested by the foregoing, there's a fair amount of followup work remaining to do. Also, the ENABLE_LIST_COMPAT macros are finally removed in this commit. Code using those should have been gone a dozen years ago. Patch by me; thanks to David Rowley, Jesper Pedersen, and others for review. Discussion: https://postgr.es/m/11587.1550975080@sss.pgh.pa.us
2019-07-15 19:41:58 +02:00
if (lnext(e->args, l))
printf(",");
}
printf(")");
}
else
printf("unknown expr");
}
/*
* print_pathkeys -
* pathkeys list of PathKeys
*/
void
print_pathkeys(const List *pathkeys, const List *rtable)
{
const ListCell *i;
printf("(");
1999-02-20 20:02:43 +01:00
foreach(i, pathkeys)
{
2007-11-15 22:14:46 +01:00
PathKey *pathkey = (PathKey *) lfirst(i);
EquivalenceClass *eclass;
ListCell *k;
bool first = true;
eclass = pathkey->pk_eclass;
/* chase up, in case pathkey is non-canonical */
while (eclass->ec_merged)
eclass = eclass->ec_merged;
1999-02-20 20:02:43 +01:00
printf("(");
foreach(k, eclass->ec_members)
1999-02-20 20:02:43 +01:00
{
EquivalenceMember *mem = (EquivalenceMember *) lfirst(k);
1999-05-25 18:15:34 +02:00
if (first)
first = false;
else
1999-02-20 20:02:43 +01:00
printf(", ");
print_expr((Node *) mem->em_expr, rtable);
1999-02-20 20:02:43 +01:00
}
printf(")");
Represent Lists as expansible arrays, not chains of cons-cells. Originally, Postgres Lists were a more or less exact reimplementation of Lisp lists, which consist of chains of separately-allocated cons cells, each having a value and a next-cell link. We'd hacked that once before (commit d0b4399d8) to add a separate List header, but the data was still in cons cells. That makes some operations -- notably list_nth() -- O(N), and it's bulky because of the next-cell pointers and per-cell palloc overhead, and it's very cache-unfriendly if the cons cells end up scattered around rather than being adjacent. In this rewrite, we still have List headers, but the data is in a resizable array of values, with no next-cell links. Now we need at most two palloc's per List, and often only one, since we can allocate some values in the same palloc call as the List header. (Of course, extending an existing List may require repalloc's to enlarge the array. But this involves just O(log N) allocations not O(N).) Of course this is not without downsides. The key difficulty is that addition or deletion of a list entry may now cause other entries to move, which it did not before. For example, that breaks foreach() and sister macros, which historically used a pointer to the current cons-cell as loop state. We can repair those macros transparently by making their actual loop state be an integer list index; the exposed "ListCell *" pointer is no longer state carried across loop iterations, but is just a derived value. (In practice, modern compilers can optimize things back to having just one loop state value, at least for simple cases with inline loop bodies.) In principle, this is a semantics change for cases where the loop body inserts or deletes list entries ahead of the current loop index; but I found no such cases in the Postgres code. The change is not at all transparent for code that doesn't use foreach() but chases lists "by hand" using lnext(). The largest share of such code in the backend is in loops that were maintaining "prev" and "next" variables in addition to the current-cell pointer, in order to delete list cells efficiently using list_delete_cell(). However, we no longer need a previous-cell pointer to delete a list cell efficiently. Keeping a next-cell pointer doesn't work, as explained above, but we can improve matters by changing such code to use a regular foreach() loop and then using the new macro foreach_delete_current() to delete the current cell. (This macro knows how to update the associated foreach loop's state so that no cells will be missed in the traversal.) There remains a nontrivial risk of code assuming that a ListCell * pointer will remain good over an operation that could now move the list contents. To help catch such errors, list.c can be compiled with a new define symbol DEBUG_LIST_MEMORY_USAGE that forcibly moves list contents whenever that could possibly happen. This makes list operations significantly more expensive so it's not normally turned on (though it is on by default if USE_VALGRIND is on). There are two notable API differences from the previous code: * lnext() now requires the List's header pointer in addition to the current cell's address. * list_delete_cell() no longer requires a previous-cell argument. These changes are somewhat unfortunate, but on the other hand code using either function needs inspection to see if it is assuming anything it shouldn't, so it's not all bad. Programmers should be aware of these significant performance changes: * list_nth() and related functions are now O(1); so there's no major access-speed difference between a list and an array. * Inserting or deleting a list element now takes time proportional to the distance to the end of the list, due to moving the array elements. (However, it typically *doesn't* require palloc or pfree, so except in long lists it's probably still faster than before.) Notably, lcons() used to be about the same cost as lappend(), but that's no longer true if the list is long. Code that uses lcons() and list_delete_first() to maintain a stack might usefully be rewritten to push and pop at the end of the list rather than the beginning. * There are now list_insert_nth...() and list_delete_nth...() functions that add or remove a list cell identified by index. These have the data-movement penalty explained above, but there's no search penalty. * list_concat() and variants now copy the second list's data into storage belonging to the first list, so there is no longer any sharing of cells between the input lists. The second argument is now declared "const List *" to reflect that it isn't changed. This patch just does the minimum needed to get the new implementation in place and fix bugs exposed by the regression tests. As suggested by the foregoing, there's a fair amount of followup work remaining to do. Also, the ENABLE_LIST_COMPAT macros are finally removed in this commit. Code using those should have been gone a dozen years ago. Patch by me; thanks to David Rowley, Jesper Pedersen, and others for review. Discussion: https://postgr.es/m/11587.1550975080@sss.pgh.pa.us
2019-07-15 19:41:58 +02:00
if (lnext(pathkeys, i))
printf(", ");
}
printf(")\n");
}
/*
1999-05-25 18:15:34 +02:00
* print_tl
* print targetlist in a more legible way.
*/
void
print_tl(const List *tlist, const List *rtable)
{
const ListCell *tl;
printf("(\n");
foreach(tl, tlist)
{
TargetEntry *tle = (TargetEntry *) lfirst(tl);
printf("\t%d %s\t", tle->resno,
tle->resname ? tle->resname : "<null>");
if (tle->ressortgroupref != 0)
printf("(%u):\t", tle->ressortgroupref);
else
printf(" :\t");
print_expr((Node *) tle->expr, rtable);
printf("\n");
}
printf(")\n");
}
/*
* print_slot
* print out the tuple with the given TupleTableSlot
*/
void
print_slot(TupleTableSlot *slot)
{
if (TupIsNull(slot))
{
printf("tuple is null.\n");
return;
}
if (!slot->tts_tupleDescriptor)
{
printf("no tuple descriptor.\n");
return;
}
debugtup(slot, NULL);
}