PostgreSQL Source Code  git master
describe.c
Go to the documentation of this file.
1 /*
2  * psql - the PostgreSQL interactive terminal
3  *
4  * Support for the various \d ("describe") commands. Note that the current
5  * expectation is that all functions in this file will succeed when working
6  * with servers of versions 9.2 and up. It's okay to omit irrelevant
7  * information for an old server, but not to fail outright. (But failing
8  * against a pre-9.2 server is allowed.)
9  *
10  * Copyright (c) 2000-2024, PostgreSQL Global Development Group
11  *
12  * src/bin/psql/describe.c
13  */
14 #include "postgres_fe.h"
15 
16 #include <ctype.h>
17 
18 #include "catalog/pg_am.h"
19 #include "catalog/pg_attribute_d.h"
20 #include "catalog/pg_cast_d.h"
21 #include "catalog/pg_class_d.h"
22 #include "catalog/pg_default_acl_d.h"
23 #include "common.h"
24 #include "common/logging.h"
25 #include "describe.h"
26 #include "fe_utils/mbprint.h"
27 #include "fe_utils/print.h"
28 #include "fe_utils/string_utils.h"
29 #include "settings.h"
30 #include "variables.h"
31 
32 static const char *map_typename_pattern(const char *pattern);
33 static bool describeOneTableDetails(const char *schemaname,
34  const char *relationname,
35  const char *oid,
36  bool verbose);
37 static void add_tablespace_footer(printTableContent *const cont, char relkind,
38  Oid tablespace, const bool newline);
39 static void add_role_attribute(PQExpBuffer buf, const char *const str);
40 static bool listTSParsersVerbose(const char *pattern);
41 static bool describeOneTSParser(const char *oid, const char *nspname,
42  const char *prsname);
43 static bool listTSConfigsVerbose(const char *pattern);
44 static bool describeOneTSConfig(const char *oid, const char *nspname,
45  const char *cfgname,
46  const char *pnspname, const char *prsname);
47 static void printACLColumn(PQExpBuffer buf, const char *colname);
48 static bool listOneExtensionContents(const char *extname, const char *oid);
49 static bool validateSQLNamePattern(PQExpBuffer buf, const char *pattern,
50  bool have_where, bool force_escape,
51  const char *schemavar, const char *namevar,
52  const char *altnamevar,
53  const char *visibilityrule,
54  bool *added_clause, int maxparts);
55 
56 
57 /*----------------
58  * Handlers for various slash commands displaying some sort of list
59  * of things in the database.
60  *
61  * Note: try to format the queries to look nice in -E output.
62  *----------------
63  */
64 
65 
66 /*
67  * \da
68  * Takes an optional regexp to select particular aggregates
69  */
70 bool
71 describeAggregates(const char *pattern, bool verbose, bool showSystem)
72 {
74  PGresult *res;
75  printQueryOpt myopt = pset.popt;
76 
78 
80  "SELECT n.nspname as \"%s\",\n"
81  " p.proname AS \"%s\",\n"
82  " pg_catalog.format_type(p.prorettype, NULL) AS \"%s\",\n"
83  " CASE WHEN p.pronargs = 0\n"
84  " THEN CAST('*' AS pg_catalog.text)\n"
85  " ELSE pg_catalog.pg_get_function_arguments(p.oid)\n"
86  " END AS \"%s\",\n",
87  gettext_noop("Schema"),
88  gettext_noop("Name"),
89  gettext_noop("Result data type"),
90  gettext_noop("Argument data types"));
91 
92  if (pset.sversion >= 110000)
94  " pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"\n"
95  "FROM pg_catalog.pg_proc p\n"
96  " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n"
97  "WHERE p.prokind = 'a'\n",
98  gettext_noop("Description"));
99  else
101  " pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"\n"
102  "FROM pg_catalog.pg_proc p\n"
103  " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n"
104  "WHERE p.proisagg\n",
105  gettext_noop("Description"));
106 
107  if (!showSystem && !pattern)
108  appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
109  " AND n.nspname <> 'information_schema'\n");
110 
111  if (!validateSQLNamePattern(&buf, pattern, true, false,
112  "n.nspname", "p.proname", NULL,
113  "pg_catalog.pg_function_is_visible(p.oid)",
114  NULL, 3))
115  {
117  return false;
118  }
119 
120  appendPQExpBufferStr(&buf, "ORDER BY 1, 2, 4;");
121 
122  res = PSQLexec(buf.data);
124  if (!res)
125  return false;
126 
127  myopt.title = _("List of aggregate functions");
128  myopt.translate_header = true;
129 
130  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
131 
132  PQclear(res);
133  return true;
134 }
135 
136 /*
137  * \dA
138  * Takes an optional regexp to select particular access methods
139  */
140 bool
141 describeAccessMethods(const char *pattern, bool verbose)
142 {
144  PGresult *res;
145  printQueryOpt myopt = pset.popt;
146  static const bool translate_columns[] = {false, true, false, false};
147 
148  if (pset.sversion < 90600)
149  {
150  char sverbuf[32];
151 
152  pg_log_error("The server (version %s) does not support access methods.",
154  sverbuf, sizeof(sverbuf)));
155  return true;
156  }
157 
159 
161  "SELECT amname AS \"%s\",\n"
162  " CASE amtype"
163  " WHEN 'i' THEN '%s'"
164  " WHEN 't' THEN '%s'"
165  " END AS \"%s\"",
166  gettext_noop("Name"),
167  gettext_noop("Index"),
168  gettext_noop("Table"),
169  gettext_noop("Type"));
170 
171  if (verbose)
172  {
174  ",\n amhandler AS \"%s\",\n"
175  " pg_catalog.obj_description(oid, 'pg_am') AS \"%s\"",
176  gettext_noop("Handler"),
177  gettext_noop("Description"));
178  }
179 
181  "\nFROM pg_catalog.pg_am\n");
182 
183  if (!validateSQLNamePattern(&buf, pattern, false, false,
184  NULL, "amname", NULL,
185  NULL,
186  NULL, 1))
187  {
189  return false;
190  }
191 
192  appendPQExpBufferStr(&buf, "ORDER BY 1;");
193 
194  res = PSQLexec(buf.data);
196  if (!res)
197  return false;
198 
199  myopt.title = _("List of access methods");
200  myopt.translate_header = true;
201  myopt.translate_columns = translate_columns;
202  myopt.n_translate_columns = lengthof(translate_columns);
203 
204  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
205 
206  PQclear(res);
207  return true;
208 }
209 
210 /*
211  * \db
212  * Takes an optional regexp to select particular tablespaces
213  */
214 bool
215 describeTablespaces(const char *pattern, bool verbose)
216 {
218  PGresult *res;
219  printQueryOpt myopt = pset.popt;
220 
222 
224  "SELECT spcname AS \"%s\",\n"
225  " pg_catalog.pg_get_userbyid(spcowner) AS \"%s\",\n"
226  " pg_catalog.pg_tablespace_location(oid) AS \"%s\"",
227  gettext_noop("Name"),
228  gettext_noop("Owner"),
229  gettext_noop("Location"));
230 
231  if (verbose)
232  {
233  appendPQExpBufferStr(&buf, ",\n ");
234  printACLColumn(&buf, "spcacl");
236  ",\n spcoptions AS \"%s\""
237  ",\n pg_catalog.pg_size_pretty(pg_catalog.pg_tablespace_size(oid)) AS \"%s\""
238  ",\n pg_catalog.shobj_description(oid, 'pg_tablespace') AS \"%s\"",
239  gettext_noop("Options"),
240  gettext_noop("Size"),
241  gettext_noop("Description"));
242  }
243 
245  "\nFROM pg_catalog.pg_tablespace\n");
246 
247  if (!validateSQLNamePattern(&buf, pattern, false, false,
248  NULL, "spcname", NULL,
249  NULL,
250  NULL, 1))
251  {
253  return false;
254  }
255 
256  appendPQExpBufferStr(&buf, "ORDER BY 1;");
257 
258  res = PSQLexec(buf.data);
260  if (!res)
261  return false;
262 
263  myopt.title = _("List of tablespaces");
264  myopt.translate_header = true;
265 
266  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
267 
268  PQclear(res);
269  return true;
270 }
271 
272 
273 /*
274  * \df
275  * Takes an optional regexp to select particular functions.
276  *
277  * As with \d, you can specify the kinds of functions you want:
278  *
279  * a for aggregates
280  * n for normal
281  * p for procedure
282  * t for trigger
283  * w for window
284  *
285  * and you can mix and match these in any order.
286  */
287 bool
288 describeFunctions(const char *functypes, const char *func_pattern,
289  char **arg_patterns, int num_arg_patterns,
290  bool verbose, bool showSystem)
291 {
292  bool showAggregate = strchr(functypes, 'a') != NULL;
293  bool showNormal = strchr(functypes, 'n') != NULL;
294  bool showProcedure = strchr(functypes, 'p') != NULL;
295  bool showTrigger = strchr(functypes, 't') != NULL;
296  bool showWindow = strchr(functypes, 'w') != NULL;
297  bool have_where;
299  PGresult *res;
300  printQueryOpt myopt = pset.popt;
301  static const bool translate_columns[] = {false, false, false, false, true, true, true, false, true, false, false, false, false};
302 
303  /* No "Parallel" column before 9.6 */
304  static const bool translate_columns_pre_96[] = {false, false, false, false, true, true, false, true, false, false, false, false};
305 
306  if (strlen(functypes) != strspn(functypes, "anptwS+"))
307  {
308  pg_log_error("\\df only takes [anptwS+] as options");
309  return true;
310  }
311 
312  if (showProcedure && pset.sversion < 110000)
313  {
314  char sverbuf[32];
315 
316  pg_log_error("\\df does not take a \"%c\" option with server version %s",
317  'p',
319  sverbuf, sizeof(sverbuf)));
320  return true;
321  }
322 
323  if (!showAggregate && !showNormal && !showProcedure && !showTrigger && !showWindow)
324  {
325  showAggregate = showNormal = showTrigger = showWindow = true;
326  if (pset.sversion >= 110000)
327  showProcedure = true;
328  }
329 
331 
333  "SELECT n.nspname as \"%s\",\n"
334  " p.proname as \"%s\",\n",
335  gettext_noop("Schema"),
336  gettext_noop("Name"));
337 
338  if (pset.sversion >= 110000)
340  " pg_catalog.pg_get_function_result(p.oid) as \"%s\",\n"
341  " pg_catalog.pg_get_function_arguments(p.oid) as \"%s\",\n"
342  " CASE p.prokind\n"
343  " WHEN 'a' THEN '%s'\n"
344  " WHEN 'w' THEN '%s'\n"
345  " WHEN 'p' THEN '%s'\n"
346  " ELSE '%s'\n"
347  " END as \"%s\"",
348  gettext_noop("Result data type"),
349  gettext_noop("Argument data types"),
350  /* translator: "agg" is short for "aggregate" */
351  gettext_noop("agg"),
352  gettext_noop("window"),
353  gettext_noop("proc"),
354  gettext_noop("func"),
355  gettext_noop("Type"));
356  else
358  " pg_catalog.pg_get_function_result(p.oid) as \"%s\",\n"
359  " pg_catalog.pg_get_function_arguments(p.oid) as \"%s\",\n"
360  " CASE\n"
361  " WHEN p.proisagg THEN '%s'\n"
362  " WHEN p.proiswindow THEN '%s'\n"
363  " WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN '%s'\n"
364  " ELSE '%s'\n"
365  " END as \"%s\"",
366  gettext_noop("Result data type"),
367  gettext_noop("Argument data types"),
368  /* translator: "agg" is short for "aggregate" */
369  gettext_noop("agg"),
370  gettext_noop("window"),
371  gettext_noop("trigger"),
372  gettext_noop("func"),
373  gettext_noop("Type"));
374 
375  if (verbose)
376  {
378  ",\n CASE\n"
379  " WHEN p.provolatile = 'i' THEN '%s'\n"
380  " WHEN p.provolatile = 's' THEN '%s'\n"
381  " WHEN p.provolatile = 'v' THEN '%s'\n"
382  " END as \"%s\"",
383  gettext_noop("immutable"),
384  gettext_noop("stable"),
385  gettext_noop("volatile"),
386  gettext_noop("Volatility"));
387  if (pset.sversion >= 90600)
389  ",\n CASE\n"
390  " WHEN p.proparallel = 'r' THEN '%s'\n"
391  " WHEN p.proparallel = 's' THEN '%s'\n"
392  " WHEN p.proparallel = 'u' THEN '%s'\n"
393  " END as \"%s\"",
394  gettext_noop("restricted"),
395  gettext_noop("safe"),
396  gettext_noop("unsafe"),
397  gettext_noop("Parallel"));
399  ",\n pg_catalog.pg_get_userbyid(p.proowner) as \"%s\""
400  ",\n CASE WHEN prosecdef THEN '%s' ELSE '%s' END AS \"%s\"",
401  gettext_noop("Owner"),
402  gettext_noop("definer"),
403  gettext_noop("invoker"),
404  gettext_noop("Security"));
405  appendPQExpBufferStr(&buf, ",\n ");
406  printACLColumn(&buf, "p.proacl");
408  ",\n l.lanname as \"%s\"",
409  gettext_noop("Language"));
411  ",\n CASE WHEN l.lanname IN ('internal', 'c') THEN p.prosrc END as \"%s\"",
412  gettext_noop("Internal name"));
414  ",\n pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"",
415  gettext_noop("Description"));
416  }
417 
419  "\nFROM pg_catalog.pg_proc p"
420  "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n");
421 
422  for (int i = 0; i < num_arg_patterns; i++)
423  {
425  " LEFT JOIN pg_catalog.pg_type t%d ON t%d.oid = p.proargtypes[%d]\n"
426  " LEFT JOIN pg_catalog.pg_namespace nt%d ON nt%d.oid = t%d.typnamespace\n",
427  i, i, i, i, i, i);
428  }
429 
430  if (verbose)
432  " LEFT JOIN pg_catalog.pg_language l ON l.oid = p.prolang\n");
433 
434  have_where = false;
435 
436  /* filter by function type, if requested */
437  if (showNormal && showAggregate && showProcedure && showTrigger && showWindow)
438  /* Do nothing */ ;
439  else if (showNormal)
440  {
441  if (!showAggregate)
442  {
443  if (have_where)
444  appendPQExpBufferStr(&buf, " AND ");
445  else
446  {
447  appendPQExpBufferStr(&buf, "WHERE ");
448  have_where = true;
449  }
450  if (pset.sversion >= 110000)
451  appendPQExpBufferStr(&buf, "p.prokind <> 'a'\n");
452  else
453  appendPQExpBufferStr(&buf, "NOT p.proisagg\n");
454  }
455  if (!showProcedure && pset.sversion >= 110000)
456  {
457  if (have_where)
458  appendPQExpBufferStr(&buf, " AND ");
459  else
460  {
461  appendPQExpBufferStr(&buf, "WHERE ");
462  have_where = true;
463  }
464  appendPQExpBufferStr(&buf, "p.prokind <> 'p'\n");
465  }
466  if (!showTrigger)
467  {
468  if (have_where)
469  appendPQExpBufferStr(&buf, " AND ");
470  else
471  {
472  appendPQExpBufferStr(&buf, "WHERE ");
473  have_where = true;
474  }
475  appendPQExpBufferStr(&buf, "p.prorettype <> 'pg_catalog.trigger'::pg_catalog.regtype\n");
476  }
477  if (!showWindow)
478  {
479  if (have_where)
480  appendPQExpBufferStr(&buf, " AND ");
481  else
482  {
483  appendPQExpBufferStr(&buf, "WHERE ");
484  have_where = true;
485  }
486  if (pset.sversion >= 110000)
487  appendPQExpBufferStr(&buf, "p.prokind <> 'w'\n");
488  else
489  appendPQExpBufferStr(&buf, "NOT p.proiswindow\n");
490  }
491  }
492  else
493  {
494  bool needs_or = false;
495 
496  appendPQExpBufferStr(&buf, "WHERE (\n ");
497  have_where = true;
498  /* Note: at least one of these must be true ... */
499  if (showAggregate)
500  {
501  if (pset.sversion >= 110000)
502  appendPQExpBufferStr(&buf, "p.prokind = 'a'\n");
503  else
504  appendPQExpBufferStr(&buf, "p.proisagg\n");
505  needs_or = true;
506  }
507  if (showTrigger)
508  {
509  if (needs_or)
510  appendPQExpBufferStr(&buf, " OR ");
512  "p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype\n");
513  needs_or = true;
514  }
515  if (showProcedure)
516  {
517  if (needs_or)
518  appendPQExpBufferStr(&buf, " OR ");
519  appendPQExpBufferStr(&buf, "p.prokind = 'p'\n");
520  needs_or = true;
521  }
522  if (showWindow)
523  {
524  if (needs_or)
525  appendPQExpBufferStr(&buf, " OR ");
526  if (pset.sversion >= 110000)
527  appendPQExpBufferStr(&buf, "p.prokind = 'w'\n");
528  else
529  appendPQExpBufferStr(&buf, "p.proiswindow\n");
530  }
531  appendPQExpBufferStr(&buf, " )\n");
532  }
533 
534  if (!validateSQLNamePattern(&buf, func_pattern, have_where, false,
535  "n.nspname", "p.proname", NULL,
536  "pg_catalog.pg_function_is_visible(p.oid)",
537  NULL, 3))
538  goto error_return;
539 
540  for (int i = 0; i < num_arg_patterns; i++)
541  {
542  if (strcmp(arg_patterns[i], "-") != 0)
543  {
544  /*
545  * Match type-name patterns against either internal or external
546  * name, like \dT. Unlike \dT, there seems no reason to
547  * discriminate against arrays or composite types.
548  */
549  char nspname[64];
550  char typname[64];
551  char ft[64];
552  char tiv[64];
553 
554  snprintf(nspname, sizeof(nspname), "nt%d.nspname", i);
555  snprintf(typname, sizeof(typname), "t%d.typname", i);
556  snprintf(ft, sizeof(ft),
557  "pg_catalog.format_type(t%d.oid, NULL)", i);
558  snprintf(tiv, sizeof(tiv),
559  "pg_catalog.pg_type_is_visible(t%d.oid)", i);
561  map_typename_pattern(arg_patterns[i]),
562  true, false,
563  nspname, typname, ft, tiv,
564  NULL, 3))
565  goto error_return;
566  }
567  else
568  {
569  /* "-" pattern specifies no such parameter */
570  appendPQExpBuffer(&buf, " AND t%d.typname IS NULL\n", i);
571  }
572  }
573 
574  if (!showSystem && !func_pattern)
575  appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
576  " AND n.nspname <> 'information_schema'\n");
577 
578  appendPQExpBufferStr(&buf, "ORDER BY 1, 2, 4;");
579 
580  res = PSQLexec(buf.data);
582  if (!res)
583  return false;
584 
585  myopt.title = _("List of functions");
586  myopt.translate_header = true;
587  if (pset.sversion >= 90600)
588  {
589  myopt.translate_columns = translate_columns;
590  myopt.n_translate_columns = lengthof(translate_columns);
591  }
592  else
593  {
594  myopt.translate_columns = translate_columns_pre_96;
595  myopt.n_translate_columns = lengthof(translate_columns_pre_96);
596  }
597 
598  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
599 
600  PQclear(res);
601  return true;
602 
603 error_return:
605  return false;
606 }
607 
608 
609 
610 /*
611  * \dT
612  * describe types
613  */
614 bool
615 describeTypes(const char *pattern, bool verbose, bool showSystem)
616 {
618  PGresult *res;
619  printQueryOpt myopt = pset.popt;
620 
622 
624  "SELECT n.nspname as \"%s\",\n"
625  " pg_catalog.format_type(t.oid, NULL) AS \"%s\",\n",
626  gettext_noop("Schema"),
627  gettext_noop("Name"));
628  if (verbose)
629  {
631  " t.typname AS \"%s\",\n"
632  " CASE WHEN t.typrelid != 0\n"
633  " THEN CAST('tuple' AS pg_catalog.text)\n"
634  " WHEN t.typlen < 0\n"
635  " THEN CAST('var' AS pg_catalog.text)\n"
636  " ELSE CAST(t.typlen AS pg_catalog.text)\n"
637  " END AS \"%s\",\n"
638  " pg_catalog.array_to_string(\n"
639  " ARRAY(\n"
640  " SELECT e.enumlabel\n"
641  " FROM pg_catalog.pg_enum e\n"
642  " WHERE e.enumtypid = t.oid\n"
643  " ORDER BY e.enumsortorder\n"
644  " ),\n"
645  " E'\\n'\n"
646  " ) AS \"%s\",\n"
647  " pg_catalog.pg_get_userbyid(t.typowner) AS \"%s\",\n",
648  gettext_noop("Internal name"),
649  gettext_noop("Size"),
650  gettext_noop("Elements"),
651  gettext_noop("Owner"));
652  printACLColumn(&buf, "t.typacl");
653  appendPQExpBufferStr(&buf, ",\n ");
654  }
655 
657  " pg_catalog.obj_description(t.oid, 'pg_type') as \"%s\"\n",
658  gettext_noop("Description"));
659 
660  appendPQExpBufferStr(&buf, "FROM pg_catalog.pg_type t\n"
661  " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n");
662 
663  /*
664  * do not include complex types (typrelid!=0) unless they are standalone
665  * composite types
666  */
667  appendPQExpBufferStr(&buf, "WHERE (t.typrelid = 0 ");
668  appendPQExpBufferStr(&buf, "OR (SELECT c.relkind = " CppAsString2(RELKIND_COMPOSITE_TYPE)
669  " FROM pg_catalog.pg_class c "
670  "WHERE c.oid = t.typrelid))\n");
671 
672  /*
673  * do not include array types unless the pattern contains []
674  */
675  if (pattern == NULL || strstr(pattern, "[]") == NULL)
676  appendPQExpBufferStr(&buf, " AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid)\n");
677 
678  if (!showSystem && !pattern)
679  appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
680  " AND n.nspname <> 'information_schema'\n");
681 
682  /* Match name pattern against either internal or external name */
684  true, false,
685  "n.nspname", "t.typname",
686  "pg_catalog.format_type(t.oid, NULL)",
687  "pg_catalog.pg_type_is_visible(t.oid)",
688  NULL, 3))
689  {
691  return false;
692  }
693 
694  appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
695 
696  res = PSQLexec(buf.data);
698  if (!res)
699  return false;
700 
701  myopt.title = _("List of data types");
702  myopt.translate_header = true;
703 
704  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
705 
706  PQclear(res);
707  return true;
708 }
709 
710 /*
711  * Map some variant type names accepted by the backend grammar into
712  * canonical type names.
713  *
714  * Helper for \dT and other functions that take typename patterns.
715  * This doesn't completely mask the fact that these names are special;
716  * for example, a pattern of "dec*" won't magically match "numeric".
717  * But it goes a long way to reduce the surprise factor.
718  */
719 static const char *
720 map_typename_pattern(const char *pattern)
721 {
722  static const char *const typename_map[] = {
723  /*
724  * These names are accepted by gram.y, although they are neither the
725  * "real" name seen in pg_type nor the canonical name printed by
726  * format_type().
727  */
728  "decimal", "numeric",
729  "float", "double precision",
730  "int", "integer",
731 
732  /*
733  * We also have to map the array names for cases where the canonical
734  * name is different from what pg_type says.
735  */
736  "bool[]", "boolean[]",
737  "decimal[]", "numeric[]",
738  "float[]", "double precision[]",
739  "float4[]", "real[]",
740  "float8[]", "double precision[]",
741  "int[]", "integer[]",
742  "int2[]", "smallint[]",
743  "int4[]", "integer[]",
744  "int8[]", "bigint[]",
745  "time[]", "time without time zone[]",
746  "timetz[]", "time with time zone[]",
747  "timestamp[]", "timestamp without time zone[]",
748  "timestamptz[]", "timestamp with time zone[]",
749  "varbit[]", "bit varying[]",
750  "varchar[]", "character varying[]",
751  NULL
752  };
753 
754  if (pattern == NULL)
755  return NULL;
756  for (int i = 0; typename_map[i] != NULL; i += 2)
757  {
758  if (pg_strcasecmp(pattern, typename_map[i]) == 0)
759  return typename_map[i + 1];
760  }
761  return pattern;
762 }
763 
764 
765 /*
766  * \do
767  * Describe operators
768  */
769 bool
770 describeOperators(const char *oper_pattern,
771  char **arg_patterns, int num_arg_patterns,
772  bool verbose, bool showSystem)
773 {
775  PGresult *res;
776  printQueryOpt myopt = pset.popt;
777 
779 
780  /*
781  * Note: before Postgres 9.1, we did not assign comments to any built-in
782  * operators, preferring to let the comment on the underlying function
783  * suffice. The coalesce() on the obj_description() calls below supports
784  * this convention by providing a fallback lookup of a comment on the
785  * operator's function. Since 9.1 there is a policy that every built-in
786  * operator should have a comment; so the coalesce() is no longer
787  * necessary so far as built-in operators are concerned. We keep it
788  * anyway, for now, because third-party modules may still be following the
789  * old convention.
790  *
791  * The support for postfix operators in this query is dead code as of
792  * Postgres 14, but we need to keep it for as long as we support talking
793  * to pre-v14 servers.
794  */
795 
797  "SELECT n.nspname as \"%s\",\n"
798  " o.oprname AS \"%s\",\n"
799  " CASE WHEN o.oprkind='l' THEN NULL ELSE pg_catalog.format_type(o.oprleft, NULL) END AS \"%s\",\n"
800  " CASE WHEN o.oprkind='r' THEN NULL ELSE pg_catalog.format_type(o.oprright, NULL) END AS \"%s\",\n"
801  " pg_catalog.format_type(o.oprresult, NULL) AS \"%s\",\n",
802  gettext_noop("Schema"),
803  gettext_noop("Name"),
804  gettext_noop("Left arg type"),
805  gettext_noop("Right arg type"),
806  gettext_noop("Result type"));
807 
808  if (verbose)
810  " o.oprcode AS \"%s\",\n",
811  gettext_noop("Function"));
812 
814  " coalesce(pg_catalog.obj_description(o.oid, 'pg_operator'),\n"
815  " pg_catalog.obj_description(o.oprcode, 'pg_proc')) AS \"%s\"\n"
816  "FROM pg_catalog.pg_operator o\n"
817  " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = o.oprnamespace\n",
818  gettext_noop("Description"));
819 
820  if (num_arg_patterns >= 2)
821  {
822  num_arg_patterns = 2; /* ignore any additional arguments */
824  " LEFT JOIN pg_catalog.pg_type t0 ON t0.oid = o.oprleft\n"
825  " LEFT JOIN pg_catalog.pg_namespace nt0 ON nt0.oid = t0.typnamespace\n"
826  " LEFT JOIN pg_catalog.pg_type t1 ON t1.oid = o.oprright\n"
827  " LEFT JOIN pg_catalog.pg_namespace nt1 ON nt1.oid = t1.typnamespace\n");
828  }
829  else if (num_arg_patterns == 1)
830  {
832  " LEFT JOIN pg_catalog.pg_type t0 ON t0.oid = o.oprright\n"
833  " LEFT JOIN pg_catalog.pg_namespace nt0 ON nt0.oid = t0.typnamespace\n");
834  }
835 
836  if (!showSystem && !oper_pattern)
837  appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n"
838  " AND n.nspname <> 'information_schema'\n");
839 
840  if (!validateSQLNamePattern(&buf, oper_pattern,
841  !showSystem && !oper_pattern, true,
842  "n.nspname", "o.oprname", NULL,
843  "pg_catalog.pg_operator_is_visible(o.oid)",
844  NULL, 3))
845  goto error_return;
846 
847  if (num_arg_patterns == 1)
848  appendPQExpBufferStr(&buf, " AND o.oprleft = 0\n");
849 
850  for (int i = 0; i < num_arg_patterns; i++)
851  {
852  if (strcmp(arg_patterns[i], "-") != 0)
853  {
854  /*
855  * Match type-name patterns against either internal or external
856  * name, like \dT. Unlike \dT, there seems no reason to
857  * discriminate against arrays or composite types.
858  */
859  char nspname[64];
860  char typname[64];
861  char ft[64];
862  char tiv[64];
863 
864  snprintf(nspname, sizeof(nspname), "nt%d.nspname", i);
865  snprintf(typname, sizeof(typname), "t%d.typname", i);
866  snprintf(ft, sizeof(ft),
867  "pg_catalog.format_type(t%d.oid, NULL)", i);
868  snprintf(tiv, sizeof(tiv),
869  "pg_catalog.pg_type_is_visible(t%d.oid)", i);
871  map_typename_pattern(arg_patterns[i]),
872  true, false,
873  nspname, typname, ft, tiv,
874  NULL, 3))
875  goto error_return;
876  }
877  else
878  {
879  /* "-" pattern specifies no such parameter */
880  appendPQExpBuffer(&buf, " AND t%d.typname IS NULL\n", i);
881  }
882  }
883 
884  appendPQExpBufferStr(&buf, "ORDER BY 1, 2, 3, 4;");
885 
886  res = PSQLexec(buf.data);
888  if (!res)
889  return false;
890 
891  myopt.title = _("List of operators");
892  myopt.translate_header = true;
893 
894  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
895 
896  PQclear(res);
897  return true;
898 
899 error_return:
901  return false;
902 }
903 
904 
905 /*
906  * listAllDbs
907  *
908  * for \l, \list, and -l switch
909  */
910 bool
911 listAllDbs(const char *pattern, bool verbose)
912 {
913  PGresult *res;
915  printQueryOpt myopt = pset.popt;
916 
918 
920  "SELECT\n"
921  " d.datname as \"%s\",\n"
922  " pg_catalog.pg_get_userbyid(d.datdba) as \"%s\",\n"
923  " pg_catalog.pg_encoding_to_char(d.encoding) as \"%s\",\n",
924  gettext_noop("Name"),
925  gettext_noop("Owner"),
926  gettext_noop("Encoding"));
927  if (pset.sversion >= 150000)
929  " CASE d.datlocprovider WHEN 'c' THEN 'libc' WHEN 'i' THEN 'icu' END AS \"%s\",\n",
930  gettext_noop("Locale Provider"));
931  else
933  " 'libc' AS \"%s\",\n",
934  gettext_noop("Locale Provider"));
936  " d.datcollate as \"%s\",\n"
937  " d.datctype as \"%s\",\n",
938  gettext_noop("Collate"),
939  gettext_noop("Ctype"));
940  if (pset.sversion >= 150000)
942  " d.daticulocale as \"%s\",\n",
943  gettext_noop("ICU Locale"));
944  else
946  " NULL as \"%s\",\n",
947  gettext_noop("ICU Locale"));
948  if (pset.sversion >= 160000)
950  " d.daticurules as \"%s\",\n",
951  gettext_noop("ICU Rules"));
952  else
954  " NULL as \"%s\",\n",
955  gettext_noop("ICU Rules"));
956  appendPQExpBufferStr(&buf, " ");
957  printACLColumn(&buf, "d.datacl");
958  if (verbose)
960  ",\n CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')\n"
961  " THEN pg_catalog.pg_size_pretty(pg_catalog.pg_database_size(d.datname))\n"
962  " ELSE 'No Access'\n"
963  " END as \"%s\""
964  ",\n t.spcname as \"%s\""
965  ",\n pg_catalog.shobj_description(d.oid, 'pg_database') as \"%s\"",
966  gettext_noop("Size"),
967  gettext_noop("Tablespace"),
968  gettext_noop("Description"));
970  "\nFROM pg_catalog.pg_database d\n");
971  if (verbose)
973  " JOIN pg_catalog.pg_tablespace t on d.dattablespace = t.oid\n");
974 
975  if (pattern)
976  {
977  if (!validateSQLNamePattern(&buf, pattern, false, false,
978  NULL, "d.datname", NULL, NULL,
979  NULL, 1))
980  {
982  return false;
983  }
984  }
985 
986  appendPQExpBufferStr(&buf, "ORDER BY 1;");
987  res = PSQLexec(buf.data);
989  if (!res)
990  return false;
991 
992  myopt.title = _("List of databases");
993  myopt.translate_header = true;
994 
995  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
996 
997  PQclear(res);
998  return true;
999 }
1000 
1001 
1002 /*
1003  * List Tables' Grant/Revoke Permissions
1004  * \z (now also \dp -- perhaps more mnemonic)
1005  */
1006 bool
1007 permissionsList(const char *pattern, bool showSystem)
1008 {
1010  PGresult *res;
1011  printQueryOpt myopt = pset.popt;
1012  static const bool translate_columns[] = {false, false, true, false, false, false};
1013 
1014  initPQExpBuffer(&buf);
1015 
1016  /*
1017  * we ignore indexes and toast tables since they have no meaningful rights
1018  */
1020  "SELECT n.nspname as \"%s\",\n"
1021  " c.relname as \"%s\",\n"
1022  " CASE c.relkind"
1023  " WHEN " CppAsString2(RELKIND_RELATION) " THEN '%s'"
1024  " WHEN " CppAsString2(RELKIND_VIEW) " THEN '%s'"
1025  " WHEN " CppAsString2(RELKIND_MATVIEW) " THEN '%s'"
1026  " WHEN " CppAsString2(RELKIND_SEQUENCE) " THEN '%s'"
1027  " WHEN " CppAsString2(RELKIND_FOREIGN_TABLE) " THEN '%s'"
1028  " WHEN " CppAsString2(RELKIND_PARTITIONED_TABLE) " THEN '%s'"
1029  " END as \"%s\",\n"
1030  " ",
1031  gettext_noop("Schema"),
1032  gettext_noop("Name"),
1033  gettext_noop("table"),
1034  gettext_noop("view"),
1035  gettext_noop("materialized view"),
1036  gettext_noop("sequence"),
1037  gettext_noop("foreign table"),
1038  gettext_noop("partitioned table"),
1039  gettext_noop("Type"));
1040 
1041  printACLColumn(&buf, "c.relacl");
1042 
1043  /*
1044  * The formatting of attacl should match printACLColumn(). However, we
1045  * need no special case for an empty attacl, because the backend always
1046  * optimizes that back to NULL.
1047  */
1049  ",\n pg_catalog.array_to_string(ARRAY(\n"
1050  " SELECT attname || E':\\n ' || pg_catalog.array_to_string(attacl, E'\\n ')\n"
1051  " FROM pg_catalog.pg_attribute a\n"
1052  " WHERE attrelid = c.oid AND NOT attisdropped AND attacl IS NOT NULL\n"
1053  " ), E'\\n') AS \"%s\"",
1054  gettext_noop("Column privileges"));
1055 
1056  if (pset.sversion >= 90500 && pset.sversion < 100000)
1058  ",\n pg_catalog.array_to_string(ARRAY(\n"
1059  " SELECT polname\n"
1060  " || CASE WHEN polcmd != '*' THEN\n"
1061  " E' (' || polcmd::pg_catalog.text || E'):'\n"
1062  " ELSE E':'\n"
1063  " END\n"
1064  " || CASE WHEN polqual IS NOT NULL THEN\n"
1065  " E'\\n (u): ' || pg_catalog.pg_get_expr(polqual, polrelid)\n"
1066  " ELSE E''\n"
1067  " END\n"
1068  " || CASE WHEN polwithcheck IS NOT NULL THEN\n"
1069  " E'\\n (c): ' || pg_catalog.pg_get_expr(polwithcheck, polrelid)\n"
1070  " ELSE E''\n"
1071  " END"
1072  " || CASE WHEN polroles <> '{0}' THEN\n"
1073  " E'\\n to: ' || pg_catalog.array_to_string(\n"
1074  " ARRAY(\n"
1075  " SELECT rolname\n"
1076  " FROM pg_catalog.pg_roles\n"
1077  " WHERE oid = ANY (polroles)\n"
1078  " ORDER BY 1\n"
1079  " ), E', ')\n"
1080  " ELSE E''\n"
1081  " END\n"
1082  " FROM pg_catalog.pg_policy pol\n"
1083  " WHERE polrelid = c.oid), E'\\n')\n"
1084  " AS \"%s\"",
1085  gettext_noop("Policies"));
1086 
1087  if (pset.sversion >= 100000)
1089  ",\n pg_catalog.array_to_string(ARRAY(\n"
1090  " SELECT polname\n"
1091  " || CASE WHEN NOT polpermissive THEN\n"
1092  " E' (RESTRICTIVE)'\n"
1093  " ELSE '' END\n"
1094  " || CASE WHEN polcmd != '*' THEN\n"
1095  " E' (' || polcmd::pg_catalog.text || E'):'\n"
1096  " ELSE E':'\n"
1097  " END\n"
1098  " || CASE WHEN polqual IS NOT NULL THEN\n"
1099  " E'\\n (u): ' || pg_catalog.pg_get_expr(polqual, polrelid)\n"
1100  " ELSE E''\n"
1101  " END\n"
1102  " || CASE WHEN polwithcheck IS NOT NULL THEN\n"
1103  " E'\\n (c): ' || pg_catalog.pg_get_expr(polwithcheck, polrelid)\n"
1104  " ELSE E''\n"
1105  " END"
1106  " || CASE WHEN polroles <> '{0}' THEN\n"
1107  " E'\\n to: ' || pg_catalog.array_to_string(\n"
1108  " ARRAY(\n"
1109  " SELECT rolname\n"
1110  " FROM pg_catalog.pg_roles\n"
1111  " WHERE oid = ANY (polroles)\n"
1112  " ORDER BY 1\n"
1113  " ), E', ')\n"
1114  " ELSE E''\n"
1115  " END\n"
1116  " FROM pg_catalog.pg_policy pol\n"
1117  " WHERE polrelid = c.oid), E'\\n')\n"
1118  " AS \"%s\"",
1119  gettext_noop("Policies"));
1120 
1121  appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_class c\n"
1122  " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"
1123  "WHERE c.relkind IN ("
1124  CppAsString2(RELKIND_RELATION) ","
1125  CppAsString2(RELKIND_VIEW) ","
1126  CppAsString2(RELKIND_MATVIEW) ","
1127  CppAsString2(RELKIND_SEQUENCE) ","
1128  CppAsString2(RELKIND_FOREIGN_TABLE) ","
1129  CppAsString2(RELKIND_PARTITIONED_TABLE) ")\n");
1130 
1131  if (!showSystem && !pattern)
1132  appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
1133  " AND n.nspname <> 'information_schema'\n");
1134 
1135  if (!validateSQLNamePattern(&buf, pattern, true, false,
1136  "n.nspname", "c.relname", NULL,
1137  "pg_catalog.pg_table_is_visible(c.oid)",
1138  NULL, 3))
1139  goto error_return;
1140 
1141  appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
1142 
1143  res = PSQLexec(buf.data);
1144  if (!res)
1145  goto error_return;
1146 
1147  printfPQExpBuffer(&buf, _("Access privileges"));
1148  myopt.title = buf.data;
1149  myopt.translate_header = true;
1150  myopt.translate_columns = translate_columns;
1151  myopt.n_translate_columns = lengthof(translate_columns);
1152 
1153  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
1154 
1155  termPQExpBuffer(&buf);
1156  PQclear(res);
1157  return true;
1158 
1159 error_return:
1160  termPQExpBuffer(&buf);
1161  return false;
1162 }
1163 
1164 
1165 /*
1166  * \ddp
1167  *
1168  * List Default ACLs. The pattern can match either schema or role name.
1169  */
1170 bool
1171 listDefaultACLs(const char *pattern)
1172 {
1174  PGresult *res;
1175  printQueryOpt myopt = pset.popt;
1176  static const bool translate_columns[] = {false, false, true, false};
1177 
1178  initPQExpBuffer(&buf);
1179 
1181  "SELECT pg_catalog.pg_get_userbyid(d.defaclrole) AS \"%s\",\n"
1182  " n.nspname AS \"%s\",\n"
1183  " CASE d.defaclobjtype WHEN '%c' THEN '%s' WHEN '%c' THEN '%s' WHEN '%c' THEN '%s' WHEN '%c' THEN '%s' WHEN '%c' THEN '%s' END AS \"%s\",\n"
1184  " ",
1185  gettext_noop("Owner"),
1186  gettext_noop("Schema"),
1187  DEFACLOBJ_RELATION,
1188  gettext_noop("table"),
1189  DEFACLOBJ_SEQUENCE,
1190  gettext_noop("sequence"),
1191  DEFACLOBJ_FUNCTION,
1192  gettext_noop("function"),
1193  DEFACLOBJ_TYPE,
1194  gettext_noop("type"),
1195  DEFACLOBJ_NAMESPACE,
1196  gettext_noop("schema"),
1197  gettext_noop("Type"));
1198 
1199  printACLColumn(&buf, "d.defaclacl");
1200 
1201  appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_default_acl d\n"
1202  " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = d.defaclnamespace\n");
1203 
1204  if (!validateSQLNamePattern(&buf, pattern, false, false,
1205  NULL,
1206  "n.nspname",
1207  "pg_catalog.pg_get_userbyid(d.defaclrole)",
1208  NULL,
1209  NULL, 3))
1210  goto error_return;
1211 
1212  appendPQExpBufferStr(&buf, "ORDER BY 1, 2, 3;");
1213 
1214  res = PSQLexec(buf.data);
1215  if (!res)
1216  goto error_return;
1217 
1218  printfPQExpBuffer(&buf, _("Default access privileges"));
1219  myopt.title = buf.data;
1220  myopt.translate_header = true;
1221  myopt.translate_columns = translate_columns;
1222  myopt.n_translate_columns = lengthof(translate_columns);
1223 
1224  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
1225 
1226  termPQExpBuffer(&buf);
1227  PQclear(res);
1228  return true;
1229 
1230 error_return:
1231  termPQExpBuffer(&buf);
1232  return false;
1233 }
1234 
1235 
1236 /*
1237  * Get object comments
1238  *
1239  * \dd [foo]
1240  *
1241  * Note: This command only lists comments for object types which do not have
1242  * their comments displayed by their own backslash commands. The following
1243  * types of objects will be displayed: constraint, operator class,
1244  * operator family, rule, and trigger.
1245  *
1246  */
1247 bool
1248 objectDescription(const char *pattern, bool showSystem)
1249 {
1251  PGresult *res;
1252  printQueryOpt myopt = pset.popt;
1253  static const bool translate_columns[] = {false, false, true, false};
1254 
1255  initPQExpBuffer(&buf);
1256 
1258  "SELECT DISTINCT tt.nspname AS \"%s\", tt.name AS \"%s\", tt.object AS \"%s\", d.description AS \"%s\"\n"
1259  "FROM (\n",
1260  gettext_noop("Schema"),
1261  gettext_noop("Name"),
1262  gettext_noop("Object"),
1263  gettext_noop("Description"));
1264 
1265  /* Table constraint descriptions */
1267  " SELECT pgc.oid as oid, pgc.tableoid AS tableoid,\n"
1268  " n.nspname as nspname,\n"
1269  " CAST(pgc.conname AS pg_catalog.text) as name,"
1270  " CAST('%s' AS pg_catalog.text) as object\n"
1271  " FROM pg_catalog.pg_constraint pgc\n"
1272  " JOIN pg_catalog.pg_class c "
1273  "ON c.oid = pgc.conrelid\n"
1274  " LEFT JOIN pg_catalog.pg_namespace n "
1275  " ON n.oid = c.relnamespace\n",
1276  gettext_noop("table constraint"));
1277 
1278  if (!showSystem && !pattern)
1279  appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n"
1280  " AND n.nspname <> 'information_schema'\n");
1281 
1282  if (!validateSQLNamePattern(&buf, pattern, !showSystem && !pattern,
1283  false, "n.nspname", "pgc.conname", NULL,
1284  "pg_catalog.pg_table_is_visible(c.oid)",
1285  NULL, 3))
1286  goto error_return;
1287 
1288  /* Domain constraint descriptions */
1290  "UNION ALL\n"
1291  " SELECT pgc.oid as oid, pgc.tableoid AS tableoid,\n"
1292  " n.nspname as nspname,\n"
1293  " CAST(pgc.conname AS pg_catalog.text) as name,"
1294  " CAST('%s' AS pg_catalog.text) as object\n"
1295  " FROM pg_catalog.pg_constraint pgc\n"
1296  " JOIN pg_catalog.pg_type t "
1297  "ON t.oid = pgc.contypid\n"
1298  " LEFT JOIN pg_catalog.pg_namespace n "
1299  " ON n.oid = t.typnamespace\n",
1300  gettext_noop("domain constraint"));
1301 
1302  if (!showSystem && !pattern)
1303  appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n"
1304  " AND n.nspname <> 'information_schema'\n");
1305 
1306  if (!validateSQLNamePattern(&buf, pattern, !showSystem && !pattern,
1307  false, "n.nspname", "pgc.conname", NULL,
1308  "pg_catalog.pg_type_is_visible(t.oid)",
1309  NULL, 3))
1310  goto error_return;
1311 
1312  /* Operator class descriptions */
1314  "UNION ALL\n"
1315  " SELECT o.oid as oid, o.tableoid as tableoid,\n"
1316  " n.nspname as nspname,\n"
1317  " CAST(o.opcname AS pg_catalog.text) as name,\n"
1318  " CAST('%s' AS pg_catalog.text) as object\n"
1319  " FROM pg_catalog.pg_opclass o\n"
1320  " JOIN pg_catalog.pg_am am ON "
1321  "o.opcmethod = am.oid\n"
1322  " JOIN pg_catalog.pg_namespace n ON "
1323  "n.oid = o.opcnamespace\n",
1324  gettext_noop("operator class"));
1325 
1326  if (!showSystem && !pattern)
1327  appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
1328  " AND n.nspname <> 'information_schema'\n");
1329 
1330  if (!validateSQLNamePattern(&buf, pattern, true, false,
1331  "n.nspname", "o.opcname", NULL,
1332  "pg_catalog.pg_opclass_is_visible(o.oid)",
1333  NULL, 3))
1334  goto error_return;
1335 
1336  /* Operator family descriptions */
1338  "UNION ALL\n"
1339  " SELECT opf.oid as oid, opf.tableoid as tableoid,\n"
1340  " n.nspname as nspname,\n"
1341  " CAST(opf.opfname AS pg_catalog.text) AS name,\n"
1342  " CAST('%s' AS pg_catalog.text) as object\n"
1343  " FROM pg_catalog.pg_opfamily opf\n"
1344  " JOIN pg_catalog.pg_am am "
1345  "ON opf.opfmethod = am.oid\n"
1346  " JOIN pg_catalog.pg_namespace n "
1347  "ON opf.opfnamespace = n.oid\n",
1348  gettext_noop("operator family"));
1349 
1350  if (!showSystem && !pattern)
1351  appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
1352  " AND n.nspname <> 'information_schema'\n");
1353 
1354  if (!validateSQLNamePattern(&buf, pattern, true, false,
1355  "n.nspname", "opf.opfname", NULL,
1356  "pg_catalog.pg_opfamily_is_visible(opf.oid)",
1357  NULL, 3))
1358  goto error_return;
1359 
1360  /* Rule descriptions (ignore rules for views) */
1362  "UNION ALL\n"
1363  " SELECT r.oid as oid, r.tableoid as tableoid,\n"
1364  " n.nspname as nspname,\n"
1365  " CAST(r.rulename AS pg_catalog.text) as name,"
1366  " CAST('%s' AS pg_catalog.text) as object\n"
1367  " FROM pg_catalog.pg_rewrite r\n"
1368  " JOIN pg_catalog.pg_class c ON c.oid = r.ev_class\n"
1369  " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"
1370  " WHERE r.rulename != '_RETURN'\n",
1371  gettext_noop("rule"));
1372 
1373  if (!showSystem && !pattern)
1374  appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
1375  " AND n.nspname <> 'information_schema'\n");
1376 
1377  if (!validateSQLNamePattern(&buf, pattern, true, false,
1378  "n.nspname", "r.rulename", NULL,
1379  "pg_catalog.pg_table_is_visible(c.oid)",
1380  NULL, 3))
1381  goto error_return;
1382 
1383  /* Trigger descriptions */
1385  "UNION ALL\n"
1386  " SELECT t.oid as oid, t.tableoid as tableoid,\n"
1387  " n.nspname as nspname,\n"
1388  " CAST(t.tgname AS pg_catalog.text) as name,"
1389  " CAST('%s' AS pg_catalog.text) as object\n"
1390  " FROM pg_catalog.pg_trigger t\n"
1391  " JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid\n"
1392  " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n",
1393  gettext_noop("trigger"));
1394 
1395  if (!showSystem && !pattern)
1396  appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n"
1397  " AND n.nspname <> 'information_schema'\n");
1398 
1399  if (!validateSQLNamePattern(&buf, pattern, !showSystem && !pattern, false,
1400  "n.nspname", "t.tgname", NULL,
1401  "pg_catalog.pg_table_is_visible(c.oid)",
1402  NULL, 3))
1403  goto error_return;
1404 
1406  ") AS tt\n"
1407  " JOIN pg_catalog.pg_description d ON (tt.oid = d.objoid AND tt.tableoid = d.classoid AND d.objsubid = 0)\n");
1408 
1409  appendPQExpBufferStr(&buf, "ORDER BY 1, 2, 3;");
1410 
1411  res = PSQLexec(buf.data);
1412  termPQExpBuffer(&buf);
1413  if (!res)
1414  return false;
1415 
1416  myopt.title = _("Object descriptions");
1417  myopt.translate_header = true;
1418  myopt.translate_columns = translate_columns;
1419  myopt.n_translate_columns = lengthof(translate_columns);
1420 
1421  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
1422 
1423  PQclear(res);
1424  return true;
1425 
1426 error_return:
1427  termPQExpBuffer(&buf);
1428  return false;
1429 }
1430 
1431 
1432 /*
1433  * describeTableDetails (for \d)
1434  *
1435  * This routine finds the tables to be displayed, and calls
1436  * describeOneTableDetails for each one.
1437  *
1438  * verbose: if true, this is \d+
1439  */
1440 bool
1441 describeTableDetails(const char *pattern, bool verbose, bool showSystem)
1442 {
1444  PGresult *res;
1445  int i;
1446 
1447  initPQExpBuffer(&buf);
1448 
1450  "SELECT c.oid,\n"
1451  " n.nspname,\n"
1452  " c.relname\n"
1453  "FROM pg_catalog.pg_class c\n"
1454  " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n");
1455 
1456  if (!showSystem && !pattern)
1457  appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n"
1458  " AND n.nspname <> 'information_schema'\n");
1459 
1460  if (!validateSQLNamePattern(&buf, pattern, !showSystem && !pattern, false,
1461  "n.nspname", "c.relname", NULL,
1462  "pg_catalog.pg_table_is_visible(c.oid)",
1463  NULL, 3))
1464  {
1465  termPQExpBuffer(&buf);
1466  return false;
1467  }
1468 
1469  appendPQExpBufferStr(&buf, "ORDER BY 2, 3;");
1470 
1471  res = PSQLexec(buf.data);
1472  termPQExpBuffer(&buf);
1473  if (!res)
1474  return false;
1475 
1476  if (PQntuples(res) == 0)
1477  {
1478  if (!pset.quiet)
1479  {
1480  if (pattern)
1481  pg_log_error("Did not find any relation named \"%s\".",
1482  pattern);
1483  else
1484  pg_log_error("Did not find any relations.");
1485  }
1486  PQclear(res);
1487  return false;
1488  }
1489 
1490  for (i = 0; i < PQntuples(res); i++)
1491  {
1492  const char *oid;
1493  const char *nspname;
1494  const char *relname;
1495 
1496  oid = PQgetvalue(res, i, 0);
1497  nspname = PQgetvalue(res, i, 1);
1498  relname = PQgetvalue(res, i, 2);
1499 
1500  if (!describeOneTableDetails(nspname, relname, oid, verbose))
1501  {
1502  PQclear(res);
1503  return false;
1504  }
1505  if (cancel_pressed)
1506  {
1507  PQclear(res);
1508  return false;
1509  }
1510  }
1511 
1512  PQclear(res);
1513  return true;
1514 }
1515 
1516 /*
1517  * describeOneTableDetails (for \d)
1518  *
1519  * Unfortunately, the information presented here is so complicated that it
1520  * cannot be done in a single query. So we have to assemble the printed table
1521  * by hand and pass it to the underlying printTable() function.
1522  */
1523 static bool
1524 describeOneTableDetails(const char *schemaname,
1525  const char *relationname,
1526  const char *oid,
1527  bool verbose)
1528 {
1529  bool retval = false;
1531  PGresult *res = NULL;
1532  printTableOpt myopt = pset.popt.topt;
1533  printTableContent cont;
1534  bool printTableInitialized = false;
1535  int i;
1536  char *view_def = NULL;
1537  char *headers[12];
1538  PQExpBufferData title;
1540  int cols;
1541  int attname_col = -1, /* column indexes in "res" */
1542  atttype_col = -1,
1543  attrdef_col = -1,
1544  attnotnull_col = -1,
1545  attcoll_col = -1,
1546  attidentity_col = -1,
1547  attgenerated_col = -1,
1548  isindexkey_col = -1,
1549  indexdef_col = -1,
1550  fdwopts_col = -1,
1551  attstorage_col = -1,
1552  attcompression_col = -1,
1553  attstattarget_col = -1,
1554  attdescr_col = -1;
1555  int numrows;
1556  struct
1557  {
1558  int16 checks;
1559  char relkind;
1560  bool hasindex;
1561  bool hasrules;
1562  bool hastriggers;
1563  bool rowsecurity;
1564  bool forcerowsecurity;
1565  bool hasoids;
1566  bool ispartition;
1567  Oid tablespace;
1568  char *reloptions;
1569  char *reloftype;
1570  char relpersistence;
1571  char relreplident;
1572  char *relam;
1573  } tableinfo;
1574  bool show_column_details = false;
1575 
1576  myopt.default_footer = false;
1577  /* This output looks confusing in expanded mode. */
1578  myopt.expanded = false;
1579 
1580  initPQExpBuffer(&buf);
1581  initPQExpBuffer(&title);
1583 
1584  /* Get general table info */
1585  if (pset.sversion >= 120000)
1586  {
1588  "SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, "
1589  "c.relhastriggers, c.relrowsecurity, c.relforcerowsecurity, "
1590  "false AS relhasoids, c.relispartition, %s, c.reltablespace, "
1591  "CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, "
1592  "c.relpersistence, c.relreplident, am.amname\n"
1593  "FROM pg_catalog.pg_class c\n "
1594  "LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)\n"
1595  "LEFT JOIN pg_catalog.pg_am am ON (c.relam = am.oid)\n"
1596  "WHERE c.oid = '%s';",
1597  (verbose ?
1598  "pg_catalog.array_to_string(c.reloptions || "
1599  "array(select 'toast.' || x from pg_catalog.unnest(tc.reloptions) x), ', ')\n"
1600  : "''"),
1601  oid);
1602  }
1603  else if (pset.sversion >= 100000)
1604  {
1606  "SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, "
1607  "c.relhastriggers, c.relrowsecurity, c.relforcerowsecurity, "
1608  "c.relhasoids, c.relispartition, %s, c.reltablespace, "
1609  "CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, "
1610  "c.relpersistence, c.relreplident\n"
1611  "FROM pg_catalog.pg_class c\n "
1612  "LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)\n"
1613  "WHERE c.oid = '%s';",
1614  (verbose ?
1615  "pg_catalog.array_to_string(c.reloptions || "
1616  "array(select 'toast.' || x from pg_catalog.unnest(tc.reloptions) x), ', ')\n"
1617  : "''"),
1618  oid);
1619  }
1620  else if (pset.sversion >= 90500)
1621  {
1623  "SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, "
1624  "c.relhastriggers, c.relrowsecurity, c.relforcerowsecurity, "
1625  "c.relhasoids, false as relispartition, %s, c.reltablespace, "
1626  "CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, "
1627  "c.relpersistence, c.relreplident\n"
1628  "FROM pg_catalog.pg_class c\n "
1629  "LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)\n"
1630  "WHERE c.oid = '%s';",
1631  (verbose ?
1632  "pg_catalog.array_to_string(c.reloptions || "
1633  "array(select 'toast.' || x from pg_catalog.unnest(tc.reloptions) x), ', ')\n"
1634  : "''"),
1635  oid);
1636  }
1637  else if (pset.sversion >= 90400)
1638  {
1640  "SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, "
1641  "c.relhastriggers, false, false, c.relhasoids, "
1642  "false as relispartition, %s, c.reltablespace, "
1643  "CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, "
1644  "c.relpersistence, c.relreplident\n"
1645  "FROM pg_catalog.pg_class c\n "
1646  "LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)\n"
1647  "WHERE c.oid = '%s';",
1648  (verbose ?
1649  "pg_catalog.array_to_string(c.reloptions || "
1650  "array(select 'toast.' || x from pg_catalog.unnest(tc.reloptions) x), ', ')\n"
1651  : "''"),
1652  oid);
1653  }
1654  else
1655  {
1657  "SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, "
1658  "c.relhastriggers, false, false, c.relhasoids, "
1659  "false as relispartition, %s, c.reltablespace, "
1660  "CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, "
1661  "c.relpersistence\n"
1662  "FROM pg_catalog.pg_class c\n "
1663  "LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)\n"
1664  "WHERE c.oid = '%s';",
1665  (verbose ?
1666  "pg_catalog.array_to_string(c.reloptions || "
1667  "array(select 'toast.' || x from pg_catalog.unnest(tc.reloptions) x), ', ')\n"
1668  : "''"),
1669  oid);
1670  }
1671 
1672  res = PSQLexec(buf.data);
1673  if (!res)
1674  goto error_return;
1675 
1676  /* Did we get anything? */
1677  if (PQntuples(res) == 0)
1678  {
1679  if (!pset.quiet)
1680  pg_log_error("Did not find any relation with OID %s.", oid);
1681  goto error_return;
1682  }
1683 
1684  tableinfo.checks = atoi(PQgetvalue(res, 0, 0));
1685  tableinfo.relkind = *(PQgetvalue(res, 0, 1));
1686  tableinfo.hasindex = strcmp(PQgetvalue(res, 0, 2), "t") == 0;
1687  tableinfo.hasrules = strcmp(PQgetvalue(res, 0, 3), "t") == 0;
1688  tableinfo.hastriggers = strcmp(PQgetvalue(res, 0, 4), "t") == 0;
1689  tableinfo.rowsecurity = strcmp(PQgetvalue(res, 0, 5), "t") == 0;
1690  tableinfo.forcerowsecurity = strcmp(PQgetvalue(res, 0, 6), "t") == 0;
1691  tableinfo.hasoids = strcmp(PQgetvalue(res, 0, 7), "t") == 0;
1692  tableinfo.ispartition = strcmp(PQgetvalue(res, 0, 8), "t") == 0;
1693  tableinfo.reloptions = pg_strdup(PQgetvalue(res, 0, 9));
1694  tableinfo.tablespace = atooid(PQgetvalue(res, 0, 10));
1695  tableinfo.reloftype = (strcmp(PQgetvalue(res, 0, 11), "") != 0) ?
1696  pg_strdup(PQgetvalue(res, 0, 11)) : NULL;
1697  tableinfo.relpersistence = *(PQgetvalue(res, 0, 12));
1698  tableinfo.relreplident = (pset.sversion >= 90400) ?
1699  *(PQgetvalue(res, 0, 13)) : 'd';
1700  if (pset.sversion >= 120000)
1701  tableinfo.relam = PQgetisnull(res, 0, 14) ?
1702  (char *) NULL : pg_strdup(PQgetvalue(res, 0, 14));
1703  else
1704  tableinfo.relam = NULL;
1705  PQclear(res);
1706  res = NULL;
1707 
1708  /*
1709  * If it's a sequence, deal with it here separately.
1710  */
1711  if (tableinfo.relkind == RELKIND_SEQUENCE)
1712  {
1713  PGresult *result = NULL;
1714  printQueryOpt myopt = pset.popt;
1715  char *footers[2] = {NULL, NULL};
1716 
1717  if (pset.sversion >= 100000)
1718  {
1720  "SELECT pg_catalog.format_type(seqtypid, NULL) AS \"%s\",\n"
1721  " seqstart AS \"%s\",\n"
1722  " seqmin AS \"%s\",\n"
1723  " seqmax AS \"%s\",\n"
1724  " seqincrement AS \"%s\",\n"
1725  " CASE WHEN seqcycle THEN '%s' ELSE '%s' END AS \"%s\",\n"
1726  " seqcache AS \"%s\"\n",
1727  gettext_noop("Type"),
1728  gettext_noop("Start"),
1729  gettext_noop("Minimum"),
1730  gettext_noop("Maximum"),
1731  gettext_noop("Increment"),
1732  gettext_noop("yes"),
1733  gettext_noop("no"),
1734  gettext_noop("Cycles?"),
1735  gettext_noop("Cache"));
1737  "FROM pg_catalog.pg_sequence\n"
1738  "WHERE seqrelid = '%s';",
1739  oid);
1740  }
1741  else
1742  {
1744  "SELECT 'bigint' AS \"%s\",\n"
1745  " start_value AS \"%s\",\n"
1746  " min_value AS \"%s\",\n"
1747  " max_value AS \"%s\",\n"
1748  " increment_by AS \"%s\",\n"
1749  " CASE WHEN is_cycled THEN '%s' ELSE '%s' END AS \"%s\",\n"
1750  " cache_value AS \"%s\"\n",
1751  gettext_noop("Type"),
1752  gettext_noop("Start"),
1753  gettext_noop("Minimum"),
1754  gettext_noop("Maximum"),
1755  gettext_noop("Increment"),
1756  gettext_noop("yes"),
1757  gettext_noop("no"),
1758  gettext_noop("Cycles?"),
1759  gettext_noop("Cache"));
1760  appendPQExpBuffer(&buf, "FROM %s", fmtId(schemaname));
1761  /* must be separate because fmtId isn't reentrant */
1762  appendPQExpBuffer(&buf, ".%s;", fmtId(relationname));
1763  }
1764 
1765  res = PSQLexec(buf.data);
1766  if (!res)
1767  goto error_return;
1768 
1769  /* Get the column that owns this sequence */
1770  printfPQExpBuffer(&buf, "SELECT pg_catalog.quote_ident(nspname) || '.' ||"
1771  "\n pg_catalog.quote_ident(relname) || '.' ||"
1772  "\n pg_catalog.quote_ident(attname),"
1773  "\n d.deptype"
1774  "\nFROM pg_catalog.pg_class c"
1775  "\nINNER JOIN pg_catalog.pg_depend d ON c.oid=d.refobjid"
1776  "\nINNER JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace"
1777  "\nINNER JOIN pg_catalog.pg_attribute a ON ("
1778  "\n a.attrelid=c.oid AND"
1779  "\n a.attnum=d.refobjsubid)"
1780  "\nWHERE d.classid='pg_catalog.pg_class'::pg_catalog.regclass"
1781  "\n AND d.refclassid='pg_catalog.pg_class'::pg_catalog.regclass"
1782  "\n AND d.objid='%s'"
1783  "\n AND d.deptype IN ('a', 'i')",
1784  oid);
1785 
1786  result = PSQLexec(buf.data);
1787 
1788  /*
1789  * If we get no rows back, don't show anything (obviously). We should
1790  * never get more than one row back, but if we do, just ignore it and
1791  * don't print anything.
1792  */
1793  if (!result)
1794  goto error_return;
1795  else if (PQntuples(result) == 1)
1796  {
1797  switch (PQgetvalue(result, 0, 1)[0])
1798  {
1799  case 'a':
1800  footers[0] = psprintf(_("Owned by: %s"),
1801  PQgetvalue(result, 0, 0));
1802  break;
1803  case 'i':
1804  footers[0] = psprintf(_("Sequence for identity column: %s"),
1805  PQgetvalue(result, 0, 0));
1806  break;
1807  }
1808  }
1809  PQclear(result);
1810 
1811  if (tableinfo.relpersistence == 'u')
1812  printfPQExpBuffer(&title, _("Unlogged sequence \"%s.%s\""),
1813  schemaname, relationname);
1814  else
1815  printfPQExpBuffer(&title, _("Sequence \"%s.%s\""),
1816  schemaname, relationname);
1817 
1818  myopt.footers = footers;
1819  myopt.topt.default_footer = false;
1820  myopt.title = title.data;
1821  myopt.translate_header = true;
1822 
1823  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
1824 
1825  free(footers[0]);
1826 
1827  retval = true;
1828  goto error_return; /* not an error, just return early */
1829  }
1830 
1831  /* Identify whether we should print collation, nullable, default vals */
1832  if (tableinfo.relkind == RELKIND_RELATION ||
1833  tableinfo.relkind == RELKIND_VIEW ||
1834  tableinfo.relkind == RELKIND_MATVIEW ||
1835  tableinfo.relkind == RELKIND_FOREIGN_TABLE ||
1836  tableinfo.relkind == RELKIND_COMPOSITE_TYPE ||
1837  tableinfo.relkind == RELKIND_PARTITIONED_TABLE)
1838  show_column_details = true;
1839 
1840  /*
1841  * Get per-column info
1842  *
1843  * Since the set of query columns we need varies depending on relkind and
1844  * server version, we compute all the column numbers on-the-fly. Column
1845  * number variables for columns not fetched are left as -1; this avoids
1846  * duplicative test logic below.
1847  */
1848  cols = 0;
1849  printfPQExpBuffer(&buf, "SELECT a.attname");
1850  attname_col = cols++;
1851  appendPQExpBufferStr(&buf, ",\n pg_catalog.format_type(a.atttypid, a.atttypmod)");
1852  atttype_col = cols++;
1853 
1854  if (show_column_details)
1855  {
1856  /* use "pretty" mode for expression to avoid excessive parentheses */
1858  ",\n (SELECT pg_catalog.pg_get_expr(d.adbin, d.adrelid, true)"
1859  "\n FROM pg_catalog.pg_attrdef d"
1860  "\n WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef)"
1861  ",\n a.attnotnull");
1862  attrdef_col = cols++;
1863  attnotnull_col = cols++;
1864  appendPQExpBufferStr(&buf, ",\n (SELECT c.collname FROM pg_catalog.pg_collation c, pg_catalog.pg_type t\n"
1865  " WHERE c.oid = a.attcollation AND t.oid = a.atttypid AND a.attcollation <> t.typcollation) AS attcollation");
1866  attcoll_col = cols++;
1867  if (pset.sversion >= 100000)
1868  appendPQExpBufferStr(&buf, ",\n a.attidentity");
1869  else
1870  appendPQExpBufferStr(&buf, ",\n ''::pg_catalog.char AS attidentity");
1871  attidentity_col = cols++;
1872  if (pset.sversion >= 120000)
1873  appendPQExpBufferStr(&buf, ",\n a.attgenerated");
1874  else
1875  appendPQExpBufferStr(&buf, ",\n ''::pg_catalog.char AS attgenerated");
1876  attgenerated_col = cols++;
1877  }
1878  if (tableinfo.relkind == RELKIND_INDEX ||
1879  tableinfo.relkind == RELKIND_PARTITIONED_INDEX)
1880  {
1881  if (pset.sversion >= 110000)
1882  {
1883  appendPQExpBuffer(&buf, ",\n CASE WHEN a.attnum <= (SELECT i.indnkeyatts FROM pg_catalog.pg_index i WHERE i.indexrelid = '%s') THEN '%s' ELSE '%s' END AS is_key",
1884  oid,
1885  gettext_noop("yes"),
1886  gettext_noop("no"));
1887  isindexkey_col = cols++;
1888  }
1889  appendPQExpBufferStr(&buf, ",\n pg_catalog.pg_get_indexdef(a.attrelid, a.attnum, TRUE) AS indexdef");
1890  indexdef_col = cols++;
1891  }
1892  /* FDW options for foreign table column */
1893  if (tableinfo.relkind == RELKIND_FOREIGN_TABLE)
1894  {
1895  appendPQExpBufferStr(&buf, ",\n CASE WHEN attfdwoptions IS NULL THEN '' ELSE "
1896  " '(' || pg_catalog.array_to_string(ARRAY(SELECT pg_catalog.quote_ident(option_name) || ' ' || pg_catalog.quote_literal(option_value) FROM "
1897  " pg_catalog.pg_options_to_table(attfdwoptions)), ', ') || ')' END AS attfdwoptions");
1898  fdwopts_col = cols++;
1899  }
1900  if (verbose)
1901  {
1902  appendPQExpBufferStr(&buf, ",\n a.attstorage");
1903  attstorage_col = cols++;
1904 
1905  /* compression info, if relevant to relkind */
1906  if (pset.sversion >= 140000 &&
1908  (tableinfo.relkind == RELKIND_RELATION ||
1909  tableinfo.relkind == RELKIND_PARTITIONED_TABLE ||
1910  tableinfo.relkind == RELKIND_MATVIEW))
1911  {
1912  appendPQExpBufferStr(&buf, ",\n a.attcompression AS attcompression");
1913  attcompression_col = cols++;
1914  }
1915 
1916  /* stats target, if relevant to relkind */
1917  if (tableinfo.relkind == RELKIND_RELATION ||
1918  tableinfo.relkind == RELKIND_INDEX ||
1919  tableinfo.relkind == RELKIND_PARTITIONED_INDEX ||
1920  tableinfo.relkind == RELKIND_MATVIEW ||
1921  tableinfo.relkind == RELKIND_FOREIGN_TABLE ||
1922  tableinfo.relkind == RELKIND_PARTITIONED_TABLE)
1923  {
1924  appendPQExpBufferStr(&buf, ",\n CASE WHEN a.attstattarget=-1 THEN NULL ELSE a.attstattarget END AS attstattarget");
1925  attstattarget_col = cols++;
1926  }
1927 
1928  /*
1929  * In 9.0+, we have column comments for: relations, views, composite
1930  * types, and foreign tables (cf. CommentObject() in comment.c).
1931  */
1932  if (tableinfo.relkind == RELKIND_RELATION ||
1933  tableinfo.relkind == RELKIND_VIEW ||
1934  tableinfo.relkind == RELKIND_MATVIEW ||
1935  tableinfo.relkind == RELKIND_FOREIGN_TABLE ||
1936  tableinfo.relkind == RELKIND_COMPOSITE_TYPE ||
1937  tableinfo.relkind == RELKIND_PARTITIONED_TABLE)
1938  {
1939  appendPQExpBufferStr(&buf, ",\n pg_catalog.col_description(a.attrelid, a.attnum)");
1940  attdescr_col = cols++;
1941  }
1942  }
1943 
1944  appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_attribute a");
1945  appendPQExpBuffer(&buf, "\nWHERE a.attrelid = '%s' AND a.attnum > 0 AND NOT a.attisdropped", oid);
1946  appendPQExpBufferStr(&buf, "\nORDER BY a.attnum;");
1947 
1948  res = PSQLexec(buf.data);
1949  if (!res)
1950  goto error_return;
1951  numrows = PQntuples(res);
1952 
1953  /* Make title */
1954  switch (tableinfo.relkind)
1955  {
1956  case RELKIND_RELATION:
1957  if (tableinfo.relpersistence == 'u')
1958  printfPQExpBuffer(&title, _("Unlogged table \"%s.%s\""),
1959  schemaname, relationname);
1960  else
1961  printfPQExpBuffer(&title, _("Table \"%s.%s\""),
1962  schemaname, relationname);
1963  break;
1964  case RELKIND_VIEW:
1965  printfPQExpBuffer(&title, _("View \"%s.%s\""),
1966  schemaname, relationname);
1967  break;
1968  case RELKIND_MATVIEW:
1969  if (tableinfo.relpersistence == 'u')
1970  printfPQExpBuffer(&title, _("Unlogged materialized view \"%s.%s\""),
1971  schemaname, relationname);
1972  else
1973  printfPQExpBuffer(&title, _("Materialized view \"%s.%s\""),
1974  schemaname, relationname);
1975  break;
1976  case RELKIND_INDEX:
1977  if (tableinfo.relpersistence == 'u')
1978  printfPQExpBuffer(&title, _("Unlogged index \"%s.%s\""),
1979  schemaname, relationname);
1980  else
1981  printfPQExpBuffer(&title, _("Index \"%s.%s\""),
1982  schemaname, relationname);
1983  break;
1984  case RELKIND_PARTITIONED_INDEX:
1985  if (tableinfo.relpersistence == 'u')
1986  printfPQExpBuffer(&title, _("Unlogged partitioned index \"%s.%s\""),
1987  schemaname, relationname);
1988  else
1989  printfPQExpBuffer(&title, _("Partitioned index \"%s.%s\""),
1990  schemaname, relationname);
1991  break;
1992  case RELKIND_TOASTVALUE:
1993  printfPQExpBuffer(&title, _("TOAST table \"%s.%s\""),
1994  schemaname, relationname);
1995  break;
1996  case RELKIND_COMPOSITE_TYPE:
1997  printfPQExpBuffer(&title, _("Composite type \"%s.%s\""),
1998  schemaname, relationname);
1999  break;
2000  case RELKIND_FOREIGN_TABLE:
2001  printfPQExpBuffer(&title, _("Foreign table \"%s.%s\""),
2002  schemaname, relationname);
2003  break;
2004  case RELKIND_PARTITIONED_TABLE:
2005  if (tableinfo.relpersistence == 'u')
2006  printfPQExpBuffer(&title, _("Unlogged partitioned table \"%s.%s\""),
2007  schemaname, relationname);
2008  else
2009  printfPQExpBuffer(&title, _("Partitioned table \"%s.%s\""),
2010  schemaname, relationname);
2011  break;
2012  default:
2013  /* untranslated unknown relkind */
2014  printfPQExpBuffer(&title, "?%c? \"%s.%s\"",
2015  tableinfo.relkind, schemaname, relationname);
2016  break;
2017  }
2018 
2019  /* Fill headers[] with the names of the columns we will output */
2020  cols = 0;
2021  headers[cols++] = gettext_noop("Column");
2022  headers[cols++] = gettext_noop("Type");
2023  if (show_column_details)
2024  {
2025  headers[cols++] = gettext_noop("Collation");
2026  headers[cols++] = gettext_noop("Nullable");
2027  headers[cols++] = gettext_noop("Default");
2028  }
2029  if (isindexkey_col >= 0)
2030  headers[cols++] = gettext_noop("Key?");
2031  if (indexdef_col >= 0)
2032  headers[cols++] = gettext_noop("Definition");
2033  if (fdwopts_col >= 0)
2034  headers[cols++] = gettext_noop("FDW options");
2035  if (attstorage_col >= 0)
2036  headers[cols++] = gettext_noop("Storage");
2037  if (attcompression_col >= 0)
2038  headers[cols++] = gettext_noop("Compression");
2039  if (attstattarget_col >= 0)
2040  headers[cols++] = gettext_noop("Stats target");
2041  if (attdescr_col >= 0)
2042  headers[cols++] = gettext_noop("Description");
2043 
2044  Assert(cols <= lengthof(headers));
2045 
2046  printTableInit(&cont, &myopt, title.data, cols, numrows);
2047  printTableInitialized = true;
2048 
2049  for (i = 0; i < cols; i++)
2050  printTableAddHeader(&cont, headers[i], true, 'l');
2051 
2052  /* Generate table cells to be printed */
2053  for (i = 0; i < numrows; i++)
2054  {
2055  /* Column */
2056  printTableAddCell(&cont, PQgetvalue(res, i, attname_col), false, false);
2057 
2058  /* Type */
2059  printTableAddCell(&cont, PQgetvalue(res, i, atttype_col), false, false);
2060 
2061  /* Collation, Nullable, Default */
2062  if (show_column_details)
2063  {
2064  char *identity;
2065  char *generated;
2066  char *default_str;
2067  bool mustfree = false;
2068 
2069  printTableAddCell(&cont, PQgetvalue(res, i, attcoll_col), false, false);
2070 
2071  printTableAddCell(&cont,
2072  strcmp(PQgetvalue(res, i, attnotnull_col), "t") == 0 ? "not null" : "",
2073  false, false);
2074 
2075  identity = PQgetvalue(res, i, attidentity_col);
2076  generated = PQgetvalue(res, i, attgenerated_col);
2077 
2078  if (identity[0] == ATTRIBUTE_IDENTITY_ALWAYS)
2079  default_str = "generated always as identity";
2080  else if (identity[0] == ATTRIBUTE_IDENTITY_BY_DEFAULT)
2081  default_str = "generated by default as identity";
2082  else if (generated[0] == ATTRIBUTE_GENERATED_STORED)
2083  {
2084  default_str = psprintf("generated always as (%s) stored",
2085  PQgetvalue(res, i, attrdef_col));
2086  mustfree = true;
2087  }
2088  else
2089  default_str = PQgetvalue(res, i, attrdef_col);
2090 
2091  printTableAddCell(&cont, default_str, false, mustfree);
2092  }
2093 
2094  /* Info for index columns */
2095  if (isindexkey_col >= 0)
2096  printTableAddCell(&cont, PQgetvalue(res, i, isindexkey_col), true, false);
2097  if (indexdef_col >= 0)
2098  printTableAddCell(&cont, PQgetvalue(res, i, indexdef_col), false, false);
2099 
2100  /* FDW options for foreign table columns */
2101  if (fdwopts_col >= 0)
2102  printTableAddCell(&cont, PQgetvalue(res, i, fdwopts_col), false, false);
2103 
2104  /* Storage mode, if relevant */
2105  if (attstorage_col >= 0)
2106  {
2107  char *storage = PQgetvalue(res, i, attstorage_col);
2108 
2109  /* these strings are literal in our syntax, so not translated. */
2110  printTableAddCell(&cont, (storage[0] == 'p' ? "plain" :
2111  (storage[0] == 'm' ? "main" :
2112  (storage[0] == 'x' ? "extended" :
2113  (storage[0] == 'e' ? "external" :
2114  "???")))),
2115  false, false);
2116  }
2117 
2118  /* Column compression, if relevant */
2119  if (attcompression_col >= 0)
2120  {
2121  char *compression = PQgetvalue(res, i, attcompression_col);
2122 
2123  /* these strings are literal in our syntax, so not translated. */
2124  printTableAddCell(&cont, (compression[0] == 'p' ? "pglz" :
2125  (compression[0] == 'l' ? "lz4" :
2126  (compression[0] == '\0' ? "" :
2127  "???"))),
2128  false, false);
2129  }
2130 
2131  /* Statistics target, if the relkind supports this feature */
2132  if (attstattarget_col >= 0)
2133  printTableAddCell(&cont, PQgetvalue(res, i, attstattarget_col),
2134  false, false);
2135 
2136  /* Column comments, if the relkind supports this feature */
2137  if (attdescr_col >= 0)
2138  printTableAddCell(&cont, PQgetvalue(res, i, attdescr_col),
2139  false, false);
2140  }
2141 
2142  /* Make footers */
2143 
2144  if (tableinfo.ispartition)
2145  {
2146  /* Footer information for a partition child table */
2147  PGresult *result;
2148 
2150  "SELECT inhparent::pg_catalog.regclass,\n"
2151  " pg_catalog.pg_get_expr(c.relpartbound, c.oid),\n ");
2152 
2154  pset.sversion >= 140000 ? "inhdetachpending" :
2155  "false as inhdetachpending");
2156 
2157  /* If verbose, also request the partition constraint definition */
2158  if (verbose)
2160  ",\n pg_catalog.pg_get_partition_constraintdef(c.oid)");
2162  "\nFROM pg_catalog.pg_class c"
2163  " JOIN pg_catalog.pg_inherits i"
2164  " ON c.oid = inhrelid"
2165  "\nWHERE c.oid = '%s';", oid);
2166  result = PSQLexec(buf.data);
2167  if (!result)
2168  goto error_return;
2169 
2170  if (PQntuples(result) > 0)
2171  {
2172  char *parent_name = PQgetvalue(result, 0, 0);
2173  char *partdef = PQgetvalue(result, 0, 1);
2174  char *detached = PQgetvalue(result, 0, 2);
2175 
2176  printfPQExpBuffer(&tmpbuf, _("Partition of: %s %s%s"), parent_name,
2177  partdef,
2178  strcmp(detached, "t") == 0 ? " DETACH PENDING" : "");
2180 
2181  if (verbose)
2182  {
2183  char *partconstraintdef = NULL;
2184 
2185  if (!PQgetisnull(result, 0, 3))
2186  partconstraintdef = PQgetvalue(result, 0, 3);
2187  /* If there isn't any constraint, show that explicitly */
2188  if (partconstraintdef == NULL || partconstraintdef[0] == '\0')
2189  printfPQExpBuffer(&tmpbuf, _("No partition constraint"));
2190  else
2191  printfPQExpBuffer(&tmpbuf, _("Partition constraint: %s"),
2192  partconstraintdef);
2194  }
2195  }
2196  PQclear(result);
2197  }
2198 
2199  if (tableinfo.relkind == RELKIND_PARTITIONED_TABLE)
2200  {
2201  /* Footer information for a partitioned table (partitioning parent) */
2202  PGresult *result;
2203 
2205  "SELECT pg_catalog.pg_get_partkeydef('%s'::pg_catalog.oid);",
2206  oid);
2207  result = PSQLexec(buf.data);
2208  if (!result)
2209  goto error_return;
2210 
2211  if (PQntuples(result) == 1)
2212  {
2213  char *partkeydef = PQgetvalue(result, 0, 0);
2214 
2215  printfPQExpBuffer(&tmpbuf, _("Partition key: %s"), partkeydef);
2217  }
2218  PQclear(result);
2219  }
2220 
2221  if (tableinfo.relkind == RELKIND_TOASTVALUE)
2222  {
2223  /* For a TOAST table, print name of owning table */
2224  PGresult *result;
2225 
2227  "SELECT n.nspname, c.relname\n"
2228  "FROM pg_catalog.pg_class c"
2229  " JOIN pg_catalog.pg_namespace n"
2230  " ON n.oid = c.relnamespace\n"
2231  "WHERE reltoastrelid = '%s';", oid);
2232  result = PSQLexec(buf.data);
2233  if (!result)
2234  goto error_return;
2235 
2236  if (PQntuples(result) == 1)
2237  {
2238  char *schemaname = PQgetvalue(result, 0, 0);
2239  char *relname = PQgetvalue(result, 0, 1);
2240 
2241  printfPQExpBuffer(&tmpbuf, _("Owning table: \"%s.%s\""),
2242  schemaname, relname);
2244  }
2245  PQclear(result);
2246  }
2247 
2248  if (tableinfo.relkind == RELKIND_INDEX ||
2249  tableinfo.relkind == RELKIND_PARTITIONED_INDEX)
2250  {
2251  /* Footer information about an index */
2252  PGresult *result;
2253 
2255  "SELECT i.indisunique, i.indisprimary, i.indisclustered, "
2256  "i.indisvalid,\n"
2257  " (NOT i.indimmediate) AND "
2258  "EXISTS (SELECT 1 FROM pg_catalog.pg_constraint "
2259  "WHERE conrelid = i.indrelid AND "
2260  "conindid = i.indexrelid AND "
2261  "contype IN ('p','u','x') AND "
2262  "condeferrable) AS condeferrable,\n"
2263  " (NOT i.indimmediate) AND "
2264  "EXISTS (SELECT 1 FROM pg_catalog.pg_constraint "
2265  "WHERE conrelid = i.indrelid AND "
2266  "conindid = i.indexrelid AND "
2267  "contype IN ('p','u','x') AND "
2268  "condeferred) AS condeferred,\n");
2269 
2270  if (pset.sversion >= 90400)
2271  appendPQExpBufferStr(&buf, "i.indisreplident,\n");
2272  else
2273  appendPQExpBufferStr(&buf, "false AS indisreplident,\n");
2274 
2275  if (pset.sversion >= 150000)
2276  appendPQExpBufferStr(&buf, "i.indnullsnotdistinct,\n");
2277  else
2278  appendPQExpBufferStr(&buf, "false AS indnullsnotdistinct,\n");
2279 
2280  appendPQExpBuffer(&buf, " a.amname, c2.relname, "
2281  "pg_catalog.pg_get_expr(i.indpred, i.indrelid, true)\n"
2282  "FROM pg_catalog.pg_index i, pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_am a\n"
2283  "WHERE i.indexrelid = c.oid AND c.oid = '%s' AND c.relam = a.oid\n"
2284  "AND i.indrelid = c2.oid;",
2285  oid);
2286 
2287  result = PSQLexec(buf.data);
2288  if (!result)
2289  goto error_return;
2290  else if (PQntuples(result) != 1)
2291  {
2292  PQclear(result);
2293  goto error_return;
2294  }
2295  else
2296  {
2297  char *indisunique = PQgetvalue(result, 0, 0);
2298  char *indisprimary = PQgetvalue(result, 0, 1);
2299  char *indisclustered = PQgetvalue(result, 0, 2);
2300  char *indisvalid = PQgetvalue(result, 0, 3);
2301  char *deferrable = PQgetvalue(result, 0, 4);
2302  char *deferred = PQgetvalue(result, 0, 5);
2303  char *indisreplident = PQgetvalue(result, 0, 6);
2304  char *indnullsnotdistinct = PQgetvalue(result, 0, 7);
2305  char *indamname = PQgetvalue(result, 0, 8);
2306  char *indtable = PQgetvalue(result, 0, 9);
2307  char *indpred = PQgetvalue(result, 0, 10);
2308 
2309  if (strcmp(indisprimary, "t") == 0)
2310  printfPQExpBuffer(&tmpbuf, _("primary key, "));
2311  else if (strcmp(indisunique, "t") == 0)
2312  {
2313  printfPQExpBuffer(&tmpbuf, _("unique"));
2314  if (strcmp(indnullsnotdistinct, "t") == 0)
2315  appendPQExpBufferStr(&tmpbuf, _(" nulls not distinct"));
2316  appendPQExpBufferStr(&tmpbuf, _(", "));
2317  }
2318  else
2320  appendPQExpBuffer(&tmpbuf, "%s, ", indamname);
2321 
2322  /* we assume here that index and table are in same schema */
2323  appendPQExpBuffer(&tmpbuf, _("for table \"%s.%s\""),
2324  schemaname, indtable);
2325 
2326  if (strlen(indpred))
2327  appendPQExpBuffer(&tmpbuf, _(", predicate (%s)"), indpred);
2328 
2329  if (strcmp(indisclustered, "t") == 0)
2330  appendPQExpBufferStr(&tmpbuf, _(", clustered"));
2331 
2332  if (strcmp(indisvalid, "t") != 0)
2333  appendPQExpBufferStr(&tmpbuf, _(", invalid"));
2334 
2335  if (strcmp(deferrable, "t") == 0)
2336  appendPQExpBufferStr(&tmpbuf, _(", deferrable"));
2337 
2338  if (strcmp(deferred, "t") == 0)
2339  appendPQExpBufferStr(&tmpbuf, _(", initially deferred"));
2340 
2341  if (strcmp(indisreplident, "t") == 0)
2342  appendPQExpBufferStr(&tmpbuf, _(", replica identity"));
2343 
2345 
2346  /*
2347  * If it's a partitioned index, we'll print the tablespace below
2348  */
2349  if (tableinfo.relkind == RELKIND_INDEX)
2350  add_tablespace_footer(&cont, tableinfo.relkind,
2351  tableinfo.tablespace, true);
2352  }
2353 
2354  PQclear(result);
2355  }
2356  /* If you add relkinds here, see also "Finish printing..." stanza below */
2357  else if (tableinfo.relkind == RELKIND_RELATION ||
2358  tableinfo.relkind == RELKIND_MATVIEW ||
2359  tableinfo.relkind == RELKIND_FOREIGN_TABLE ||
2360  tableinfo.relkind == RELKIND_PARTITIONED_TABLE ||
2361  tableinfo.relkind == RELKIND_PARTITIONED_INDEX ||
2362  tableinfo.relkind == RELKIND_TOASTVALUE)
2363  {
2364  /* Footer information about a table */
2365  PGresult *result = NULL;
2366  int tuples = 0;
2367 
2368  /* print indexes */
2369  if (tableinfo.hasindex)
2370  {
2372  "SELECT c2.relname, i.indisprimary, i.indisunique, "
2373  "i.indisclustered, i.indisvalid, "
2374  "pg_catalog.pg_get_indexdef(i.indexrelid, 0, true),\n "
2375  "pg_catalog.pg_get_constraintdef(con.oid, true), "
2376  "contype, condeferrable, condeferred");
2377  if (pset.sversion >= 90400)
2378  appendPQExpBufferStr(&buf, ", i.indisreplident");
2379  else
2380  appendPQExpBufferStr(&buf, ", false AS indisreplident");
2381  appendPQExpBufferStr(&buf, ", c2.reltablespace");
2382  if (pset.sversion >= 170000)
2383  appendPQExpBufferStr(&buf, ", con.conwithoutoverlaps");
2384  else
2385  appendPQExpBufferStr(&buf, ", false AS conwithoutoverlaps");
2387  "\nFROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i\n"
2388  " LEFT JOIN pg_catalog.pg_constraint con ON (conrelid = i.indrelid AND conindid = i.indexrelid AND contype IN ('p','u','x'))\n"
2389  "WHERE c.oid = '%s' AND c.oid = i.indrelid AND i.indexrelid = c2.oid\n"
2390  "ORDER BY i.indisprimary DESC, c2.relname;",
2391  oid);
2392  result = PSQLexec(buf.data);
2393  if (!result)
2394  goto error_return;
2395  else
2396  tuples = PQntuples(result);
2397 
2398  if (tuples > 0)
2399  {
2400  printTableAddFooter(&cont, _("Indexes:"));
2401  for (i = 0; i < tuples; i++)
2402  {
2403  /* untranslated index name */
2404  printfPQExpBuffer(&buf, " \"%s\"",
2405  PQgetvalue(result, i, 0));
2406 
2407  /*
2408  * If exclusion constraint or PK/UNIQUE constraint WITHOUT
2409  * OVERLAPS, print the constraintdef
2410  */
2411  if (strcmp(PQgetvalue(result, i, 7), "x") == 0 ||
2412  strcmp(PQgetvalue(result, i, 12), "t") == 0)
2413  {
2414  appendPQExpBuffer(&buf, " %s",
2415  PQgetvalue(result, i, 6));
2416  }
2417  else
2418  {
2419  const char *indexdef;
2420  const char *usingpos;
2421 
2422  /* Label as primary key or unique (but not both) */
2423  if (strcmp(PQgetvalue(result, i, 1), "t") == 0)
2424  appendPQExpBufferStr(&buf, " PRIMARY KEY,");
2425  else if (strcmp(PQgetvalue(result, i, 2), "t") == 0)
2426  {
2427  if (strcmp(PQgetvalue(result, i, 7), "u") == 0)
2428  appendPQExpBufferStr(&buf, " UNIQUE CONSTRAINT,");
2429  else
2430  appendPQExpBufferStr(&buf, " UNIQUE,");
2431  }
2432 
2433  /* Everything after "USING" is echoed verbatim */
2434  indexdef = PQgetvalue(result, i, 5);
2435  usingpos = strstr(indexdef, " USING ");
2436  if (usingpos)
2437  indexdef = usingpos + 7;
2438  appendPQExpBuffer(&buf, " %s", indexdef);
2439 
2440  /* Need these for deferrable PK/UNIQUE indexes */
2441  if (strcmp(PQgetvalue(result, i, 8), "t") == 0)
2442  appendPQExpBufferStr(&buf, " DEFERRABLE");
2443 
2444  if (strcmp(PQgetvalue(result, i, 9), "t") == 0)
2445  appendPQExpBufferStr(&buf, " INITIALLY DEFERRED");
2446  }
2447 
2448  /* Add these for all cases */
2449  if (strcmp(PQgetvalue(result, i, 3), "t") == 0)
2450  appendPQExpBufferStr(&buf, " CLUSTER");
2451 
2452  if (strcmp(PQgetvalue(result, i, 4), "t") != 0)
2453  appendPQExpBufferStr(&buf, " INVALID");
2454 
2455  if (strcmp(PQgetvalue(result, i, 10), "t") == 0)
2456  appendPQExpBufferStr(&buf, " REPLICA IDENTITY");
2457 
2458  printTableAddFooter(&cont, buf.data);
2459 
2460  /* Print tablespace of the index on the same line */
2461  add_tablespace_footer(&cont, RELKIND_INDEX,
2462  atooid(PQgetvalue(result, i, 11)),
2463  false);
2464  }
2465  }
2466  PQclear(result);
2467  }
2468 
2469  /* print table (and column) check constraints */
2470  if (tableinfo.checks)
2471  {
2473  "SELECT r.conname, "
2474  "pg_catalog.pg_get_constraintdef(r.oid, true)\n"
2475  "FROM pg_catalog.pg_constraint r\n"
2476  "WHERE r.conrelid = '%s' AND r.contype = 'c'\n"
2477  "ORDER BY 1;",
2478  oid);
2479  result = PSQLexec(buf.data);
2480  if (!result)
2481  goto error_return;
2482  else
2483  tuples = PQntuples(result);
2484 
2485  if (tuples > 0)
2486  {
2487  printTableAddFooter(&cont, _("Check constraints:"));
2488  for (i = 0; i < tuples; i++)
2489  {
2490  /* untranslated constraint name and def */
2491  printfPQExpBuffer(&buf, " \"%s\" %s",
2492  PQgetvalue(result, i, 0),
2493  PQgetvalue(result, i, 1));
2494 
2495  printTableAddFooter(&cont, buf.data);
2496  }
2497  }
2498  PQclear(result);
2499  }
2500 
2501  /*
2502  * Print foreign-key constraints (there are none if no triggers,
2503  * except if the table is partitioned, in which case the triggers
2504  * appear in the partitions)
2505  */
2506  if (tableinfo.hastriggers ||
2507  tableinfo.relkind == RELKIND_PARTITIONED_TABLE)
2508  {
2509  if (pset.sversion >= 120000 &&
2510  (tableinfo.ispartition || tableinfo.relkind == RELKIND_PARTITIONED_TABLE))
2511  {
2512  /*
2513  * Put the constraints defined in this table first, followed
2514  * by the constraints defined in ancestor partitioned tables.
2515  */
2517  "SELECT conrelid = '%s'::pg_catalog.regclass AS sametable,\n"
2518  " conname,\n"
2519  " pg_catalog.pg_get_constraintdef(oid, true) AS condef,\n"
2520  " conrelid::pg_catalog.regclass AS ontable\n"
2521  " FROM pg_catalog.pg_constraint,\n"
2522  " pg_catalog.pg_partition_ancestors('%s')\n"
2523  " WHERE conrelid = relid AND contype = 'f' AND conparentid = 0\n"
2524  "ORDER BY sametable DESC, conname;",
2525  oid, oid);
2526  }
2527  else
2528  {
2530  "SELECT true as sametable, conname,\n"
2531  " pg_catalog.pg_get_constraintdef(r.oid, true) as condef,\n"
2532  " conrelid::pg_catalog.regclass AS ontable\n"
2533  "FROM pg_catalog.pg_constraint r\n"
2534  "WHERE r.conrelid = '%s' AND r.contype = 'f'\n",
2535  oid);
2536 
2537  if (pset.sversion >= 120000)
2538  appendPQExpBufferStr(&buf, " AND conparentid = 0\n");
2539  appendPQExpBufferStr(&buf, "ORDER BY conname");
2540  }
2541 
2542  result = PSQLexec(buf.data);
2543  if (!result)
2544  goto error_return;
2545  else
2546  tuples = PQntuples(result);
2547 
2548  if (tuples > 0)
2549  {
2550  int i_sametable = PQfnumber(result, "sametable"),
2551  i_conname = PQfnumber(result, "conname"),
2552  i_condef = PQfnumber(result, "condef"),
2553  i_ontable = PQfnumber(result, "ontable");
2554 
2555  printTableAddFooter(&cont, _("Foreign-key constraints:"));
2556  for (i = 0; i < tuples; i++)
2557  {
2558  /*
2559  * Print untranslated constraint name and definition. Use
2560  * a "TABLE tab" prefix when the constraint is defined in
2561  * a parent partitioned table.
2562  */
2563  if (strcmp(PQgetvalue(result, i, i_sametable), "f") == 0)
2564  printfPQExpBuffer(&buf, " TABLE \"%s\" CONSTRAINT \"%s\" %s",
2565  PQgetvalue(result, i, i_ontable),
2566  PQgetvalue(result, i, i_conname),
2567  PQgetvalue(result, i, i_condef));
2568  else
2569  printfPQExpBuffer(&buf, " \"%s\" %s",
2570  PQgetvalue(result, i, i_conname),
2571  PQgetvalue(result, i, i_condef));
2572 
2573  printTableAddFooter(&cont, buf.data);
2574  }
2575  }
2576  PQclear(result);
2577  }
2578 
2579  /* print incoming foreign-key references */
2580  if (tableinfo.hastriggers ||
2581  tableinfo.relkind == RELKIND_PARTITIONED_TABLE)
2582  {
2583  if (pset.sversion >= 120000)
2584  {
2586  "SELECT conname, conrelid::pg_catalog.regclass AS ontable,\n"
2587  " pg_catalog.pg_get_constraintdef(oid, true) AS condef\n"
2588  " FROM pg_catalog.pg_constraint c\n"
2589  " WHERE confrelid IN (SELECT pg_catalog.pg_partition_ancestors('%s')\n"
2590  " UNION ALL VALUES ('%s'::pg_catalog.regclass))\n"
2591  " AND contype = 'f' AND conparentid = 0\n"
2592  "ORDER BY conname;",
2593  oid, oid);
2594  }
2595  else
2596  {
2598  "SELECT conname, conrelid::pg_catalog.regclass AS ontable,\n"
2599  " pg_catalog.pg_get_constraintdef(oid, true) AS condef\n"
2600  " FROM pg_catalog.pg_constraint\n"
2601  " WHERE confrelid = %s AND contype = 'f'\n"
2602  "ORDER BY conname;",
2603  oid);
2604  }
2605 
2606  result = PSQLexec(buf.data);
2607  if (!result)
2608  goto error_return;
2609  else
2610  tuples = PQntuples(result);
2611 
2612  if (tuples > 0)
2613  {
2614  int i_conname = PQfnumber(result, "conname"),
2615  i_ontable = PQfnumber(result, "ontable"),
2616  i_condef = PQfnumber(result, "condef");
2617 
2618  printTableAddFooter(&cont, _("Referenced by:"));
2619  for (i = 0; i < tuples; i++)
2620  {
2621  printfPQExpBuffer(&buf, " TABLE \"%s\" CONSTRAINT \"%s\" %s",
2622  PQgetvalue(result, i, i_ontable),
2623  PQgetvalue(result, i, i_conname),
2624  PQgetvalue(result, i, i_condef));
2625 
2626  printTableAddFooter(&cont, buf.data);
2627  }
2628  }
2629  PQclear(result);
2630  }
2631 
2632  /* print any row-level policies */
2633  if (pset.sversion >= 90500)
2634  {
2635  printfPQExpBuffer(&buf, "SELECT pol.polname,");
2636  if (pset.sversion >= 100000)
2638  " pol.polpermissive,\n");
2639  else
2641  " 't' as polpermissive,\n");
2643  " CASE WHEN pol.polroles = '{0}' THEN NULL ELSE pg_catalog.array_to_string(array(select rolname from pg_catalog.pg_roles where oid = any (pol.polroles) order by 1),',') END,\n"
2644  " pg_catalog.pg_get_expr(pol.polqual, pol.polrelid),\n"
2645  " pg_catalog.pg_get_expr(pol.polwithcheck, pol.polrelid),\n"
2646  " CASE pol.polcmd\n"
2647  " WHEN 'r' THEN 'SELECT'\n"
2648  " WHEN 'a' THEN 'INSERT'\n"
2649  " WHEN 'w' THEN 'UPDATE'\n"
2650  " WHEN 'd' THEN 'DELETE'\n"
2651  " END AS cmd\n"
2652  "FROM pg_catalog.pg_policy pol\n"
2653  "WHERE pol.polrelid = '%s' ORDER BY 1;",
2654  oid);
2655 
2656  result = PSQLexec(buf.data);
2657  if (!result)
2658  goto error_return;
2659  else
2660  tuples = PQntuples(result);
2661 
2662  /*
2663  * Handle cases where RLS is enabled and there are policies, or
2664  * there aren't policies, or RLS isn't enabled but there are
2665  * policies
2666  */
2667  if (tableinfo.rowsecurity && !tableinfo.forcerowsecurity && tuples > 0)
2668  printTableAddFooter(&cont, _("Policies:"));
2669 
2670  if (tableinfo.rowsecurity && tableinfo.forcerowsecurity && tuples > 0)
2671  printTableAddFooter(&cont, _("Policies (forced row security enabled):"));
2672 
2673  if (tableinfo.rowsecurity && !tableinfo.forcerowsecurity && tuples == 0)
2674  printTableAddFooter(&cont, _("Policies (row security enabled): (none)"));
2675 
2676  if (tableinfo.rowsecurity && tableinfo.forcerowsecurity && tuples == 0)
2677  printTableAddFooter(&cont, _("Policies (forced row security enabled): (none)"));
2678 
2679  if (!tableinfo.rowsecurity && tuples > 0)
2680  printTableAddFooter(&cont, _("Policies (row security disabled):"));
2681 
2682  /* Might be an empty set - that's ok */
2683  for (i = 0; i < tuples; i++)
2684  {
2685  printfPQExpBuffer(&buf, " POLICY \"%s\"",
2686  PQgetvalue(result, i, 0));
2687 
2688  if (*(PQgetvalue(result, i, 1)) == 'f')
2689  appendPQExpBufferStr(&buf, " AS RESTRICTIVE");
2690 
2691  if (!PQgetisnull(result, i, 5))
2692  appendPQExpBuffer(&buf, " FOR %s",
2693  PQgetvalue(result, i, 5));
2694 
2695  if (!PQgetisnull(result, i, 2))
2696  {
2697  appendPQExpBuffer(&buf, "\n TO %s",
2698  PQgetvalue(result, i, 2));
2699  }
2700 
2701  if (!PQgetisnull(result, i, 3))
2702  appendPQExpBuffer(&buf, "\n USING (%s)",
2703  PQgetvalue(result, i, 3));
2704 
2705  if (!PQgetisnull(result, i, 4))
2706  appendPQExpBuffer(&buf, "\n WITH CHECK (%s)",
2707  PQgetvalue(result, i, 4));
2708 
2709  printTableAddFooter(&cont, buf.data);
2710  }
2711  PQclear(result);
2712  }
2713 
2714  /* print any extended statistics */
2715  if (pset.sversion >= 140000)
2716  {
2718  "SELECT oid, "
2719  "stxrelid::pg_catalog.regclass, "
2720  "stxnamespace::pg_catalog.regnamespace::pg_catalog.text AS nsp, "
2721  "stxname,\n"
2722  "pg_catalog.pg_get_statisticsobjdef_columns(oid) AS columns,\n"
2723  " 'd' = any(stxkind) AS ndist_enabled,\n"
2724  " 'f' = any(stxkind) AS deps_enabled,\n"
2725  " 'm' = any(stxkind) AS mcv_enabled,\n"
2726  "stxstattarget\n"
2727  "FROM pg_catalog.pg_statistic_ext\n"
2728  "WHERE stxrelid = '%s'\n"
2729  "ORDER BY nsp, stxname;",
2730  oid);
2731 
2732  result = PSQLexec(buf.data);
2733  if (!result)
2734  goto error_return;
2735  else
2736  tuples = PQntuples(result);
2737 
2738  if (tuples > 0)
2739  {
2740  printTableAddFooter(&cont, _("Statistics objects:"));
2741 
2742  for (i = 0; i < tuples; i++)
2743  {
2744  bool gotone = false;
2745  bool has_ndistinct;
2746  bool has_dependencies;
2747  bool has_mcv;
2748  bool has_all;
2749  bool has_some;
2750 
2751  has_ndistinct = (strcmp(PQgetvalue(result, i, 5), "t") == 0);
2752  has_dependencies = (strcmp(PQgetvalue(result, i, 6), "t") == 0);
2753  has_mcv = (strcmp(PQgetvalue(result, i, 7), "t") == 0);
2754 
2755  printfPQExpBuffer(&buf, " ");
2756 
2757  /* statistics object name (qualified with namespace) */
2758  appendPQExpBuffer(&buf, "\"%s.%s\"",
2759  PQgetvalue(result, i, 2),
2760  PQgetvalue(result, i, 3));
2761 
2762  /*
2763  * When printing kinds we ignore expression statistics,
2764  * which are used only internally and can't be specified
2765  * by user. We don't print the kinds when none are
2766  * specified (in which case it has to be statistics on a
2767  * single expr) or when all are specified (in which case
2768  * we assume it's expanded by CREATE STATISTICS).
2769  */
2770  has_all = (has_ndistinct && has_dependencies && has_mcv);
2771  has_some = (has_ndistinct || has_dependencies || has_mcv);
2772 
2773  if (has_some && !has_all)
2774  {
2775  appendPQExpBufferStr(&buf, " (");
2776 
2777  /* options */
2778  if (has_ndistinct)
2779  {
2780  appendPQExpBufferStr(&buf, "ndistinct");
2781  gotone = true;
2782  }
2783 
2784  if (has_dependencies)
2785  {
2786  appendPQExpBuffer(&buf, "%sdependencies", gotone ? ", " : "");
2787  gotone = true;
2788  }
2789 
2790  if (has_mcv)
2791  {
2792  appendPQExpBuffer(&buf, "%smcv", gotone ? ", " : "");
2793  }
2794 
2795  appendPQExpBufferChar(&buf, ')');
2796  }
2797 
2798  appendPQExpBuffer(&buf, " ON %s FROM %s",
2799  PQgetvalue(result, i, 4),
2800  PQgetvalue(result, i, 1));
2801 
2802  /* Show the stats target if it's not default */
2803  if (strcmp(PQgetvalue(result, i, 8), "-1") != 0)
2804  appendPQExpBuffer(&buf, "; STATISTICS %s",
2805  PQgetvalue(result, i, 8));
2806 
2807  printTableAddFooter(&cont, buf.data);
2808  }
2809  }
2810  PQclear(result);
2811  }
2812  else if (pset.sversion >= 100000)
2813  {
2815  "SELECT oid, "
2816  "stxrelid::pg_catalog.regclass, "
2817  "stxnamespace::pg_catalog.regnamespace AS nsp, "
2818  "stxname,\n"
2819  " (SELECT pg_catalog.string_agg(pg_catalog.quote_ident(attname),', ')\n"
2820  " FROM pg_catalog.unnest(stxkeys) s(attnum)\n"
2821  " JOIN pg_catalog.pg_attribute a ON (stxrelid = a.attrelid AND\n"
2822  " a.attnum = s.attnum AND NOT attisdropped)) AS columns,\n"
2823  " 'd' = any(stxkind) AS ndist_enabled,\n"
2824  " 'f' = any(stxkind) AS deps_enabled,\n"
2825  " 'm' = any(stxkind) AS mcv_enabled,\n");
2826 
2827  if (pset.sversion >= 130000)
2828  appendPQExpBufferStr(&buf, " stxstattarget\n");
2829  else
2830  appendPQExpBufferStr(&buf, " -1 AS stxstattarget\n");
2831  appendPQExpBuffer(&buf, "FROM pg_catalog.pg_statistic_ext\n"
2832  "WHERE stxrelid = '%s'\n"
2833  "ORDER BY 1;",
2834  oid);
2835 
2836  result = PSQLexec(buf.data);
2837  if (!result)
2838  goto error_return;
2839  else
2840  tuples = PQntuples(result);
2841 
2842  if (tuples > 0)
2843  {
2844  printTableAddFooter(&cont, _("Statistics objects:"));
2845 
2846  for (i = 0; i < tuples; i++)
2847  {
2848  bool gotone = false;
2849 
2850  printfPQExpBuffer(&buf, " ");
2851 
2852  /* statistics object name (qualified with namespace) */
2853  appendPQExpBuffer(&buf, "\"%s.%s\" (",
2854  PQgetvalue(result, i, 2),
2855  PQgetvalue(result, i, 3));
2856 
2857  /* options */
2858  if (strcmp(PQgetvalue(result, i, 5), "t") == 0)
2859  {
2860  appendPQExpBufferStr(&buf, "ndistinct");
2861  gotone = true;
2862  }
2863 
2864  if (strcmp(PQgetvalue(result, i, 6), "t") == 0)
2865  {
2866  appendPQExpBuffer(&buf, "%sdependencies", gotone ? ", " : "");
2867  gotone = true;
2868  }
2869 
2870  if (strcmp(PQgetvalue(result, i, 7), "t") == 0)
2871  {
2872  appendPQExpBuffer(&buf, "%smcv", gotone ? ", " : "");
2873  }
2874 
2875  appendPQExpBuffer(&buf, ") ON %s FROM %s",
2876  PQgetvalue(result, i, 4),
2877  PQgetvalue(result, i, 1));
2878 
2879  /* Show the stats target if it's not default */
2880  if (strcmp(PQgetvalue(result, i, 8), "-1") != 0)
2881  appendPQExpBuffer(&buf, "; STATISTICS %s",
2882  PQgetvalue(result, i, 8));
2883 
2884  printTableAddFooter(&cont, buf.data);
2885  }
2886  }
2887  PQclear(result);
2888  }
2889 
2890  /* print rules */
2891  if (tableinfo.hasrules && tableinfo.relkind != RELKIND_MATVIEW)
2892  {
2894  "SELECT r.rulename, trim(trailing ';' from pg_catalog.pg_get_ruledef(r.oid, true)), "
2895  "ev_enabled\n"
2896  "FROM pg_catalog.pg_rewrite r\n"
2897  "WHERE r.ev_class = '%s' ORDER BY 1;",
2898  oid);
2899  result = PSQLexec(buf.data);
2900  if (!result)
2901  goto error_return;
2902  else
2903  tuples = PQntuples(result);
2904 
2905  if (tuples > 0)
2906  {
2907  bool have_heading;
2908  int category;
2909 
2910  for (category = 0; category < 4; category++)
2911  {
2912  have_heading = false;
2913 
2914  for (i = 0; i < tuples; i++)
2915  {
2916  const char *ruledef;
2917  bool list_rule = false;
2918 
2919  switch (category)
2920  {
2921  case 0:
2922  if (*PQgetvalue(result, i, 2) == 'O')
2923  list_rule = true;
2924  break;
2925  case 1:
2926  if (*PQgetvalue(result, i, 2) == 'D')
2927  list_rule = true;
2928  break;
2929  case 2:
2930  if (*PQgetvalue(result, i, 2) == 'A')
2931  list_rule = true;
2932  break;
2933  case 3:
2934  if (*PQgetvalue(result, i, 2) == 'R')
2935  list_rule = true;
2936  break;
2937  }
2938  if (!list_rule)
2939  continue;
2940 
2941  if (!have_heading)
2942  {
2943  switch (category)
2944  {
2945  case 0:
2946  printfPQExpBuffer(&buf, _("Rules:"));
2947  break;
2948  case 1:
2949  printfPQExpBuffer(&buf, _("Disabled rules:"));
2950  break;
2951  case 2:
2952  printfPQExpBuffer(&buf, _("Rules firing always:"));
2953  break;
2954  case 3:
2955  printfPQExpBuffer(&buf, _("Rules firing on replica only:"));
2956  break;
2957  }
2958  printTableAddFooter(&cont, buf.data);
2959  have_heading = true;
2960  }
2961 
2962  /* Everything after "CREATE RULE" is echoed verbatim */
2963  ruledef = PQgetvalue(result, i, 1);
2964  ruledef += 12;
2965  printfPQExpBuffer(&buf, " %s", ruledef);
2966  printTableAddFooter(&cont, buf.data);
2967  }
2968  }
2969  }
2970  PQclear(result);
2971  }
2972 
2973  /* print any publications */
2974  if (pset.sversion >= 100000)
2975  {
2976  if (pset.sversion >= 150000)
2977  {
2979  "SELECT pubname\n"
2980  " , NULL\n"
2981  " , NULL\n"
2982  "FROM pg_catalog.pg_publication p\n"
2983  " JOIN pg_catalog.pg_publication_namespace pn ON p.oid = pn.pnpubid\n"
2984  " JOIN pg_catalog.pg_class pc ON pc.relnamespace = pn.pnnspid\n"
2985  "WHERE pc.oid ='%s' and pg_catalog.pg_relation_is_publishable('%s')\n"
2986  "UNION\n"
2987  "SELECT pubname\n"
2988  " , pg_get_expr(pr.prqual, c.oid)\n"
2989  " , (CASE WHEN pr.prattrs IS NOT NULL THEN\n"
2990  " (SELECT string_agg(attname, ', ')\n"
2991  " FROM pg_catalog.generate_series(0, pg_catalog.array_upper(pr.prattrs::pg_catalog.int2[], 1)) s,\n"
2992  " pg_catalog.pg_attribute\n"
2993  " WHERE attrelid = pr.prrelid AND attnum = prattrs[s])\n"
2994  " ELSE NULL END) "
2995  "FROM pg_catalog.pg_publication p\n"
2996  " JOIN pg_catalog.pg_publication_rel pr ON p.oid = pr.prpubid\n"
2997  " JOIN pg_catalog.pg_class c ON c.oid = pr.prrelid\n"
2998  "WHERE pr.prrelid = '%s'\n"
2999  "UNION\n"
3000  "SELECT pubname\n"
3001  " , NULL\n"
3002  " , NULL\n"
3003  "FROM pg_catalog.pg_publication p\n"
3004  "WHERE p.puballtables AND pg_catalog.pg_relation_is_publishable('%s')\n"
3005  "ORDER BY 1;",
3006  oid, oid, oid, oid);
3007  }
3008  else
3009  {
3011  "SELECT pubname\n"
3012  " , NULL\n"
3013  " , NULL\n"
3014  "FROM pg_catalog.pg_publication p\n"
3015  "JOIN pg_catalog.pg_publication_rel pr ON p.oid = pr.prpubid\n"
3016  "WHERE pr.prrelid = '%s'\n"
3017  "UNION ALL\n"
3018  "SELECT pubname\n"
3019  " , NULL\n"
3020  " , NULL\n"
3021  "FROM pg_catalog.pg_publication p\n"
3022  "WHERE p.puballtables AND pg_catalog.pg_relation_is_publishable('%s')\n"
3023  "ORDER BY 1;",
3024  oid, oid);
3025  }
3026 
3027  result = PSQLexec(buf.data);
3028  if (!result)
3029  goto error_return;
3030  else
3031  tuples = PQntuples(result);
3032 
3033  if (tuples > 0)
3034  printTableAddFooter(&cont, _("Publications:"));
3035 
3036  /* Might be an empty set - that's ok */
3037  for (i = 0; i < tuples; i++)
3038  {
3039  printfPQExpBuffer(&buf, " \"%s\"",
3040  PQgetvalue(result, i, 0));
3041 
3042  /* column list (if any) */
3043  if (!PQgetisnull(result, i, 2))
3044  appendPQExpBuffer(&buf, " (%s)",
3045  PQgetvalue(result, i, 2));
3046 
3047  /* row filter (if any) */
3048  if (!PQgetisnull(result, i, 1))
3049  appendPQExpBuffer(&buf, " WHERE %s",
3050  PQgetvalue(result, i, 1));
3051 
3052  printTableAddFooter(&cont, buf.data);
3053  }
3054  PQclear(result);
3055  }
3056 
3057  /* If verbose, print NOT NULL constraints */
3058  if (verbose)
3059  {
3061  "SELECT co.conname, at.attname, co.connoinherit, co.conislocal,\n"
3062  "co.coninhcount <> 0\n"
3063  "FROM pg_catalog.pg_constraint co JOIN\n"
3064  "pg_catalog.pg_attribute at ON\n"
3065  "(at.attnum = co.conkey[1])\n"
3066  "WHERE co.contype = 'n' AND\n"
3067  "co.conrelid = '%s'::pg_catalog.regclass AND\n"
3068  "at.attrelid = '%s'::pg_catalog.regclass\n"
3069  "ORDER BY at.attnum",
3070  oid,
3071  oid);
3072 
3073  result = PSQLexec(buf.data);
3074  if (!result)
3075  goto error_return;
3076  else
3077  tuples = PQntuples(result);
3078 
3079  if (tuples > 0)
3080  printTableAddFooter(&cont, _("Not-null constraints:"));
3081 
3082  /* Might be an empty set - that's ok */
3083  for (i = 0; i < tuples; i++)
3084  {
3085  bool islocal = PQgetvalue(result, i, 3)[0] == 't';
3086  bool inherited = PQgetvalue(result, i, 4)[0] == 't';
3087 
3088  printfPQExpBuffer(&buf, " \"%s\" NOT NULL \"%s\"%s",
3089  PQgetvalue(result, i, 0),
3090  PQgetvalue(result, i, 1),
3091  PQgetvalue(result, i, 2)[0] == 't' ?
3092  " NO INHERIT" :
3093  islocal && inherited ? _(" (local, inherited)") :
3094  inherited ? _(" (inherited)") : "");
3095 
3096  printTableAddFooter(&cont, buf.data);
3097  }
3098  PQclear(result);
3099  }
3100  }
3101 
3102  /* Get view_def if table is a view or materialized view */
3103  if ((tableinfo.relkind == RELKIND_VIEW ||
3104  tableinfo.relkind == RELKIND_MATVIEW) && verbose)
3105  {
3106  PGresult *result;
3107 
3109  "SELECT pg_catalog.pg_get_viewdef('%s'::pg_catalog.oid, true);",
3110  oid);
3111  result = PSQLexec(buf.data);
3112  if (!result)
3113  goto error_return;
3114 
3115  if (PQntuples(result) > 0)
3116  view_def = pg_strdup(PQgetvalue(result, 0, 0));
3117 
3118  PQclear(result);
3119  }
3120 
3121  if (view_def)
3122  {
3123  PGresult *result = NULL;
3124 
3125  /* Footer information about a view */
3126  printTableAddFooter(&cont, _("View definition:"));
3127  printTableAddFooter(&cont, view_def);
3128 
3129  /* print rules */
3130  if (tableinfo.hasrules)
3131  {
3133  "SELECT r.rulename, trim(trailing ';' from pg_catalog.pg_get_ruledef(r.oid, true))\n"
3134  "FROM pg_catalog.pg_rewrite r\n"
3135  "WHERE r.ev_class = '%s' AND r.rulename != '_RETURN' ORDER BY 1;",
3136  oid);
3137  result = PSQLexec(buf.data);
3138  if (!result)
3139  goto error_return;
3140 
3141  if (PQntuples(result) > 0)
3142  {
3143  printTableAddFooter(&cont, _("Rules:"));
3144  for (i = 0; i < PQntuples(result); i++)
3145  {
3146  const char *ruledef;
3147 
3148  /* Everything after "CREATE RULE" is echoed verbatim */
3149  ruledef = PQgetvalue(result, i, 1);
3150  ruledef += 12;
3151 
3152  printfPQExpBuffer(&buf, " %s", ruledef);
3153  printTableAddFooter(&cont, buf.data);
3154  }
3155  }
3156  PQclear(result);
3157  }
3158  }
3159 
3160  /*
3161  * Print triggers next, if any (but only user-defined triggers). This
3162  * could apply to either a table or a view.
3163  */
3164  if (tableinfo.hastriggers)
3165  {
3166  PGresult *result;
3167  int tuples;
3168 
3170  "SELECT t.tgname, "
3171  "pg_catalog.pg_get_triggerdef(t.oid, true), "
3172  "t.tgenabled, t.tgisinternal,\n");
3173 
3174  /*
3175  * Detect whether each trigger is inherited, and if so, get the name
3176  * of the topmost table it's inherited from. We have no easy way to
3177  * do that pre-v13, for lack of the tgparentid column. Even with
3178  * tgparentid, a straightforward search for the topmost parent would
3179  * require a recursive CTE, which seems unduly expensive. We cheat a
3180  * bit by assuming parent triggers will match by tgname; then, joining
3181  * with pg_partition_ancestors() allows the planner to make use of
3182  * pg_trigger_tgrelid_tgname_index if it wishes. We ensure we find
3183  * the correct topmost parent by stopping at the first-in-partition-
3184  * ancestry-order trigger that has tgparentid = 0. (There might be
3185  * unrelated, non-inherited triggers with the same name further up the
3186  * stack, so this is important.)
3187  */
3188  if (pset.sversion >= 130000)
3190  " CASE WHEN t.tgparentid != 0 THEN\n"
3191  " (SELECT u.tgrelid::pg_catalog.regclass\n"
3192  " FROM pg_catalog.pg_trigger AS u,\n"
3193  " pg_catalog.pg_partition_ancestors(t.tgrelid) WITH ORDINALITY AS a(relid, depth)\n"
3194  " WHERE u.tgname = t.tgname AND u.tgrelid = a.relid\n"
3195  " AND u.tgparentid = 0\n"
3196  " ORDER BY a.depth LIMIT 1)\n"
3197  " END AS parent\n");
3198  else
3199  appendPQExpBufferStr(&buf, " NULL AS parent\n");
3200 
3202  "FROM pg_catalog.pg_trigger t\n"
3203  "WHERE t.tgrelid = '%s' AND ",
3204  oid);
3205 
3206  /*
3207  * tgisinternal is set true for inherited triggers of partitions in
3208  * servers between v11 and v14, though these must still be shown to
3209  * the user. So we use another property that is true for such
3210  * inherited triggers to avoid them being hidden, which is their
3211  * dependence on another trigger.
3212  */
3213  if (pset.sversion >= 110000 && pset.sversion < 150000)
3214  appendPQExpBufferStr(&buf, "(NOT t.tgisinternal OR (t.tgisinternal AND t.tgenabled = 'D') \n"
3215  " OR EXISTS (SELECT 1 FROM pg_catalog.pg_depend WHERE objid = t.oid \n"
3216  " AND refclassid = 'pg_catalog.pg_trigger'::pg_catalog.regclass))");
3217  else
3218  /* display/warn about disabled internal triggers */
3219  appendPQExpBufferStr(&buf, "(NOT t.tgisinternal OR (t.tgisinternal AND t.tgenabled = 'D'))");
3220  appendPQExpBufferStr(&buf, "\nORDER BY 1;");
3221 
3222  result = PSQLexec(buf.data);
3223  if (!result)
3224  goto error_return;
3225  else
3226  tuples = PQntuples(result);
3227 
3228  if (tuples > 0)
3229  {
3230  bool have_heading;
3231  int category;
3232 
3233  /*
3234  * split the output into 4 different categories. Enabled triggers,
3235  * disabled triggers and the two special ALWAYS and REPLICA
3236  * configurations.
3237  */
3238  for (category = 0; category <= 4; category++)
3239  {
3240  have_heading = false;
3241  for (i = 0; i < tuples; i++)
3242  {
3243  bool list_trigger;
3244  const char *tgdef;
3245  const char *usingpos;
3246  const char *tgenabled;
3247  const char *tgisinternal;
3248 
3249  /*
3250  * Check if this trigger falls into the current category
3251  */
3252  tgenabled = PQgetvalue(result, i, 2);
3253  tgisinternal = PQgetvalue(result, i, 3);
3254  list_trigger = false;
3255  switch (category)
3256  {
3257  case 0:
3258  if (*tgenabled == 'O' || *tgenabled == 't')
3259  list_trigger = true;
3260  break;
3261  case 1:
3262  if ((*tgenabled == 'D' || *tgenabled == 'f') &&
3263  *tgisinternal == 'f')
3264  list_trigger = true;
3265  break;
3266  case 2:
3267  if ((*tgenabled == 'D' || *tgenabled == 'f') &&
3268  *tgisinternal == 't')
3269  list_trigger = true;
3270  break;
3271  case 3:
3272  if (*tgenabled == 'A')
3273  list_trigger = true;
3274  break;
3275  case 4:
3276  if (*tgenabled == 'R')
3277  list_trigger = true;
3278  break;
3279  }
3280  if (list_trigger == false)
3281  continue;
3282 
3283  /* Print the category heading once */
3284  if (have_heading == false)
3285  {
3286  switch (category)
3287  {
3288  case 0:
3289  printfPQExpBuffer(&buf, _("Triggers:"));
3290  break;
3291  case 1:
3292  printfPQExpBuffer(&buf, _("Disabled user triggers:"));
3293  break;
3294  case 2:
3295  printfPQExpBuffer(&buf, _("Disabled internal triggers:"));
3296  break;
3297  case 3:
3298  printfPQExpBuffer(&buf, _("Triggers firing always:"));
3299  break;
3300  case 4:
3301  printfPQExpBuffer(&buf, _("Triggers firing on replica only:"));
3302  break;
3303  }
3304  printTableAddFooter(&cont, buf.data);
3305  have_heading = true;
3306  }
3307 
3308  /* Everything after "TRIGGER" is echoed verbatim */
3309  tgdef = PQgetvalue(result, i, 1);
3310  usingpos = strstr(tgdef, " TRIGGER ");
3311  if (usingpos)
3312  tgdef = usingpos + 9;
3313 
3314  printfPQExpBuffer(&buf, " %s", tgdef);
3315 
3316  /* Visually distinguish inherited triggers */
3317  if (!PQgetisnull(result, i, 4))
3318  appendPQExpBuffer(&buf, ", ON TABLE %s",
3319  PQgetvalue(result, i, 4));
3320 
3321  printTableAddFooter(&cont, buf.data);
3322  }
3323  }
3324  }
3325  PQclear(result);
3326  }
3327 
3328  /*
3329  * Finish printing the footer information about a table.
3330  */
3331  if (tableinfo.relkind == RELKIND_RELATION ||
3332  tableinfo.relkind == RELKIND_MATVIEW ||
3333  tableinfo.relkind == RELKIND_FOREIGN_TABLE ||
3334  tableinfo.relkind == RELKIND_PARTITIONED_TABLE ||
3335  tableinfo.relkind == RELKIND_PARTITIONED_INDEX ||
3336  tableinfo.relkind == RELKIND_TOASTVALUE)
3337  {
3338  bool is_partitioned;
3339  PGresult *result;
3340  int tuples;
3341 
3342  /* simplify some repeated tests below */
3343  is_partitioned = (tableinfo.relkind == RELKIND_PARTITIONED_TABLE ||
3344  tableinfo.relkind == RELKIND_PARTITIONED_INDEX);
3345 
3346  /* print foreign server name */
3347  if (tableinfo.relkind == RELKIND_FOREIGN_TABLE)
3348  {
3349  char *ftoptions;
3350 
3351  /* Footer information about foreign table */
3353  "SELECT s.srvname,\n"
3354  " pg_catalog.array_to_string(ARRAY(\n"
3355  " SELECT pg_catalog.quote_ident(option_name)"
3356  " || ' ' || pg_catalog.quote_literal(option_value)\n"
3357  " FROM pg_catalog.pg_options_to_table(ftoptions)), ', ')\n"
3358  "FROM pg_catalog.pg_foreign_table f,\n"
3359  " pg_catalog.pg_foreign_server s\n"
3360  "WHERE f.ftrelid = '%s' AND s.oid = f.ftserver;",
3361  oid);
3362  result = PSQLexec(buf.data);
3363  if (!result)
3364  goto error_return;
3365  else if (PQntuples(result) != 1)
3366  {
3367  PQclear(result);
3368  goto error_return;
3369  }
3370 
3371  /* Print server name */
3372  printfPQExpBuffer(&buf, _("Server: %s"),
3373  PQgetvalue(result, 0, 0));
3374  printTableAddFooter(&cont, buf.data);
3375 
3376  /* Print per-table FDW options, if any */
3377  ftoptions = PQgetvalue(result, 0, 1);
3378  if (ftoptions && ftoptions[0] != '\0')
3379  {
3380  printfPQExpBuffer(&buf, _("FDW options: (%s)"), ftoptions);
3381  printTableAddFooter(&cont, buf.data);
3382  }
3383  PQclear(result);
3384  }
3385 
3386  /* print tables inherited from (exclude partitioned parents) */
3388  "SELECT c.oid::pg_catalog.regclass\n"
3389  "FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i\n"
3390  "WHERE c.oid = i.inhparent AND i.inhrelid = '%s'\n"
3391  " AND c.relkind != " CppAsString2(RELKIND_PARTITIONED_TABLE)
3392  " AND c.relkind != " CppAsString2(RELKIND_PARTITIONED_INDEX)
3393  "\nORDER BY inhseqno;",
3394  oid);
3395 
3396  result = PSQLexec(buf.data);
3397  if (!result)
3398  goto error_return;
3399  else
3400  {
3401  const char *s = _("Inherits");
3402  int sw = pg_wcswidth(s, strlen(s), pset.encoding);
3403 
3404  tuples = PQntuples(result);
3405 
3406  for (i = 0; i < tuples; i++)
3407  {
3408  if (i == 0)
3409  printfPQExpBuffer(&buf, "%s: %s",
3410  s, PQgetvalue(result, i, 0));
3411  else
3412  printfPQExpBuffer(&buf, "%*s %s",
3413  sw, "", PQgetvalue(result, i, 0));
3414  if (i < tuples - 1)
3415  appendPQExpBufferChar(&buf, ',');
3416 
3417  printTableAddFooter(&cont, buf.data);
3418  }
3419 
3420  PQclear(result);
3421  }
3422 
3423  /* print child tables (with additional info if partitions) */
3424  if (pset.sversion >= 140000)
3426  "SELECT c.oid::pg_catalog.regclass, c.relkind,"
3427  " inhdetachpending,"
3428  " pg_catalog.pg_get_expr(c.relpartbound, c.oid)\n"
3429  "FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i\n"
3430  "WHERE c.oid = i.inhrelid AND i.inhparent = '%s'\n"
3431  "ORDER BY pg_catalog.pg_get_expr(c.relpartbound, c.oid) = 'DEFAULT',"
3432  " c.oid::pg_catalog.regclass::pg_catalog.text;",
3433  oid);
3434  else if (pset.sversion >= 100000)
3436  "SELECT c.oid::pg_catalog.regclass, c.relkind,"
3437  " false AS inhdetachpending,"
3438  " pg_catalog.pg_get_expr(c.relpartbound, c.oid)\n"
3439  "FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i\n"
3440  "WHERE c.oid = i.inhrelid AND i.inhparent = '%s'\n"
3441  "ORDER BY pg_catalog.pg_get_expr(c.relpartbound, c.oid) = 'DEFAULT',"
3442  " c.oid::pg_catalog.regclass::pg_catalog.text;",
3443  oid);
3444  else
3446  "SELECT c.oid::pg_catalog.regclass, c.relkind,"
3447  " false AS inhdetachpending, NULL\n"
3448  "FROM pg_catalog.pg_class c, pg_catalog.pg_inherits i\n"
3449  "WHERE c.oid = i.inhrelid AND i.inhparent = '%s'\n"
3450  "ORDER BY c.oid::pg_catalog.regclass::pg_catalog.text;",
3451  oid);
3452 
3453  result = PSQLexec(buf.data);
3454  if (!result)
3455  goto error_return;
3456  tuples = PQntuples(result);
3457 
3458  /*
3459  * For a partitioned table with no partitions, always print the number
3460  * of partitions as zero, even when verbose output is expected.
3461  * Otherwise, we will not print "Partitions" section for a partitioned
3462  * table without any partitions.
3463  */
3464  if (is_partitioned && tuples == 0)
3465  {
3466  printfPQExpBuffer(&buf, _("Number of partitions: %d"), tuples);
3467  printTableAddFooter(&cont, buf.data);
3468  }
3469  else if (!verbose)
3470  {
3471  /* print the number of child tables, if any */
3472  if (tuples > 0)
3473  {
3474  if (is_partitioned)
3475  printfPQExpBuffer(&buf, _("Number of partitions: %d (Use \\d+ to list them.)"), tuples);
3476  else
3477  printfPQExpBuffer(&buf, _("Number of child tables: %d (Use \\d+ to list them.)"), tuples);
3478  printTableAddFooter(&cont, buf.data);
3479  }
3480  }
3481  else
3482  {
3483  /* display the list of child tables */
3484  const char *ct = is_partitioned ? _("Partitions") : _("Child tables");
3485  int ctw = pg_wcswidth(ct, strlen(ct), pset.encoding);
3486 
3487  for (i = 0; i < tuples; i++)
3488  {
3489  char child_relkind = *PQgetvalue(result, i, 1);
3490 
3491  if (i == 0)
3492  printfPQExpBuffer(&buf, "%s: %s",
3493  ct, PQgetvalue(result, i, 0));
3494  else
3495  printfPQExpBuffer(&buf, "%*s %s",
3496  ctw, "", PQgetvalue(result, i, 0));
3497  if (!PQgetisnull(result, i, 3))
3498  appendPQExpBuffer(&buf, " %s", PQgetvalue(result, i, 3));
3499  if (child_relkind == RELKIND_PARTITIONED_TABLE ||
3500  child_relkind == RELKIND_PARTITIONED_INDEX)
3501  appendPQExpBufferStr(&buf, ", PARTITIONED");
3502  else if (child_relkind == RELKIND_FOREIGN_TABLE)
3503  appendPQExpBufferStr(&buf, ", FOREIGN");
3504  if (strcmp(PQgetvalue(result, i, 2), "t") == 0)
3505  appendPQExpBufferStr(&buf, " (DETACH PENDING)");
3506  if (i < tuples - 1)
3507  appendPQExpBufferChar(&buf, ',');
3508 
3509  printTableAddFooter(&cont, buf.data);
3510  }
3511  }
3512  PQclear(result);
3513 
3514  /* Table type */
3515  if (tableinfo.reloftype)
3516  {
3517  printfPQExpBuffer(&buf, _("Typed table of type: %s"), tableinfo.reloftype);
3518  printTableAddFooter(&cont, buf.data);
3519  }
3520 
3521  if (verbose &&
3522  (tableinfo.relkind == RELKIND_RELATION ||
3523  tableinfo.relkind == RELKIND_MATVIEW) &&
3524 
3525  /*
3526  * No need to display default values; we already display a REPLICA
3527  * IDENTITY marker on indexes.
3528  */
3529  tableinfo.relreplident != 'i' &&
3530  ((strcmp(schemaname, "pg_catalog") != 0 && tableinfo.relreplident != 'd') ||
3531  (strcmp(schemaname, "pg_catalog") == 0 && tableinfo.relreplident != 'n')))
3532  {
3533  const char *s = _("Replica Identity");
3534 
3535  printfPQExpBuffer(&buf, "%s: %s",
3536  s,
3537  tableinfo.relreplident == 'f' ? "FULL" :
3538  tableinfo.relreplident == 'n' ? "NOTHING" :
3539  "???");
3540 
3541  printTableAddFooter(&cont, buf.data);
3542  }
3543 
3544  /* OIDs, if verbose and not a materialized view */
3545  if (verbose && tableinfo.relkind != RELKIND_MATVIEW && tableinfo.hasoids)
3546  printTableAddFooter(&cont, _("Has OIDs: yes"));
3547 
3548  /* Tablespace info */
3549  add_tablespace_footer(&cont, tableinfo.relkind, tableinfo.tablespace,
3550  true);
3551 
3552  /* Access method info */
3553  if (verbose && tableinfo.relam != NULL && !pset.hide_tableam)
3554  {
3555  printfPQExpBuffer(&buf, _("Access method: %s"), tableinfo.relam);
3556  printTableAddFooter(&cont, buf.data);
3557  }
3558  }
3559 
3560  /* reloptions, if verbose */
3561  if (verbose &&
3562  tableinfo.reloptions && tableinfo.reloptions[0] != '\0')
3563  {
3564  const char *t = _("Options");
3565 
3566  printfPQExpBuffer(&buf, "%s: %s", t, tableinfo.reloptions);
3567  printTableAddFooter(&cont, buf.data);
3568  }
3569 
3570  printTable(&cont, pset.queryFout, false, pset.logfile);
3571 
3572  retval = true;
3573 
3574 error_return:
3575 
3576  /* clean up */
3577  if (printTableInitialized)
3578  printTableCleanup(&cont);
3579  termPQExpBuffer(&buf);
3580  termPQExpBuffer(&title);
3582 
3583  free(view_def);
3584 
3585  PQclear(res);
3586 
3587  return retval;
3588 }
3589 
3590 /*
3591  * Add a tablespace description to a footer. If 'newline' is true, it is added
3592  * in a new line; otherwise it's appended to the current value of the last
3593  * footer.
3594  */
3595 static void
3596 add_tablespace_footer(printTableContent *const cont, char relkind,
3597  Oid tablespace, const bool newline)
3598 {
3599  /* relkinds for which we support tablespaces */
3600  if (relkind == RELKIND_RELATION ||
3601  relkind == RELKIND_MATVIEW ||
3602  relkind == RELKIND_INDEX ||
3603  relkind == RELKIND_PARTITIONED_TABLE ||
3604  relkind == RELKIND_PARTITIONED_INDEX ||
3605  relkind == RELKIND_TOASTVALUE)
3606  {
3607  /*
3608  * We ignore the database default tablespace so that users not using
3609  * tablespaces don't need to know about them.
3610  */
3611  if (tablespace != 0)
3612  {
3613  PGresult *result = NULL;
3615 
3616  initPQExpBuffer(&buf);
3618  "SELECT spcname FROM pg_catalog.pg_tablespace\n"
3619  "WHERE oid = '%u';", tablespace);
3620  result = PSQLexec(buf.data);
3621  if (!result)
3622  {
3623  termPQExpBuffer(&buf);
3624  return;
3625  }
3626  /* Should always be the case, but.... */
3627  if (PQntuples(result) > 0)
3628  {
3629  if (newline)
3630  {
3631  /* Add the tablespace as a new footer */
3632  printfPQExpBuffer(&buf, _("Tablespace: \"%s\""),
3633  PQgetvalue(result, 0, 0));
3634  printTableAddFooter(cont, buf.data);
3635  }
3636  else
3637  {
3638  /* Append the tablespace to the latest footer */
3639  printfPQExpBuffer(&buf, "%s", cont->footer->data);
3640 
3641  /*-------
3642  translator: before this string there's an index description like
3643  '"foo_pkey" PRIMARY KEY, btree (a)' */
3644  appendPQExpBuffer(&buf, _(", tablespace \"%s\""),
3645  PQgetvalue(result, 0, 0));
3646  printTableSetFooter(cont, buf.data);
3647  }
3648  }
3649  PQclear(result);
3650  termPQExpBuffer(&buf);
3651  }
3652  }
3653 }
3654 
3655 /*
3656  * \du or \dg
3657  *
3658  * Describes roles. Any schema portion of the pattern is ignored.
3659  */
3660 bool
3661 describeRoles(const char *pattern, bool verbose, bool showSystem)
3662 {
3664  PGresult *res;
3665  printTableContent cont;
3666  printTableOpt myopt = pset.popt.topt;
3667  int ncols = 2;
3668  int nrows = 0;
3669  int i;
3670  int conns;
3671  const char align = 'l';
3672  char **attr;
3673 
3674  myopt.default_footer = false;
3675 
3676  initPQExpBuffer(&buf);
3677 
3679  "SELECT r.rolname, r.rolsuper, r.rolinherit,\n"
3680  " r.rolcreaterole, r.rolcreatedb, r.rolcanlogin,\n"
3681  " r.rolconnlimit, r.rolvaliduntil");
3682 
3683  if (verbose)
3684  {
3685  appendPQExpBufferStr(&buf, "\n, pg_catalog.shobj_description(r.oid, 'pg_authid') AS description");
3686  ncols++;
3687  }
3688  appendPQExpBufferStr(&buf, "\n, r.rolreplication");
3689 
3690  if (pset.sversion >= 90500)
3691  {
3692  appendPQExpBufferStr(&buf, "\n, r.rolbypassrls");
3693  }
3694 
3695  appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_roles r\n");
3696 
3697  if (!showSystem && !pattern)
3698  appendPQExpBufferStr(&buf, "WHERE r.rolname !~ '^pg_'\n");
3699 
3700  if (!validateSQLNamePattern(&buf, pattern, false, false,
3701  NULL, "r.rolname", NULL, NULL,
3702  NULL, 1))
3703  {
3704  termPQExpBuffer(&buf);
3705  return false;
3706  }
3707 
3708  appendPQExpBufferStr(&buf, "ORDER BY 1;");
3709 
3710  res = PSQLexec(buf.data);
3711  if (!res)
3712  return false;
3713 
3714  nrows = PQntuples(res);
3715  attr = pg_malloc0((nrows + 1) * sizeof(*attr));
3716 
3717  printTableInit(&cont, &myopt, _("List of roles"), ncols, nrows);
3718 
3719  printTableAddHeader(&cont, gettext_noop("Role name"), true, align);
3720  printTableAddHeader(&cont, gettext_noop("Attributes"), true, align);
3721 
3722  if (verbose)
3723  printTableAddHeader(&cont, gettext_noop("Description"), true, align);
3724 
3725  for (i = 0; i < nrows; i++)
3726  {
3727  printTableAddCell(&cont, PQgetvalue(res, i, 0), false, false);
3728 
3730  if (strcmp(PQgetvalue(res, i, 1), "t") == 0)
3731  add_role_attribute(&buf, _("Superuser"));
3732 
3733  if (strcmp(PQgetvalue(res, i, 2), "t") != 0)
3734  add_role_attribute(&buf, _("No inheritance"));
3735 
3736  if (strcmp(PQgetvalue(res, i, 3), "t") == 0)
3737  add_role_attribute(&buf, _("Create role"));
3738 
3739  if (strcmp(PQgetvalue(res, i, 4), "t") == 0)
3740  add_role_attribute(&buf, _("Create DB"));
3741 
3742  if (strcmp(PQgetvalue(res, i, 5), "t") != 0)
3743  add_role_attribute(&buf, _("Cannot login"));
3744 
3745  if (strcmp(PQgetvalue(res, i, (verbose ? 9 : 8)), "t") == 0)
3746  add_role_attribute(&buf, _("Replication"));
3747 
3748  if (pset.sversion >= 90500)
3749  if (strcmp(PQgetvalue(res, i, (verbose ? 10 : 9)), "t") == 0)
3750  add_role_attribute(&buf, _("Bypass RLS"));
3751 
3752  conns = atoi(PQgetvalue(res, i, 6));
3753  if (conns >= 0)
3754  {
3755  if (buf.len > 0)
3756  appendPQExpBufferChar(&buf, '\n');
3757 
3758  if (conns == 0)
3759  appendPQExpBufferStr(&buf, _("No connections"));
3760  else
3761  appendPQExpBuffer(&buf, ngettext("%d connection",
3762  "%d connections",
3763  conns),
3764  conns);
3765  }
3766 
3767  if (strcmp(PQgetvalue(res, i, 7), "") != 0)
3768  {
3769  if (buf.len > 0)
3770  appendPQExpBufferChar(&buf, '\n');
3771  appendPQExpBufferStr(&buf, _("Password valid until "));
3773  }
3774 
3775  attr[i] = pg_strdup(buf.data);
3776 
3777  printTableAddCell(&cont, attr[i], false, false);
3778 
3779  if (verbose)
3780  printTableAddCell(&cont, PQgetvalue(res, i, 8), false, false);
3781  }
3782  termPQExpBuffer(&buf);
3783 
3784  printTable(&cont, pset.queryFout, false, pset.logfile);
3785  printTableCleanup(&cont);
3786 
3787  for (i = 0; i < nrows; i++)
3788  free(attr[i]);
3789  free(attr);
3790 
3791  PQclear(res);
3792  return true;
3793 }
3794 
3795 static void
3797 {
3798  if (buf->len > 0)
3799  appendPQExpBufferStr(buf, ", ");
3800 
3802 }
3803 
3804 /*
3805  * \drds
3806  */
3807 bool
3808 listDbRoleSettings(const char *pattern, const char *pattern2)
3809 {
3811  PGresult *res;
3812  printQueryOpt myopt = pset.popt;
3813  bool havewhere;
3814 
3815  initPQExpBuffer(&buf);
3816 
3817  printfPQExpBuffer(&buf, "SELECT rolname AS \"%s\", datname AS \"%s\",\n"
3818  "pg_catalog.array_to_string(setconfig, E'\\n') AS \"%s\"\n"
3819  "FROM pg_catalog.pg_db_role_setting s\n"
3820  "LEFT JOIN pg_catalog.pg_database d ON d.oid = setdatabase\n"
3821  "LEFT JOIN pg_catalog.pg_roles r ON r.oid = setrole\n",
3822  gettext_noop("Role"),
3823  gettext_noop("Database"),
3824  gettext_noop("Settings"));
3825  if (!validateSQLNamePattern(&buf, pattern, false, false,
3826  NULL, "r.rolname", NULL, NULL, &havewhere, 1))
3827  goto error_return;
3828  if (!validateSQLNamePattern(&buf, pattern2, havewhere, false,
3829  NULL, "d.datname", NULL, NULL,
3830  NULL, 1))
3831  goto error_return;
3832  appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
3833 
3834  res = PSQLexec(buf.data);
3835  termPQExpBuffer(&buf);
3836  if (!res)
3837  return false;
3838 
3839  /*
3840  * Most functions in this file are content to print an empty table when
3841  * there are no matching objects. We intentionally deviate from that
3842  * here, but only in !quiet mode, because of the possibility that the user
3843  * is confused about what the two pattern arguments mean.
3844  */
3845  if (PQntuples(res) == 0 && !pset.quiet)
3846  {
3847  if (pattern && pattern2)
3848  pg_log_error("Did not find any settings for role \"%s\" and database \"%s\".",
3849  pattern, pattern2);
3850  else if (pattern)
3851  pg_log_error("Did not find any settings for role \"%s\".",
3852  pattern);
3853  else
3854  pg_log_error("Did not find any settings.");
3855  }
3856  else
3857  {
3858  myopt.title = _("List of settings");
3859  myopt.translate_header = true;
3860 
3861  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
3862  }
3863 
3864  PQclear(res);
3865  return true;
3866 
3867 error_return:
3868  termPQExpBuffer(&buf);
3869  return false;
3870 }
3871 
3872 /*
3873  * \drg
3874  * Describes role grants.
3875  */
3876 bool
3877 describeRoleGrants(const char *pattern, bool showSystem)
3878 {
3880  PGresult *res;
3881  printQueryOpt myopt = pset.popt;
3882 
3883  initPQExpBuffer(&buf);
3885  "SELECT m.rolname AS \"%s\", r.rolname AS \"%s\",\n"
3886  " pg_catalog.concat_ws(', ',\n",
3887  gettext_noop("Role name"),
3888  gettext_noop("Member of"));
3889 
3890  if (pset.sversion >= 160000)
3892  " CASE WHEN pam.admin_option THEN 'ADMIN' END,\n"
3893  " CASE WHEN pam.inherit_option THEN 'INHERIT' END,\n"
3894  " CASE WHEN pam.set_option THEN 'SET' END\n");
3895  else
3897  " CASE WHEN pam.admin_option THEN 'ADMIN' END,\n"
3898  " CASE WHEN m.rolinherit THEN 'INHERIT' END,\n"
3899  " 'SET'\n");
3900 
3902  " ) AS \"%s\",\n"
3903  " g.rolname AS \"%s\"\n",
3904  gettext_noop("Options"),
3905  gettext_noop("Grantor"));
3906 
3908  "FROM pg_catalog.pg_roles m\n"
3909  " JOIN pg_catalog.pg_auth_members pam ON (pam.member = m.oid)\n"
3910  " LEFT JOIN pg_catalog.pg_roles r ON (pam.roleid = r.oid)\n"
3911  " LEFT JOIN pg_catalog.pg_roles g ON (pam.grantor = g.oid)\n");
3912 
3913  if (!showSystem && !pattern)
3914  appendPQExpBufferStr(&buf, "WHERE m.rolname !~ '^pg_'\n");
3915 
3916  if (!validateSQLNamePattern(&buf, pattern, false, false,
3917  NULL, "m.rolname", NULL, NULL,
3918  NULL, 1))
3919  {
3920  termPQExpBuffer(&buf);
3921  return false;
3922  }
3923 
3924  appendPQExpBufferStr(&buf, "ORDER BY 1, 2, 4;\n");
3925 
3926  res = PSQLexec(buf.data);
3927  termPQExpBuffer(&buf);
3928  if (!res)
3929  return false;
3930 
3931  myopt.title = _("List of role grants");
3932  myopt.translate_header = true;
3933 
3934  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
3935 
3936  PQclear(res);
3937  return true;
3938 }
3939 
3940 
3941 /*
3942  * listTables()
3943  *
3944  * handler for \dt, \di, etc.
3945  *
3946  * tabtypes is an array of characters, specifying what info is desired:
3947  * t - tables
3948  * i - indexes
3949  * v - views
3950  * m - materialized views
3951  * s - sequences
3952  * E - foreign table (Note: different from 'f', the relkind value)
3953  * (any order of the above is fine)
3954  */
3955 bool
3956 listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem)
3957 {
3958  bool showTables = strchr(tabtypes, 't') != NULL;
3959  bool showIndexes = strchr(tabtypes, 'i') != NULL;
3960  bool showViews = strchr(tabtypes, 'v') != NULL;
3961  bool showMatViews = strchr(tabtypes, 'm') != NULL;
3962  bool showSeq = strchr(tabtypes, 's') != NULL;
3963  bool showForeign = strchr(tabtypes, 'E') != NULL;
3964 
3966  PGresult *res;
3967  printQueryOpt myopt = pset.popt;
3968  int cols_so_far;
3969  bool translate_columns[] = {false, false, true, false, false, false, false, false, false};
3970 
3971  /* If tabtypes is empty, we default to \dtvmsE (but see also command.c) */
3972  if (!(showTables || showIndexes || showViews || showMatViews || showSeq || showForeign))
3973  showTables = showViews = showMatViews = showSeq = showForeign = true;
3974 
3975  initPQExpBuffer(&buf);
3976 
3978  "SELECT n.nspname as \"%s\",\n"
3979  " c.relname as \"%s\",\n"
3980  " CASE c.relkind"
3981  " WHEN " CppAsString2(RELKIND_RELATION) " THEN '%s'"
3982  " WHEN " CppAsString2(RELKIND_VIEW) " THEN '%s'"
3983  " WHEN " CppAsString2(RELKIND_MATVIEW) " THEN '%s'"
3984  " WHEN " CppAsString2(RELKIND_INDEX) " THEN '%s'"
3985  " WHEN " CppAsString2(RELKIND_SEQUENCE) " THEN '%s'"
3986  " WHEN " CppAsString2(RELKIND_TOASTVALUE) " THEN '%s'"
3987  " WHEN " CppAsString2(RELKIND_FOREIGN_TABLE) " THEN '%s'"
3988  " WHEN " CppAsString2(RELKIND_PARTITIONED_TABLE) " THEN '%s'"
3989  " WHEN " CppAsString2(RELKIND_PARTITIONED_INDEX) " THEN '%s'"
3990  " END as \"%s\",\n"
3991  " pg_catalog.pg_get_userbyid(c.relowner) as \"%s\"",
3992  gettext_noop("Schema"),
3993  gettext_noop("Name"),
3994  gettext_noop("table"),
3995  gettext_noop("view"),
3996  gettext_noop("materialized view"),
3997  gettext_noop("index"),
3998  gettext_noop("sequence"),
3999  gettext_noop("TOAST table"),
4000  gettext_noop("foreign table"),
4001  gettext_noop("partitioned table"),
4002  gettext_noop("partitioned index"),
4003  gettext_noop("Type"),
4004  gettext_noop("Owner"));
4005  cols_so_far = 4;
4006 
4007  if (showIndexes)
4008  {
4010  ",\n c2.relname as \"%s\"",
4011  gettext_noop("Table"));
4012  cols_so_far++;
4013  }
4014 
4015  if (verbose)
4016  {
4017  /*
4018  * Show whether a relation is permanent, temporary, or unlogged.
4019  */
4021  ",\n CASE c.relpersistence WHEN 'p' THEN '%s' WHEN 't' THEN '%s' WHEN 'u' THEN '%s' END as \"%s\"",
4022  gettext_noop("permanent"),
4023  gettext_noop("temporary"),
4024  gettext_noop("unlogged"),
4025  gettext_noop("Persistence"));
4026  translate_columns[cols_so_far] = true;
4027 
4028  /*
4029  * We don't bother to count cols_so_far below here, as there's no need
4030  * to; this might change with future additions to the output columns.
4031  */
4032 
4033  /*
4034  * Access methods exist for tables, materialized views and indexes.
4035  * This has been introduced in PostgreSQL 12 for tables.
4036  */
4037  if (pset.sversion >= 120000 && !pset.hide_tableam &&
4038  (showTables || showMatViews || showIndexes))
4040  ",\n am.amname as \"%s\"",
4041  gettext_noop("Access method"));
4042 
4044  ",\n pg_catalog.pg_size_pretty(pg_catalog.pg_table_size(c.oid)) as \"%s\""
4045  ",\n pg_catalog.obj_description(c.oid, 'pg_class') as \"%s\"",
4046  gettext_noop("Size"),
4047  gettext_noop("Description"));
4048  }
4049 
4051  "\nFROM pg_catalog.pg_class c"
4052  "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace");
4053 
4054  if (pset.sversion >= 120000 && !pset.hide_tableam &&
4055  (showTables || showMatViews || showIndexes))
4057  "\n LEFT JOIN pg_catalog.pg_am am ON am.oid = c.relam");
4058 
4059  if (showIndexes)
4061  "\n LEFT JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid"
4062  "\n LEFT JOIN pg_catalog.pg_class c2 ON i.indrelid = c2.oid");
4063 
4064  appendPQExpBufferStr(&buf, "\nWHERE c.relkind IN (");
4065  if (showTables)
4066  {
4067  appendPQExpBufferStr(&buf, CppAsString2(RELKIND_RELATION) ","
4068  CppAsString2(RELKIND_PARTITIONED_TABLE) ",");
4069  /* with 'S' or a pattern, allow 't' to match TOAST tables too */
4070  if (showSystem || pattern)
4071  appendPQExpBufferStr(&buf, CppAsString2(RELKIND_TOASTVALUE) ",");
4072  }
4073  if (showViews)
4074  appendPQExpBufferStr(&buf, CppAsString2(RELKIND_VIEW) ",");
4075  if (showMatViews)
4076  appendPQExpBufferStr(&buf, CppAsString2(RELKIND_MATVIEW) ",");
4077  if (showIndexes)
4078  appendPQExpBufferStr(&buf, CppAsString2(RELKIND_INDEX) ","
4079  CppAsString2(RELKIND_PARTITIONED_INDEX) ",");
4080  if (showSeq)
4081  appendPQExpBufferStr(&buf, CppAsString2(RELKIND_SEQUENCE) ",");
4082  if (showSystem || pattern)
4083  appendPQExpBufferStr(&buf, "'s',"); /* was RELKIND_SPECIAL */
4084  if (showForeign)
4085  appendPQExpBufferStr(&buf, CppAsString2(RELKIND_FOREIGN_TABLE) ",");
4086 
4087  appendPQExpBufferStr(&buf, "''"); /* dummy */
4088  appendPQExpBufferStr(&buf, ")\n");
4089 
4090  if (!showSystem && !pattern)
4091  appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
4092  " AND n.nspname !~ '^pg_toast'\n"
4093  " AND n.nspname <> 'information_schema'\n");
4094 
4095  if (!validateSQLNamePattern(&buf, pattern, true, false,
4096  "n.nspname", "c.relname", NULL,
4097  "pg_catalog.pg_table_is_visible(c.oid)",
4098  NULL, 3))
4099  {
4100  termPQExpBuffer(&buf);
4101  return false;
4102  }
4103 
4104  appendPQExpBufferStr(&buf, "ORDER BY 1,2;");
4105 
4106  res = PSQLexec(buf.data);
4107  termPQExpBuffer(&buf);
4108  if (!res)
4109  return false;
4110 
4111  /*
4112  * Most functions in this file are content to print an empty table when
4113  * there are no matching objects. We intentionally deviate from that
4114  * here, but only in !quiet mode, for historical reasons.
4115  */
4116  if (PQntuples(res) == 0 && !pset.quiet)
4117  {
4118  if (pattern)
4119  pg_log_error("Did not find any relation named \"%s\".",
4120  pattern);
4121  else
4122  pg_log_error("Did not find any relations.");
4123  }
4124  else
4125  {
4126  myopt.title = _("List of relations");
4127  myopt.translate_header = true;
4128  myopt.translate_columns = translate_columns;
4129  myopt.n_translate_columns = lengthof(translate_columns);
4130 
4131  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
4132  }
4133 
4134  PQclear(res);
4135  return true;
4136 }
4137 
4138 /*
4139  * \dP
4140  * Takes an optional regexp to select particular relations
4141  *
4142  * As with \d, you can specify the kinds of relations you want:
4143  *
4144  * t for tables
4145  * i for indexes
4146  *
4147  * And there's additional flags:
4148  *
4149  * n to list non-leaf partitioned tables
4150  *
4151  * and you can mix and match these in any order.
4152  */
4153 bool
4154 listPartitionedTables(const char *reltypes, const char *pattern, bool verbose)
4155 {
4156  bool showTables = strchr(reltypes, 't') != NULL;
4157  bool showIndexes = strchr(reltypes, 'i') != NULL;
4158  bool showNested = strchr(reltypes, 'n') != NULL;
4160  PQExpBufferData title;
4161  PGresult *res;
4162  printQueryOpt myopt = pset.popt;
4163  bool translate_columns[] = {false, false, false, false, false, false, false, false, false};
4164  const char *tabletitle;
4165  bool mixed_output = false;
4166 
4167  /*
4168  * Note: Declarative table partitioning is only supported as of Pg 10.0.
4169  */
4170  if (pset.sversion < 100000)
4171  {
4172  char sverbuf[32];
4173 
4174  pg_log_error("The server (version %s) does not support declarative table partitioning.",
4176  sverbuf, sizeof(sverbuf)));
4177  return true;
4178  }
4179 
4180  /* If no relation kind was selected, show them all */
4181  if (!showTables && !showIndexes)
4182  showTables = showIndexes = true;
4183 
4184  if (showIndexes && !showTables)
4185  tabletitle = _("List of partitioned indexes"); /* \dPi */
4186  else if (showTables && !showIndexes)
4187  tabletitle = _("List of partitioned tables"); /* \dPt */
4188  else
4189  {
4190  /* show all kinds */
4191  tabletitle = _("List of partitioned relations");
4192  mixed_output = true;
4193  }
4194 
4195  initPQExpBuffer(&buf);
4196 
4198  "SELECT n.nspname as \"%s\",\n"
4199  " c.relname as \"%s\",\n"
4200  " pg_catalog.pg_get_userbyid(c.relowner) as \"%s\"",
4201  gettext_noop("Schema"),
4202  gettext_noop("Name"),
4203  gettext_noop("Owner"));
4204 
4205  if (mixed_output)
4206  {
4208  ",\n CASE c.relkind"
4209  " WHEN " CppAsString2(RELKIND_PARTITIONED_TABLE) " THEN '%s'"
4210  " WHEN " CppAsString2(RELKIND_PARTITIONED_INDEX) " THEN '%s'"
4211  " END as \"%s\"",
4212  gettext_noop("partitioned table"),
4213  gettext_noop("partitioned index"),
4214  gettext_noop("Type"));
4215 
4216  translate_columns[3] = true;
4217  }
4218 
4219  if (showNested || pattern)
4221  ",\n inh.inhparent::pg_catalog.regclass as \"%s\"",
4222  gettext_noop("Parent name"));
4223 
4224  if (showIndexes)
4226  ",\n c2.oid::pg_catalog.regclass as \"%s\"",
4227  gettext_noop("Table"));
4228 
4229  if (verbose)
4230  {
4231  if (showNested)
4232  {
4234  ",\n s.dps as \"%s\"",
4235  gettext_noop("Leaf partition size"));
4237  ",\n s.tps as \"%s\"",
4238  gettext_noop("Total size"));
4239  }
4240  else
4241  /* Sizes of all partitions are considered in this case. */
4243  ",\n s.tps as \"%s\"",
4244  gettext_noop("Total size"));
4245 
4247  ",\n pg_catalog.obj_description(c.oid, 'pg_class') as \"%s\"",
4248  gettext_noop("Description"));
4249  }
4250 
4252  "\nFROM pg_catalog.pg_class c"
4253  "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace");
4254 
4255  if (showIndexes)
4257  "\n LEFT JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid"
4258  "\n LEFT JOIN pg_catalog.pg_class c2 ON i.indrelid = c2.oid");
4259 
4260  if (showNested || pattern)
4262  "\n LEFT JOIN pg_catalog.pg_inherits inh ON c.oid = inh.inhrelid");
4263 
4264  if (verbose)
4265  {
4266  if (pset.sversion < 120000)
4267  {
4269  ",\n LATERAL (WITH RECURSIVE d\n"
4270  " AS (SELECT inhrelid AS oid, 1 AS level\n"
4271  " FROM pg_catalog.pg_inherits\n"
4272  " WHERE inhparent = c.oid\n"
4273  " UNION ALL\n"
4274  " SELECT inhrelid, level + 1\n"
4275  " FROM pg_catalog.pg_inherits i\n"
4276  " JOIN d ON i.inhparent = d.oid)\n"
4277  " SELECT pg_catalog.pg_size_pretty(sum(pg_catalog.pg_table_size("
4278  "d.oid))) AS tps,\n"
4279  " pg_catalog.pg_size_pretty(sum("
4280  "\n CASE WHEN d.level = 1"
4281  " THEN pg_catalog.pg_table_size(d.oid) ELSE 0 END)) AS dps\n"
4282  " FROM d) s");
4283  }
4284  else
4285  {
4286  /* PostgreSQL 12 has pg_partition_tree function */
4288  ",\n LATERAL (SELECT pg_catalog.pg_size_pretty(sum("
4289  "\n CASE WHEN ppt.isleaf AND ppt.level = 1"
4290  "\n THEN pg_catalog.pg_table_size(ppt.relid)"
4291  " ELSE 0 END)) AS dps"
4292  ",\n pg_catalog.pg_size_pretty(sum("
4293  "pg_catalog.pg_table_size(ppt.relid))) AS tps"
4294  "\n FROM pg_catalog.pg_partition_tree(c.oid) ppt) s");
4295  }
4296  }
4297 
4298  appendPQExpBufferStr(&buf, "\nWHERE c.relkind IN (");
4299  if (showTables)
4300  appendPQExpBufferStr(&buf, CppAsString2(RELKIND_PARTITIONED_TABLE) ",");
4301  if (showIndexes)
4302  appendPQExpBufferStr(&buf, CppAsString2(RELKIND_PARTITIONED_INDEX) ",");
4303  appendPQExpBufferStr(&buf, "''"); /* dummy */
4304  appendPQExpBufferStr(&buf, ")\n");
4305 
4306  appendPQExpBufferStr(&buf, !showNested && !pattern ?
4307  " AND NOT c.relispartition\n" : "");
4308 
4309  if (!pattern)
4310  appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
4311  " AND n.nspname !~ '^pg_toast'\n"
4312  " AND n.nspname <> 'information_schema'\n");
4313 
4314  if (!validateSQLNamePattern(&buf, pattern, true, false,
4315  "n.nspname", "c.relname", NULL,
4316  "pg_catalog.pg_table_is_visible(c.oid)",
4317  NULL, 3))
4318  {
4319  termPQExpBuffer(&buf);
4320  return false;
4321  }
4322 
4323  appendPQExpBuffer(&buf, "ORDER BY \"Schema\", %s%s\"Name\";",
4324  mixed_output ? "\"Type\" DESC, " : "",
4325  showNested || pattern ? "\"Parent name\" NULLS FIRST, " : "");
4326 
4327  res = PSQLexec(buf.data);
4328  termPQExpBuffer(&buf);
4329  if (!res)
4330  return false;
4331 
4332  initPQExpBuffer(&title);
4333  appendPQExpBufferStr(&title, tabletitle);
4334 
4335  myopt.title = title.data;
4336  myopt.translate_header = true;
4337  myopt.translate_columns = translate_columns;
4338  myopt.n_translate_columns = lengthof(translate_columns);
4339 
4340  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
4341 
4342  termPQExpBuffer(&title);
4343 
4344  PQclear(res);
4345  return true;
4346 }
4347 
4348 /*
4349  * \dL
4350  *
4351  * Describes languages.
4352  */
4353 bool
4354 listLanguages(const char *pattern, bool verbose, bool showSystem)
4355 {
4357  PGresult *res;
4358  printQueryOpt myopt = pset.popt;
4359 
4360  initPQExpBuffer(&buf);
4361 
4363  "SELECT l.lanname AS \"%s\",\n"
4364  " pg_catalog.pg_get_userbyid(l.lanowner) as \"%s\",\n"
4365  " l.lanpltrusted AS \"%s\"",
4366  gettext_noop("Name"),
4367  gettext_noop("Owner"),
4368  gettext_noop("Trusted"));
4369 
4370  if (verbose)
4371  {
4373  ",\n NOT l.lanispl AS \"%s\",\n"
4374  " l.lanplcallfoid::pg_catalog.regprocedure AS \"%s\",\n"
4375  " l.lanvalidator::pg_catalog.regprocedure AS \"%s\",\n "
4376  "l.laninline::pg_catalog.regprocedure AS \"%s\",\n ",
4377  gettext_noop("Internal language"),
4378  gettext_noop("Call handler"),
4379  gettext_noop("Validator"),
4380  gettext_noop("Inline handler"));
4381  printACLColumn(&buf, "l.lanacl");
4382  }
4383 
4385  ",\n d.description AS \"%s\""
4386  "\nFROM pg_catalog.pg_language l\n"
4387  "LEFT JOIN pg_catalog.pg_description d\n"
4388  " ON d.classoid = l.tableoid AND d.objoid = l.oid\n"
4389  " AND d.objsubid = 0\n",
4390  gettext_noop("Description"));
4391 
4392  if (pattern)
4393  {
4394  if (!validateSQLNamePattern(&buf, pattern, false, false,
4395  NULL, "l.lanname", NULL, NULL,
4396  NULL, 2))
4397  {
4398  termPQExpBuffer(&buf);
4399  return false;
4400  }
4401  }
4402 
4403  if (!showSystem && !pattern)
4404  appendPQExpBufferStr(&buf, "WHERE l.lanplcallfoid != 0\n");
4405 
4406 
4407  appendPQExpBufferStr(&buf, "ORDER BY 1;");
4408 
4409  res = PSQLexec(buf.data);
4410  termPQExpBuffer(&buf);
4411  if (!res)
4412  return false;
4413 
4414  myopt.title = _("List of languages");
4415  myopt.translate_header = true;
4416 
4417  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
4418 
4419  PQclear(res);
4420  return true;
4421 }
4422 
4423 
4424 /*
4425  * \dD
4426  *
4427  * Describes domains.
4428  */
4429 bool
4430 listDomains(const char *pattern, bool verbose, bool showSystem)
4431 {
4433  PGresult *res;
4434  printQueryOpt myopt = pset.popt;
4435 
4436  initPQExpBuffer(&buf);
4437 
4439  "SELECT n.nspname as \"%s\",\n"
4440  " t.typname as \"%s\",\n"
4441  " pg_catalog.format_type(t.typbasetype, t.typtypmod) as \"%s\",\n"
4442  " (SELECT c.collname FROM pg_catalog.pg_collation c, pg_catalog.pg_type bt\n"
4443  " WHERE c.oid = t.typcollation AND bt.oid = t.typbasetype AND t.typcollation <> bt.typcollation) as \"%s\",\n"
4444  " CASE WHEN t.typnotnull THEN 'not null' END as \"%s\",\n"
4445  " t.typdefault as \"%s\",\n"
4446  " pg_catalog.array_to_string(ARRAY(\n"
4447  " SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM pg_catalog.pg_constraint r WHERE t.oid = r.contypid\n"
4448  " ), ' ') as \"%s\"",
4449  gettext_noop("Schema"),
4450  gettext_noop("Name"),
4451  gettext_noop("Type"),
4452  gettext_noop("Collation"),
4453  gettext_noop("Nullable"),
4454  gettext_noop("Default"),
4455  gettext_noop("Check"));
4456 
4457  if (verbose)
4458  {
4459  appendPQExpBufferStr(&buf, ",\n ");
4460  printACLColumn(&buf, "t.typacl");
4462  ",\n d.description as \"%s\"",
4463  gettext_noop("Description"));
4464  }
4465 
4467  "\nFROM pg_catalog.pg_type t\n"
4468  " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n");
4469 
4470  if (verbose)
4472  " LEFT JOIN pg_catalog.pg_description d "
4473  "ON d.classoid = t.tableoid AND d.objoid = t.oid "
4474  "AND d.objsubid = 0\n");
4475 
4476  appendPQExpBufferStr(&buf, "WHERE t.typtype = 'd'\n");
4477 
4478  if (!showSystem && !pattern)
4479  appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
4480  " AND n.nspname <> 'information_schema'\n");
4481 
4482  if (!validateSQLNamePattern(&buf, pattern, true, false,
4483  "n.nspname", "t.typname", NULL,
4484  "pg_catalog.pg_type_is_visible(t.oid)",
4485  NULL, 3))
4486  {
4487  termPQExpBuffer(&buf);
4488  return false;
4489  }
4490 
4491  appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
4492 
4493  res = PSQLexec(buf.data);
4494  termPQExpBuffer(&buf);
4495  if (!res)
4496  return false;
4497 
4498  myopt.title = _("List of domains");
4499  myopt.translate_header = true;
4500 
4501  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
4502 
4503  PQclear(res);
4504  return true;
4505 }
4506 
4507 /*
4508  * \dc
4509  *
4510  * Describes conversions.
4511  */
4512 bool
4513 listConversions(const char *pattern, bool verbose, bool showSystem)
4514 {
4516  PGresult *res;
4517  printQueryOpt myopt = pset.popt;
4518  static const bool translate_columns[] =
4519  {false, false, false, false, true, false};
4520 
4521  initPQExpBuffer(&buf);
4522 
4524  "SELECT n.nspname AS \"%s\",\n"
4525  " c.conname AS \"%s\",\n"
4526  " pg_catalog.pg_encoding_to_char(c.conforencoding) AS \"%s\",\n"
4527  " pg_catalog.pg_encoding_to_char(c.contoencoding) AS \"%s\",\n"
4528  " CASE WHEN c.condefault THEN '%s'\n"
4529  " ELSE '%s' END AS \"%s\"",
4530  gettext_noop("Schema"),
4531  gettext_noop("Name"),
4532  gettext_noop("Source"),
4533  gettext_noop("Destination"),
4534  gettext_noop("yes"), gettext_noop("no"),
4535  gettext_noop("Default?"));
4536 
4537  if (verbose)
4539  ",\n d.description AS \"%s\"",
4540  gettext_noop("Description"));
4541 
4543  "\nFROM pg_catalog.pg_conversion c\n"
4544  " JOIN pg_catalog.pg_namespace n "
4545  "ON n.oid = c.connamespace\n");
4546 
4547  if (verbose)
4549  "LEFT JOIN pg_catalog.pg_description d "
4550  "ON d.classoid = c.tableoid\n"
4551  " AND d.objoid = c.oid "
4552  "AND d.objsubid = 0\n");
4553 
4554  appendPQExpBufferStr(&buf, "WHERE true\n");
4555 
4556  if (!showSystem && !pattern)
4557  appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
4558  " AND n.nspname <> 'information_schema'\n");
4559 
4560  if (!validateSQLNamePattern(&buf, pattern, true, false,
4561  "n.nspname", "c.conname", NULL,
4562  "pg_catalog.pg_conversion_is_visible(c.oid)",
4563  NULL, 3))
4564  {
4565  termPQExpBuffer(&buf);
4566  return false;
4567  }
4568 
4569  appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
4570 
4571  res = PSQLexec(buf.data);
4572  termPQExpBuffer(&buf);
4573  if (!res)
4574  return false;
4575 
4576  myopt.title = _("List of conversions");
4577  myopt.translate_header = true;
4578  myopt.translate_columns = translate_columns;
4579  myopt.n_translate_columns = lengthof(translate_columns);
4580 
4581  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
4582 
4583  PQclear(res);
4584  return true;
4585 }
4586 
4587 /*
4588  * \dconfig
4589  *
4590  * Describes configuration parameters.
4591  */
4592 bool
4593 describeConfigurationParameters(const char *pattern, bool verbose,
4594  bool showSystem)
4595 {
4597  PGresult *res;
4598  printQueryOpt myopt = pset.popt;
4599 
4600  initPQExpBuffer(&buf);
4602  "SELECT s.name AS \"%s\", "
4603  "pg_catalog.current_setting(s.name) AS \"%s\"",
4604  gettext_noop("Parameter"),
4605  gettext_noop("Value"));
4606 
4607  if (verbose)
4608  {
4610  ", s.vartype AS \"%s\", s.context AS \"%s\", ",
4611  gettext_noop("Type"),
4612  gettext_noop("Context"));
4613  if (pset.sversion >= 150000)
4614  printACLColumn(&buf, "p.paracl");
4615  else
4616  appendPQExpBuffer(&buf, "NULL AS \"%s\"",
4617  gettext_noop("Access privileges"));
4618  }
4619 
4620  appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_settings s\n");
4621 
4622  if (verbose && pset.sversion >= 150000)
4624  " LEFT JOIN pg_catalog.pg_parameter_acl p\n"
4625  " ON pg_catalog.lower(s.name) = p.parname\n");
4626 
4627  if (pattern)
4628  processSQLNamePattern(pset.db, &buf, pattern,
4629  false, false,
4630  NULL, "pg_catalog.lower(s.name)", NULL,
4631  NULL, NULL, NULL);
4632  else
4633  appendPQExpBufferStr(&buf, "WHERE s.source <> 'default' AND\n"
4634  " s.setting IS DISTINCT FROM s.boot_val\n");
4635 
4636  appendPQExpBufferStr(&buf, "ORDER BY 1;");
4637 
4638  res = PSQLexec(buf.data);
4639  termPQExpBuffer(&buf);
4640  if (!res)
4641  return false;
4642 
4643  if (pattern)
4644  myopt.title = _("List of configuration parameters");
4645  else
4646  myopt.title = _("List of non-default configuration parameters");
4647  myopt.translate_header = true;
4648 
4649  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
4650 
4651  PQclear(res);
4652  return true;
4653 }
4654 
4655 /*
4656  * \dy
4657  *
4658  * Describes Event Triggers.
4659  */
4660 bool
4661 listEventTriggers(const char *pattern, bool verbose)
4662 {
4664  PGresult *res;
4665  printQueryOpt myopt = pset.popt;
4666  static const bool translate_columns[] =
4667  {false, false, false, true, false, false, false};
4668 
4669  if (pset.sversion < 90300)
4670  {
4671  char sverbuf[32];
4672 
4673  pg_log_error("The server (version %s) does not support event triggers.",
4675  sverbuf, sizeof(sverbuf)));
4676  return true;
4677  }
4678 
4679  initPQExpBuffer(&buf);
4680 
4682  "SELECT evtname as \"%s\", "
4683  "evtevent as \"%s\", "
4684  "pg_catalog.pg_get_userbyid(e.evtowner) as \"%s\",\n"
4685  " case evtenabled when 'O' then '%s'"
4686  " when 'R' then '%s'"
4687  " when 'A' then '%s'"
4688  " when 'D' then '%s' end as \"%s\",\n"
4689  " e.evtfoid::pg_catalog.regproc as \"%s\", "
4690  "pg_catalog.array_to_string(array(select x"
4691  " from pg_catalog.unnest(evttags) as t(x)), ', ') as \"%s\"",
4692  gettext_noop("Name"),
4693  gettext_noop("Event"),
4694  gettext_noop("Owner"),
4695  gettext_noop("enabled"),
4696  gettext_noop("replica"),
4697  gettext_noop("always"),
4698  gettext_noop("disabled"),
4699  gettext_noop("Enabled"),
4700  gettext_noop("Function"),
4701  gettext_noop("Tags"));
4702  if (verbose)
4704  ",\npg_catalog.obj_description(e.oid, 'pg_event_trigger') as \"%s\"",
4705  gettext_noop("Description"));
4707  "\nFROM pg_catalog.pg_event_trigger e ");
4708 
4709  if (!validateSQLNamePattern(&buf, pattern, false, false,
4710  NULL, "evtname", NULL, NULL,
4711  NULL, 1))
4712  {
4713  termPQExpBuffer(&buf);
4714  return false;
4715  }
4716 
4717  appendPQExpBufferStr(&buf, "ORDER BY 1");
4718 
4719  res = PSQLexec(buf.data);
4720  termPQExpBuffer(&buf);
4721  if (!res)
4722  return false;
4723 
4724  myopt.title = _("List of event triggers");
4725  myopt.translate_header = true;
4726  myopt.translate_columns = translate_columns;
4727  myopt.n_translate_columns = lengthof(translate_columns);
4728 
4729  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
4730 
4731  PQclear(res);
4732  return true;
4733 }
4734 
4735 /*
4736  * \dX
4737  *
4738  * Describes extended statistics.
4739  */
4740 bool
4741 listExtendedStats(const char *pattern)
4742 {
4744  PGresult *res;
4745  printQueryOpt myopt = pset.popt;
4746 
4747  if (pset.sversion < 100000)
4748  {
4749  char sverbuf[32];
4750 
4751  pg_log_error("The server (version %s) does not support extended statistics.",
4753  sverbuf, sizeof(sverbuf)));
4754  return true;
4755  }
4756 
4757  initPQExpBuffer(&buf);
4759  "SELECT \n"
4760  "es.stxnamespace::pg_catalog.regnamespace::pg_catalog.text AS \"%s\", \n"
4761  "es.stxname AS \"%s\", \n",
4762  gettext_noop("Schema"),
4763  gettext_noop("Name"));
4764 
4765  if (pset.sversion >= 140000)
4767  "pg_catalog.format('%%s FROM %%s', \n"
4768  " pg_catalog.pg_get_statisticsobjdef_columns(es.oid), \n"
4769  " es.stxrelid::pg_catalog.regclass) AS \"%s\"",
4770  gettext_noop("Definition"));
4771  else
4773  "pg_catalog.format('%%s FROM %%s', \n"
4774  " (SELECT pg_catalog.string_agg(pg_catalog.quote_ident(a.attname),', ') \n"
4775  " FROM pg_catalog.unnest(es.stxkeys) s(attnum) \n"
4776  " JOIN pg_catalog.pg_attribute a \n"
4777  " ON (es.stxrelid = a.attrelid \n"
4778  " AND a.attnum = s.attnum \n"
4779  " AND NOT a.attisdropped)), \n"
4780  "es.stxrelid::pg_catalog.regclass) AS \"%s\"",
4781  gettext_noop("Definition"));
4782 
4784  ",\nCASE WHEN 'd' = any(es.stxkind) THEN 'defined' \n"
4785  "END AS \"%s\", \n"
4786  "CASE WHEN 'f' = any(es.stxkind) THEN 'defined' \n"
4787  "END AS \"%s\"",
4788  gettext_noop("Ndistinct"),
4789  gettext_noop("Dependencies"));
4790 
4791  /*
4792  * Include the MCV statistics kind.
4793  */
4794  if (pset.sversion >= 120000)
4795  {
4797  ",\nCASE WHEN 'm' = any(es.stxkind) THEN 'defined' \n"
4798  "END AS \"%s\" ",
4799  gettext_noop("MCV"));
4800  }
4801 
4803  " \nFROM pg_catalog.pg_statistic_ext es \n");
4804 
4805  if (!validateSQLNamePattern(&buf, pattern,
4806  false, false,
4807  "es.stxnamespace::pg_catalog.regnamespace::pg_catalog.text", "es.stxname",
4808  NULL, "pg_catalog.pg_statistics_obj_is_visible(es.oid)",
4809  NULL, 3))
4810  {
4811  termPQExpBuffer(&buf);
4812  return false;
4813  }
4814 
4815  appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
4816 
4817  res = PSQLexec(buf.data);
4818  termPQExpBuffer(&buf);
4819  if (!res)
4820  return false;
4821 
4822  myopt.title = _("List of extended statistics");
4823  myopt.translate_header = true;
4824 
4825  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
4826 
4827  PQclear(res);
4828  return true;
4829 }
4830 
4831 /*
4832  * \dC
4833  *
4834  * Describes casts.
4835  */
4836 bool
4837 listCasts(const char *pattern, bool verbose)
4838 {
4840  PGresult *res;
4841  printQueryOpt myopt = pset.popt;
4842  static const bool translate_columns[] = {false, false, false, true, false};
4843 
4844  initPQExpBuffer(&buf);
4845 
4847  "SELECT pg_catalog.format_type(castsource, NULL) AS \"%s\",\n"
4848  " pg_catalog.format_type(casttarget, NULL) AS \"%s\",\n",
4849  gettext_noop("Source type"),
4850  gettext_noop("Target type"));
4851 
4852  /*
4853  * We don't attempt to localize '(binary coercible)' or '(with inout)',
4854  * because there's too much risk of gettext translating a function name
4855  * that happens to match some string in the PO database.
4856  */
4858  " CASE WHEN c.castmethod = '%c' THEN '(binary coercible)'\n"
4859  " WHEN c.castmethod = '%c' THEN '(with inout)'\n"
4860  " ELSE p.proname\n"
4861  " END AS \"%s\",\n",
4862  COERCION_METHOD_BINARY,
4863  COERCION_METHOD_INOUT,
4864  gettext_noop("Function"));
4865 
4867  " CASE WHEN c.castcontext = '%c' THEN '%s'\n"
4868  " WHEN c.castcontext = '%c' THEN '%s'\n"
4869  " ELSE '%s'\n"
4870  " END AS \"%s\"",
4871  COERCION_CODE_EXPLICIT,
4872  gettext_noop("no"),
4873  COERCION_CODE_ASSIGNMENT,
4874  gettext_noop("in assignment"),
4875  gettext_noop("yes"),
4876  gettext_noop("Implicit?"));
4877 
4878  if (verbose)
4880  ",\n d.description AS \"%s\"",
4881  gettext_noop("Description"));
4882 
4883  /*
4884  * We need a left join to pg_proc for binary casts; the others are just
4885  * paranoia.
4886  */
4888  "\nFROM pg_catalog.pg_cast c LEFT JOIN pg_catalog.pg_proc p\n"
4889  " ON c.castfunc = p.oid\n"
4890  " LEFT JOIN pg_catalog.pg_type ts\n"
4891  " ON c.castsource = ts.oid\n"
4892  " LEFT JOIN pg_catalog.pg_namespace ns\n"
4893  " ON ns.oid = ts.typnamespace\n"
4894  " LEFT JOIN pg_catalog.pg_type tt\n"
4895  " ON c.casttarget = tt.oid\n"
4896  " LEFT JOIN pg_catalog.pg_namespace nt\n"
4897  " ON nt.oid = tt.typnamespace\n");
4898 
4899  if (verbose)
4901  " LEFT JOIN pg_catalog.pg_description d\n"
4902  " ON d.classoid = c.tableoid AND d.objoid = "
4903  "c.oid AND d.objsubid = 0\n");
4904 
4905  appendPQExpBufferStr(&buf, "WHERE ( (true");
4906 
4907  /*
4908  * Match name pattern against either internal or external name of either
4909  * castsource or casttarget
4910  */
4911  if (!validateSQLNamePattern(&buf, pattern, true, false,
4912  "ns.nspname", "ts.typname",
4913  "pg_catalog.format_type(ts.oid, NULL)",
4914  "pg_catalog.pg_type_is_visible(ts.oid)",
4915  NULL, 3))
4916  goto error_return;
4917 
4918  appendPQExpBufferStr(&buf, ") OR (true");
4919 
4920  if (!validateSQLNamePattern(&buf, pattern, true, false,
4921  "nt.nspname", "tt.typname",
4922  "pg_catalog.format_type(tt.oid, NULL)",
4923  "pg_catalog.pg_type_is_visible(tt.oid)",
4924  NULL, 3))
4925  goto error_return;
4926 
4927  appendPQExpBufferStr(&buf, ") )\nORDER BY 1, 2;");
4928 
4929  res = PSQLexec(buf.data);
4930  termPQExpBuffer(&buf);
4931  if (!res)
4932  return false;
4933 
4934  myopt.title = _("List of casts");
4935  myopt.translate_header = true;
4936  myopt.translate_columns = translate_columns;
4937  myopt.n_translate_columns = lengthof(translate_columns);
4938 
4939  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
4940 
4941  PQclear(res);
4942  return true;
4943 
4944 error_return:
4945  termPQExpBuffer(&buf);
4946  return false;
4947 }
4948 
4949 /*
4950  * \dO
4951  *
4952  * Describes collations.
4953  */
4954 bool
4955 listCollations(const char *pattern, bool verbose, bool showSystem)
4956 {
4958  PGresult *res;
4959  printQueryOpt myopt = pset.popt;
4960  static const bool translate_columns[] = {false, false, false, false, false, false, false, true, false};
4961 
4962  initPQExpBuffer(&buf);
4963 
4965  "SELECT\n"
4966  " n.nspname AS \"%s\",\n"
4967  " c.collname AS \"%s\",\n",
4968  gettext_noop("Schema"),
4969  gettext_noop("Name"));
4970 
4971  if (pset.sversion >= 100000)
4973  " CASE c.collprovider WHEN 'd' THEN 'default' WHEN 'c' THEN 'libc' WHEN 'i' THEN 'icu' END AS \"%s\",\n",
4974  gettext_noop("Provider"));
4975  else
4977  " 'libc' AS \"%s\",\n",
4978  gettext_noop("Provider"));
4979 
4981  " c.collcollate AS \"%s\",\n"
4982  " c.collctype AS \"%s\",\n",
4983  gettext_noop("Collate"),
4984  gettext_noop("Ctype"));
4985 
4986  if (pset.sversion >= 150000)
4988  " c.colliculocale AS \"%s\",\n",
4989  gettext_noop("ICU Locale"));
4990  else
4992  " c.collcollate AS \"%s\",\n",
4993  gettext_noop("ICU Locale"));
4994 
4995  if (pset.sversion >= 160000)
4997  " c.collicurules AS \"%s\",\n",
4998  gettext_noop("ICU Rules"));
4999  else
5001  " NULL AS \"%s\",\n",
5002  gettext_noop("ICU Rules"));
5003 
5004  if (pset.sversion >= 120000)
5006  " CASE WHEN c.collisdeterministic THEN '%s' ELSE '%s' END AS \"%s\"",
5007  gettext_noop("yes"), gettext_noop("no"),
5008  gettext_noop("Deterministic?"));
5009  else
5011  " '%s' AS \"%s\"",
5012  gettext_noop("yes"),
5013  gettext_noop("Deterministic?"));
5014 
5015  if (verbose)
5017  ",\n pg_catalog.obj_description(c.oid, 'pg_collation') AS \"%s\"",
5018  gettext_noop("Description"));
5019 
5021  "\nFROM pg_catalog.pg_collation c, pg_catalog.pg_namespace n\n"
5022  "WHERE n.oid = c.collnamespace\n");
5023 
5024  if (!showSystem && !pattern)
5025  appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n"
5026  " AND n.nspname <> 'information_schema'\n");
5027 
5028  /*
5029  * Hide collations that aren't usable in the current database's encoding.
5030  * If you think to change this, note that pg_collation_is_visible rejects
5031  * unusable collations, so you will need to hack name pattern processing
5032  * somehow to avoid inconsistent behavior.
5033  */
5034  appendPQExpBufferStr(&buf, " AND c.collencoding IN (-1, pg_catalog.pg_char_to_encoding(pg_catalog.getdatabaseencoding()))\n");
5035 
5036  if (!validateSQLNamePattern(&buf, pattern, true, false,
5037  "n.nspname", "c.collname", NULL,
5038  "pg_catalog.pg_collation_is_visible(c.oid)",
5039  NULL, 3))
5040  {
5041  termPQExpBuffer(&buf);
5042  return false;
5043  }
5044 
5045  appendPQExpBufferStr(&buf, "ORDER BY 1, 2;");
5046 
5047  res = PSQLexec(buf.data);
5048  termPQExpBuffer(&buf);
5049  if (!res)
5050  return false;
5051 
5052  myopt.title = _("List of collations");
5053  myopt.translate_header = true;
5054  myopt.translate_columns = translate_columns;
5055  myopt.n_translate_columns = lengthof(translate_columns);
5056 
5057  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
5058 
5059  PQclear(res);
5060  return true;
5061 }
5062 
5063 /*
5064  * \dn
5065  *
5066  * Describes schemas (namespaces)
5067  */
5068 bool
5069 listSchemas(const char *pattern, bool verbose, bool showSystem)
5070 {
5072  PGresult *res;
5073  printQueryOpt myopt = pset.popt;
5074  int pub_schema_tuples = 0;
5075  char **footers = NULL;
5076 
5077  initPQExpBuffer(&buf);
5079  "SELECT n.nspname AS \"%s\",\n"
5080  " pg_catalog.pg_get_userbyid(n.nspowner) AS \"%s\"",
5081  gettext_noop("Name"),
5082  gettext_noop("Owner"));
5083 
5084  if (verbose)
5085  {
5086  appendPQExpBufferStr(&buf, ",\n ");
5087  printACLColumn(&buf, "n.nspacl");
5089  ",\n pg_catalog.obj_description(n.oid, 'pg_namespace') AS \"%s\"",
5090  gettext_noop("Description"));
5091  }
5092 
5094  "\nFROM pg_catalog.pg_namespace n\n");
5095 
5096  if (!showSystem && !pattern)
5098  "WHERE n.nspname !~ '^pg_' AND n.nspname <> 'information_schema'\n");
5099 
5100  if (!validateSQLNamePattern(&buf, pattern,
5101  !showSystem && !pattern, false,
5102  NULL, "n.nspname", NULL,
5103  NULL,
5104  NULL, 2))
5105  goto error_return;
5106 
5107  appendPQExpBufferStr(&buf, "ORDER BY 1;");
5108 
5109  res = PSQLexec(buf.data);
5110  if (!res)
5111  goto error_return;
5112 
5113  myopt.title = _("List of schemas");
5114  myopt.translate_header = true;
5115 
5116  if (pattern && pset.sversion >= 150000)
5117  {
5118  PGresult *result;
5119  int i;
5120 
5122  "SELECT pubname \n"
5123  "FROM pg_catalog.pg_publication p\n"
5124  " JOIN pg_catalog.pg_publication_namespace pn ON p.oid = pn.pnpubid\n"
5125  " JOIN pg_catalog.pg_namespace n ON n.oid = pn.pnnspid \n"
5126  "WHERE n.nspname = '%s'\n"
5127  "ORDER BY 1",
5128  pattern);
5129  result = PSQLexec(buf.data);
5130  if (!result)
5131  goto error_return;
5132  else
5133  pub_schema_tuples = PQntuples(result);
5134 
5135  if (pub_schema_tuples > 0)
5136  {
5137  /*
5138  * Allocate memory for footers. Size of footers will be 1 (for
5139  * storing "Publications:" string) + publication schema mapping
5140  * count + 1 (for storing NULL).
5141  */
5142  footers = (char **) pg_malloc((1 + pub_schema_tuples + 1) * sizeof(char *));
5143  footers[0] = pg_strdup(_("Publications:"));
5144 
5145  /* Might be an empty set - that's ok */
5146  for (i = 0; i < pub_schema_tuples; i++)
5147  {
5148  printfPQExpBuffer(&buf, " \"%s\"",
5149  PQgetvalue(result, i, 0));
5150 
5151  footers[i + 1] = pg_strdup(buf.data);
5152  }
5153 
5154  footers[i + 1] = NULL;
5155  myopt.footers = footers;
5156  }
5157 
5158  PQclear(result);
5159  }
5160 
5161  printQuery(res, &myopt, pset.queryFout, false, pset.logfile);
5162