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