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