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