]> granicus.if.org Git - postgresql/blob - src/bin/psql/describe.c
0391b8f4cae4a4f094b003f69cbd0bc2329785c3
[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-2009, PostgreSQL Global Development Group
10  *
11  * $PostgreSQL: pgsql/src/bin/psql/describe.c,v 1.212 2009/05/05 02:29:06 tgl Exp $
12  */
13 #include "postgres_fe.h"
14
15 #include <ctype.h>
16
17 #include "common.h"
18 #include "describe.h"
19 #include "dumputils.h"
20 #include "mbprint.h"
21 #include "print.h"
22 #include "settings.h"
23 #include "variables.h"
24
25
26 static bool describeOneTableDetails(const char *schemaname,
27                                                 const char *relationname,
28                                                 const char *oid,
29                                                 bool verbose);
30 static void add_tablespace_footer(printTableContent *const cont, char relkind,
31                                                 Oid tablespace, const bool newline);
32 static void add_role_attribute(PQExpBuffer buf, const char *const str);
33 static bool listTSParsersVerbose(const char *pattern);
34 static bool describeOneTSParser(const char *oid, const char *nspname,
35                                         const char *prsname);
36 static bool listTSConfigsVerbose(const char *pattern);
37 static bool describeOneTSConfig(const char *oid, const char *nspname,
38                                         const char *cfgname,
39                                         const char *pnspname, const char *prsname);
40 static void printACLColumn(PQExpBuffer buf, const char *colname);
41
42
43 /*----------------
44  * Handlers for various slash commands displaying some sort of list
45  * of things in the database.
46  *
47  * Note: try to format the queries to look nice in -E output.
48  *----------------
49  */
50
51
52 /* \da
53  * Takes an optional regexp to select particular aggregates
54  */
55 bool
56 describeAggregates(const char *pattern, bool verbose, bool showSystem)
57 {
58         PQExpBufferData buf;
59         PGresult   *res;
60         printQueryOpt myopt = pset.popt;
61
62         initPQExpBuffer(&buf);
63
64         printfPQExpBuffer(&buf,
65                                           "SELECT n.nspname as \"%s\",\n"
66                                           "  p.proname AS \"%s\",\n"
67                                           "  pg_catalog.format_type(p.prorettype, NULL) AS \"%s\",\n",
68                                           gettext_noop("Schema"),
69                                           gettext_noop("Name"),
70                                           gettext_noop("Result data type"));
71
72         if (pset.sversion >= 80200)
73             appendPQExpBuffer(&buf,
74                                           "  CASE WHEN p.pronargs = 0\n"
75                                           "    THEN CAST('*' AS pg_catalog.text)\n"
76                                           "    ELSE\n"
77                                           "    pg_catalog.array_to_string(ARRAY(\n"
78                                           "      SELECT\n"
79                                           "        pg_catalog.format_type(p.proargtypes[s.i], NULL)\n"
80                                           "      FROM\n"
81                                           "        pg_catalog.generate_series(0, pg_catalog.array_upper(p.proargtypes, 1)) AS s(i)\n"
82                                           "    ), ', ')\n"
83                                           "  END AS \"%s\",\n",
84                                           gettext_noop("Argument data types"));
85         else
86             appendPQExpBuffer(&buf,
87                                           "  pg_catalog.format_type(p.proargtypes[0], NULL) AS \"%s\",\n",
88                                           gettext_noop("Argument data types"));
89
90         appendPQExpBuffer(&buf,
91                                  "  pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"\n"
92                                           "FROM pg_catalog.pg_proc p\n"
93            "     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n"
94                                           "WHERE p.proisagg\n",
95                                           gettext_noop("Description"));
96
97         if (!showSystem && !pattern)
98                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
99                                                                 "      AND n.nspname <> 'information_schema'\n");
100
101         processSQLNamePattern(pset.db, &buf, pattern, true, false,
102                                                   "n.nspname", "p.proname", NULL,
103                                                   "pg_catalog.pg_function_is_visible(p.oid)");
104
105         appendPQExpBuffer(&buf, "ORDER BY 1, 2, 4;");
106
107         res = PSQLexec(buf.data, false);
108         termPQExpBuffer(&buf);
109         if (!res)
110                 return false;
111
112         myopt.nullPrint = NULL;
113         myopt.title = _("List of aggregate functions");
114         myopt.translate_header = true;
115
116         printQuery(res, &myopt, pset.queryFout, pset.logfile);
117
118         PQclear(res);
119         return true;
120 }
121
122 /* \db
123  * Takes an optional regexp to select particular tablespaces
124  */
125 bool
126 describeTablespaces(const char *pattern, bool verbose)
127 {
128         PQExpBufferData buf;
129         PGresult   *res;
130         printQueryOpt myopt = pset.popt;
131
132         if (pset.sversion < 80000)
133         {
134                 fprintf(stderr, _("The server (version %d.%d) does not support tablespaces.\n"),
135                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
136                 return true;
137         }
138
139         initPQExpBuffer(&buf);
140
141         printfPQExpBuffer(&buf,
142                                           "SELECT spcname AS \"%s\",\n"
143                                           "  pg_catalog.pg_get_userbyid(spcowner) AS \"%s\",\n"
144                                           "  spclocation AS \"%s\"",
145                                           gettext_noop("Name"),
146                                           gettext_noop("Owner"),
147                                           gettext_noop("Location"));
148
149         if (verbose)
150         {
151                 appendPQExpBuffer(&buf, ",\n  ");
152                 printACLColumn(&buf, "spcacl");
153         }
154
155         if (verbose && pset.sversion >= 80200)
156                 appendPQExpBuffer(&buf,
157                           ",\n  pg_catalog.shobj_description(oid, 'pg_tablespace') AS \"%s\"",
158                                                   gettext_noop("Description"));
159
160         appendPQExpBuffer(&buf,
161                                           "\nFROM pg_catalog.pg_tablespace\n");
162
163         processSQLNamePattern(pset.db, &buf, pattern, false, false,
164                                                   NULL, "spcname", NULL,
165                                                   NULL);
166
167         appendPQExpBuffer(&buf, "ORDER BY 1;");
168
169         res = PSQLexec(buf.data, false);
170         termPQExpBuffer(&buf);
171         if (!res)
172                 return false;
173
174         myopt.nullPrint = NULL;
175         myopt.title = _("List of tablespaces");
176         myopt.translate_header = true;
177
178         printQuery(res, &myopt, pset.queryFout, pset.logfile);
179
180         PQclear(res);
181         return true;
182 }
183
184
185 /* \df
186  * Takes an optional regexp to select particular functions.
187  *
188  * As with \d, you can specify the kinds of functions you want:
189  *
190  * a for aggregates
191  * n for normal
192  * t for trigger
193  * w for window
194  *
195  * and you can mix and match these in any order.
196  */
197 bool
198 describeFunctions(const char *functypes, const char *pattern, bool verbose, bool showSystem)
199 {
200         bool            showAggregate = strchr(functypes, 'a') != NULL;
201         bool            showNormal = strchr(functypes, 'n') != NULL;
202         bool            showTrigger = strchr(functypes, 't') != NULL;
203         bool            showWindow = strchr(functypes, 'w') != NULL;
204         bool            have_where;
205         PQExpBufferData buf;
206         PGresult   *res;
207         printQueryOpt myopt = pset.popt;
208         static const bool translate_columns[] = {false, false, false, false, true, true, false, false, false, false};
209
210         if (strlen(functypes) != strspn(functypes, "antwS+"))
211         {
212                 fprintf(stderr, _("\\df only takes [antwS+] as options\n"));
213                 return true;
214         }
215
216         if (showWindow && pset.sversion < 80400)
217         {
218                 fprintf(stderr, _("\\df does not take a \"w\" option in %d.%d.\n"),
219                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
220                 return true;
221         }
222
223         if (!showAggregate && !showNormal && !showTrigger && !showWindow)
224         {
225                 showAggregate = showNormal = showTrigger = true;
226                 if (pset.sversion >= 80400)
227                         showWindow = true;
228         }
229
230         initPQExpBuffer(&buf);
231
232         printfPQExpBuffer(&buf,
233                                           "SELECT n.nspname as \"%s\",\n"
234                                           "  p.proname as \"%s\",\n",
235                                           gettext_noop("Schema"),
236                                           gettext_noop("Name"));
237
238     if (pset.sversion >= 80400)
239                 appendPQExpBuffer(&buf,
240                                                   "  pg_catalog.pg_get_function_result(p.oid) as \"%s\",\n"
241                                                   "  pg_catalog.pg_get_function_arguments(p.oid) as \"%s\",\n"
242                                                   " CASE\n"
243                                                   "  WHEN p.proisagg THEN '%s'\n"
244                                                   "  WHEN p.proiswindow THEN '%s'\n"
245                                                   "  WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN '%s'\n"
246                                                   "  ELSE '%s'\n"
247                                                   "END as \"%s\"",
248                                                   gettext_noop("Result data type"),
249                                                           gettext_noop("Argument data types"),
250                                                           /* translator: "agg" is short for "aggregate" */
251                                                           gettext_noop("agg"),
252                                                           gettext_noop("window"),
253                                                           gettext_noop("trigger"),
254                                                           gettext_noop("normal"),
255                                                           gettext_noop("Type"));
256     else if (pset.sversion >= 80100)
257                 appendPQExpBuffer(&buf,
258                                           "  CASE WHEN p.proretset THEN 'SETOF ' ELSE '' END ||\n"
259                                   "  pg_catalog.format_type(p.prorettype, NULL) as \"%s\",\n"
260                                           "  CASE WHEN proallargtypes IS NOT NULL THEN\n"
261                                           "    pg_catalog.array_to_string(ARRAY(\n"
262                                           "      SELECT\n"
263                                           "        CASE\n"
264                                           "          WHEN p.proargmodes[s.i] = 'i' THEN ''\n"
265                                           "          WHEN p.proargmodes[s.i] = 'o' THEN 'OUT '\n"
266                                           "          WHEN p.proargmodes[s.i] = 'b' THEN 'INOUT '\n"
267                                           "          WHEN p.proargmodes[s.i] = 'v' THEN 'VARIADIC '\n"
268                                           "        END ||\n"
269                                           "        CASE\n"
270                          "          WHEN COALESCE(p.proargnames[s.i], '') = '' THEN ''\n"
271                                           "          ELSE p.proargnames[s.i] || ' ' \n"
272                                           "        END ||\n"
273                           "        pg_catalog.format_type(p.proallargtypes[s.i], NULL)\n"
274                                           "      FROM\n"
275                                           "        pg_catalog.generate_series(1, pg_catalog.array_upper(p.proallargtypes, 1)) AS s(i)\n"
276                                           "    ), ', ')\n"
277                                           "  ELSE\n"
278                                           "    pg_catalog.array_to_string(ARRAY(\n"
279                                           "      SELECT\n"
280                                           "        CASE\n"
281                    "          WHEN COALESCE(p.proargnames[s.i+1], '') = '' THEN ''\n"
282                                           "          ELSE p.proargnames[s.i+1] || ' '\n"
283                                           "          END ||\n"
284                                  "        pg_catalog.format_type(p.proargtypes[s.i], NULL)\n"
285                                           "      FROM\n"
286                                           "        pg_catalog.generate_series(0, pg_catalog.array_upper(p.proargtypes, 1)) AS s(i)\n"
287                                           "    ), ', ')\n"
288                                           "  END AS \"%s\",\n"
289                                           "  CASE\n"
290                                           "    WHEN p.proisagg THEN '%s'\n"
291                                           "    WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN '%s'\n"
292                                           "    ELSE '%s'\n"
293                                           "  END AS \"%s\"",
294                                                   gettext_noop("Result data type"),
295                                                   gettext_noop("Argument data types"),
296                                                   /* translator: "agg" is short for "aggregate" */
297                                                   gettext_noop("agg"),
298                                                   gettext_noop("trigger"),
299                                                   gettext_noop("normal"),
300                                                   gettext_noop("Type"));
301         else
302                 appendPQExpBuffer(&buf,
303                                           "  CASE WHEN p.proretset THEN 'SETOF ' ELSE '' END ||\n"
304                                   "  pg_catalog.format_type(p.prorettype, NULL) as \"%s\",\n"
305                                           "  pg_catalog.oidvectortypes(p.proargtypes) as \"%s\",\n"
306                                           "  CASE\n"
307                                           "    WHEN p.proisagg THEN '%s'\n"
308                                           "    WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN '%s'\n"
309                                           "    ELSE '%s'\n"
310                                           "  END AS \"%s\"",
311                                                   gettext_noop("Result data type"),
312                                                   gettext_noop("Argument data types"),
313                                                   /* translator: "agg" is short for "aggregate" */
314                                                   gettext_noop("agg"),
315                                                   gettext_noop("trigger"),
316                                                   gettext_noop("normal"),
317                                                   gettext_noop("Type"));
318
319         if (verbose)
320                 appendPQExpBuffer(&buf,
321                                                   ",\n CASE\n"
322                                                   "  WHEN p.provolatile = 'i' THEN '%s'\n"
323                                                   "  WHEN p.provolatile = 's' THEN '%s'\n"
324                                                   "  WHEN p.provolatile = 'v' THEN '%s'\n"
325                                                   "END as \"%s\""
326                                                   ",\n  pg_catalog.pg_get_userbyid(p.proowner) as \"%s\",\n"
327                                                   "  l.lanname as \"%s\",\n"
328                                                   "  p.prosrc as \"%s\",\n"
329                                   "  pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"",
330                                                   gettext_noop("immutable"),
331                                                   gettext_noop("stable"),
332                                                   gettext_noop("volatile"),
333                                                   gettext_noop("Volatility"),
334                                                   gettext_noop("Owner"),
335                                                   gettext_noop("Language"),
336                                                   gettext_noop("Source code"),
337                                                   gettext_noop("Description"));
338
339         appendPQExpBuffer(&buf,
340                                           "\nFROM pg_catalog.pg_proc p"
341                                           "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n");
342
343         if (verbose)
344                 appendPQExpBuffer(&buf,
345                                                   "     LEFT JOIN pg_catalog.pg_language l ON l.oid = p.prolang\n");
346
347         have_where = false;
348
349         /* filter by function type, if requested */
350         if (showNormal && showAggregate && showTrigger && showWindow)
351                 /* Do nothing */;
352         else if (showNormal)
353         {
354                 if (!showAggregate)
355                 {
356                         if (have_where)
357                                 appendPQExpBuffer(&buf, "      AND ");
358                         else
359                         {
360                                 appendPQExpBuffer(&buf, "WHERE ");
361                                 have_where = true;
362                         }
363                         appendPQExpBuffer(&buf, "NOT p.proisagg\n");
364                 }
365                 if (!showTrigger)
366                 {
367                         if (have_where)
368                                 appendPQExpBuffer(&buf, "      AND ");
369                         else
370                         {
371                                 appendPQExpBuffer(&buf, "WHERE ");
372                                 have_where = true;
373                         }
374                         appendPQExpBuffer(&buf, "p.prorettype <> 'pg_catalog.trigger'::pg_catalog.regtype\n");
375                 }
376                 if (!showWindow && pset.sversion >= 80400)
377                 {
378                         if (have_where)
379                                 appendPQExpBuffer(&buf, "      AND ");
380                         else
381                         {
382                                 appendPQExpBuffer(&buf, "WHERE ");
383                                 have_where = true;
384                         }
385                         appendPQExpBuffer(&buf, "NOT p.proiswindow\n");
386                 }
387         }
388         else
389         {
390                 bool    needs_or = false;
391
392                 appendPQExpBuffer(&buf, "WHERE (\n       ");
393                 have_where = true;
394                 /* Note: at least one of these must be true ... */
395                 if (showAggregate)
396                 {
397                         appendPQExpBuffer(&buf,"p.proisagg\n");
398                         needs_or = true;
399                 }
400                 if (showTrigger)
401                 {
402                         if (needs_or)
403                                 appendPQExpBuffer(&buf, "       OR ");
404                         appendPQExpBuffer(&buf,
405                                                           "p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype\n");
406                         needs_or = true;
407                 }
408                 if (showWindow)
409                 {
410                         if (needs_or)
411                                 appendPQExpBuffer(&buf, "       OR ");
412                         appendPQExpBuffer(&buf, "p.proiswindow\n");
413                         needs_or = true;
414                 }
415                 appendPQExpBuffer(&buf, "      )\n");
416         }
417
418         processSQLNamePattern(pset.db, &buf, pattern, have_where, true,
419                                                   "n.nspname", "p.proname", NULL,
420                                                   "pg_catalog.pg_function_is_visible(p.oid)");
421
422         if (!showSystem && !pattern)
423                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
424                                                                 "      AND n.nspname <> 'information_schema'\n");
425
426         appendPQExpBuffer(&buf, "ORDER BY 1, 2, 4;");
427
428         res = PSQLexec(buf.data, false);
429         termPQExpBuffer(&buf);
430         if (!res)
431                 return false;
432
433         myopt.nullPrint = NULL;
434         myopt.title = _("List of functions");
435         myopt.translate_header = true;
436         myopt.translate_columns = translate_columns;
437
438         printQuery(res, &myopt, pset.queryFout, pset.logfile);
439
440         PQclear(res);
441         return true;
442 }
443
444
445
446 /*
447  * \dT
448  * describe types
449  */
450 bool
451 describeTypes(const char *pattern, bool verbose, bool showSystem)
452 {
453         PQExpBufferData buf;
454         PGresult   *res;
455         printQueryOpt myopt = pset.popt;
456
457         initPQExpBuffer(&buf);
458
459         printfPQExpBuffer(&buf,
460                                           "SELECT n.nspname as \"%s\",\n"
461                                           "  pg_catalog.format_type(t.oid, NULL) AS \"%s\",\n",
462                                           gettext_noop("Schema"),
463                                           gettext_noop("Name"));
464         if (verbose)
465                 appendPQExpBuffer(&buf,
466                                                   "  t.typname AS \"%s\",\n"
467                                                   "  CASE WHEN t.typrelid != 0\n"
468                                                   "      THEN CAST('tuple' AS pg_catalog.text)\n"
469                                                   "    WHEN t.typlen < 0\n"
470                                                   "      THEN CAST('var' AS pg_catalog.text)\n"
471                                                   "    ELSE CAST(t.typlen AS pg_catalog.text)\n"
472                                                   "  END AS \"%s\",\n",
473                                                   gettext_noop("Internal name"),
474                                                   gettext_noop("Size"));
475         if (verbose && pset.sversion >= 80300)
476                 appendPQExpBuffer(&buf,
477                                                   "  pg_catalog.array_to_string(\n"
478                                                   "      ARRAY(\n"
479                                                   "                  SELECT e.enumlabel\n"
480                                                   "          FROM pg_catalog.pg_enum e\n"
481                                                   "          WHERE e.enumtypid = t.oid\n"
482                                                   "          ORDER BY e.oid\n"
483                                                   "      ),\n"
484                                                   "      E'\\n'\n"
485                                                   "  ) AS \"%s\",\n",
486                                                   gettext_noop("Elements"));
487
488         appendPQExpBuffer(&buf,
489                                           "  pg_catalog.obj_description(t.oid, 'pg_type') as \"%s\"\n",
490                                           gettext_noop("Description"));
491
492         appendPQExpBuffer(&buf, "FROM pg_catalog.pg_type t\n"
493          "     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n");
494
495         /*
496          * do not include complex types (typrelid!=0) unless they are standalone
497          * composite types
498          */
499         appendPQExpBuffer(&buf, "WHERE (t.typrelid = 0 ");
500         appendPQExpBuffer(&buf, "OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c "
501                                           "WHERE c.oid = t.typrelid))\n");
502         /*
503          * do not include array types (before 8.3 we have to use the assumption
504          * that their names start with underscore)
505          */
506         if (pset.sversion >= 80300)
507                 appendPQExpBuffer(&buf, "  AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid)\n");
508         else
509                 appendPQExpBuffer(&buf, "  AND t.typname !~ '^_'\n");
510
511         if (!showSystem && !pattern)
512                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
513                                                                 "      AND n.nspname <> 'information_schema'\n");
514
515         /* Match name pattern against either internal or external name */
516         processSQLNamePattern(pset.db, &buf, pattern, true, false,
517                                                   "n.nspname", "t.typname",
518                                                   "pg_catalog.format_type(t.oid, NULL)",
519                                                   "pg_catalog.pg_type_is_visible(t.oid)");
520
521         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
522
523         res = PSQLexec(buf.data, false);
524         termPQExpBuffer(&buf);
525         if (!res)
526                 return false;
527
528         myopt.nullPrint = NULL;
529         myopt.title = _("List of data types");
530         myopt.translate_header = true;
531
532         printQuery(res, &myopt, pset.queryFout, pset.logfile);
533
534         PQclear(res);
535         return true;
536 }
537
538
539 /* \do
540  */
541 bool
542 describeOperators(const char *pattern, bool showSystem)
543 {
544         PQExpBufferData buf;
545         PGresult   *res;
546         printQueryOpt myopt = pset.popt;
547
548         initPQExpBuffer(&buf);
549
550         printfPQExpBuffer(&buf,
551                                           "SELECT n.nspname as \"%s\",\n"
552                                           "  o.oprname AS \"%s\",\n"
553                                           "  CASE WHEN o.oprkind='l' THEN NULL ELSE pg_catalog.format_type(o.oprleft, NULL) END AS \"%s\",\n"
554                                           "  CASE WHEN o.oprkind='r' THEN NULL ELSE pg_catalog.format_type(o.oprright, NULL) END AS \"%s\",\n"
555                                    "  pg_catalog.format_type(o.oprresult, NULL) AS \"%s\",\n"
556                          "  coalesce(pg_catalog.obj_description(o.oid, 'pg_operator'),\n"
557         "           pg_catalog.obj_description(o.oprcode, 'pg_proc')) AS \"%s\"\n"
558                                           "FROM pg_catalog.pg_operator o\n"
559           "     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = o.oprnamespace\n",
560                                           gettext_noop("Schema"),
561                                           gettext_noop("Name"),
562                                           gettext_noop("Left arg type"),
563                                           gettext_noop("Right arg type"),
564                                           gettext_noop("Result type"),
565                                           gettext_noop("Description"));
566
567         if (!showSystem && !pattern)
568                 appendPQExpBuffer(&buf, "WHERE n.nspname <> 'pg_catalog'\n"
569                                                                 "      AND n.nspname <> 'information_schema'\n");
570
571         processSQLNamePattern(pset.db, &buf, pattern, !showSystem && !pattern, true,
572                                                   "n.nspname", "o.oprname", NULL,
573                                                   "pg_catalog.pg_operator_is_visible(o.oid)");
574
575         appendPQExpBuffer(&buf, "ORDER BY 1, 2, 3, 4;");
576
577         res = PSQLexec(buf.data, false);
578         termPQExpBuffer(&buf);
579         if (!res)
580                 return false;
581
582         myopt.nullPrint = NULL;
583         myopt.title = _("List of operators");
584         myopt.translate_header = true;
585
586         printQuery(res, &myopt, pset.queryFout, pset.logfile);
587
588         PQclear(res);
589         return true;
590 }
591
592
593 /*
594  * listAllDbs
595  *
596  * for \l, \list, and -l switch
597  */
598 bool
599 listAllDbs(bool verbose)
600 {
601         PGresult   *res;
602         PQExpBufferData buf;
603         printQueryOpt myopt = pset.popt;
604
605         initPQExpBuffer(&buf);
606
607         printfPQExpBuffer(&buf,
608                                           "SELECT d.datname as \"%s\",\n"
609                                           "       pg_catalog.pg_get_userbyid(d.datdba) as \"%s\",\n"
610                                           "       pg_catalog.pg_encoding_to_char(d.encoding) as \"%s\",\n",
611                                           gettext_noop("Name"),
612                                           gettext_noop("Owner"),
613                                           gettext_noop("Encoding"));
614         if (pset.sversion >= 80400)
615                 appendPQExpBuffer(&buf,
616                                                   "       d.datcollate as \"%s\",\n"
617                                                   "       d.datctype as \"%s\",\n",
618                                                   gettext_noop("Collation"),
619                                                   gettext_noop("Ctype"));
620         appendPQExpBuffer(&buf, "       ");
621         printACLColumn(&buf, "d.datacl");
622         if (verbose && pset.sversion >= 80200)
623                 appendPQExpBuffer(&buf,
624                                                   ",\n       CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')\n"
625                                                   "            THEN pg_catalog.pg_size_pretty(pg_catalog.pg_database_size(d.datname))\n"
626                                                   "            ELSE 'No Access'\n"
627                                                   "       END as \"%s\"",
628                                                   gettext_noop("Size"));
629         if (verbose && pset.sversion >= 80000)
630                 appendPQExpBuffer(&buf,
631                                                   ",\n       t.spcname as \"%s\"",
632                                                   gettext_noop("Tablespace"));
633         if (verbose && pset.sversion >= 80200)
634                     appendPQExpBuffer(&buf,
635                                                   ",\n       pg_catalog.shobj_description(d.oid, 'pg_database') as \"%s\"",
636                                                   gettext_noop("Description"));
637         appendPQExpBuffer(&buf,
638                                           "\nFROM pg_catalog.pg_database d\n");
639         if (verbose && pset.sversion >= 80000)
640                 appendPQExpBuffer(&buf,
641                    "  JOIN pg_catalog.pg_tablespace t on d.dattablespace = t.oid\n");
642         appendPQExpBuffer(&buf, "ORDER BY 1;");
643         res = PSQLexec(buf.data, false);
644         termPQExpBuffer(&buf);
645         if (!res)
646                 return false;
647
648         myopt.nullPrint = NULL;
649         myopt.title = _("List of databases");
650         myopt.translate_header = true;
651
652         printQuery(res, &myopt, pset.queryFout, pset.logfile);
653
654         PQclear(res);
655         return true;
656 }
657
658
659 /*
660  * List Tables' Grant/Revoke Permissions
661  * \z (now also \dp -- perhaps more mnemonic)
662  */
663 bool
664 permissionsList(const char *pattern)
665 {
666         PQExpBufferData buf;
667         PGresult   *res;
668         printQueryOpt myopt = pset.popt;
669         static const bool translate_columns[] = {false, false, true, false, false};
670
671         initPQExpBuffer(&buf);
672
673         /*
674          * we ignore indexes and toast tables since they have no meaningful rights
675          */
676         printfPQExpBuffer(&buf,
677                                           "SELECT n.nspname as \"%s\",\n"
678                                           "  c.relname as \"%s\",\n"
679                                           "  CASE c.relkind WHEN 'r' THEN '%s' WHEN 'v' THEN '%s' WHEN 'S' THEN '%s' END as \"%s\",\n"
680                                           "  ",
681                                           gettext_noop("Schema"),
682                                           gettext_noop("Name"),
683                                           gettext_noop("table"), gettext_noop("view"), gettext_noop("sequence"),
684                                           gettext_noop("Type"));
685
686         printACLColumn(&buf, "c.relacl");
687
688         if (pset.sversion >= 80400)
689                 appendPQExpBuffer(&buf,
690                                                   ",\n  pg_catalog.array_to_string(ARRAY(\n"
691                                                   "    SELECT attname || E':\\n  ' || pg_catalog.array_to_string(attacl, E'\\n  ')\n"
692                                                   "    FROM pg_catalog.pg_attribute a\n"
693                                                   "    WHERE attrelid = c.oid AND NOT attisdropped AND attacl IS NOT NULL\n"
694                                                   "  ), E'\\n') AS \"%s\"",
695                                                   gettext_noop("Column access privileges"));
696
697         appendPQExpBuffer(&buf, "\nFROM pg_catalog.pg_class c\n"
698            "     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"
699                                           "WHERE c.relkind IN ('r', 'v', 'S')\n");
700
701         /*
702          * Unless a schema pattern is specified, we suppress system and temp
703          * tables, since they normally aren't very interesting from a permissions
704          * point of view.  You can see 'em by explicit request though, eg with \z
705          * pg_catalog.*
706          */
707         processSQLNamePattern(pset.db, &buf, pattern, true, false,
708                                                   "n.nspname", "c.relname", NULL,
709                         "n.nspname !~ '^pg_' AND pg_catalog.pg_table_is_visible(c.oid)");
710
711         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
712
713         res = PSQLexec(buf.data, false);
714         if (!res)
715         {
716                 termPQExpBuffer(&buf);
717                 return false;
718         }
719
720         myopt.nullPrint = NULL;
721         printfPQExpBuffer(&buf, _("Access privileges"));
722         myopt.title = buf.data;
723         myopt.translate_header = true;
724         myopt.translate_columns = translate_columns;
725
726         printQuery(res, &myopt, pset.queryFout, pset.logfile);
727
728         termPQExpBuffer(&buf);
729         PQclear(res);
730         return true;
731 }
732
733
734
735 /*
736  * Get object comments
737  *
738  * \dd [foo]
739  *
740  * Note: This only lists things that actually have a description. For complete
741  * lists of things, there are other \d? commands.
742  */
743 bool
744 objectDescription(const char *pattern, bool showSystem)
745 {
746         PQExpBufferData buf;
747         PGresult   *res;
748         printQueryOpt myopt = pset.popt;
749         static const bool translate_columns[] = {false, false, true, false};
750
751         initPQExpBuffer(&buf);
752
753         appendPQExpBuffer(&buf,
754                                           "SELECT DISTINCT tt.nspname AS \"%s\", tt.name AS \"%s\", tt.object AS \"%s\", d.description AS \"%s\"\n"
755                                           "FROM (\n",
756                                           gettext_noop("Schema"),
757                                           gettext_noop("Name"),
758                                           gettext_noop("Object"),
759                                           gettext_noop("Description"));
760
761         /* Aggregate descriptions */
762         appendPQExpBuffer(&buf,
763                                           "  SELECT p.oid as oid, p.tableoid as tableoid,\n"
764                                           "  n.nspname as nspname,\n"
765                                           "  CAST(p.proname AS pg_catalog.text) as name,"
766                                           "  CAST('%s' AS pg_catalog.text) as object\n"
767                                           "  FROM pg_catalog.pg_proc p\n"
768          "       LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n"
769                                           "  WHERE p.proisagg\n",
770                                           gettext_noop("aggregate"));
771
772         if (!showSystem && !pattern)
773                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
774                                                                 "      AND n.nspname <> 'information_schema'\n");
775
776         processSQLNamePattern(pset.db, &buf, pattern, true, false,
777                                                   "n.nspname", "p.proname", NULL,
778                                                   "pg_catalog.pg_function_is_visible(p.oid)");
779
780         /* Function descriptions */
781         appendPQExpBuffer(&buf,
782                                           "UNION ALL\n"
783                                           "  SELECT p.oid as oid, p.tableoid as tableoid,\n"
784                                           "  n.nspname as nspname,\n"
785                                           "  CAST(p.proname AS pg_catalog.text) as name,"
786                                           "  CAST('%s' AS pg_catalog.text) as object\n"
787                                           "  FROM pg_catalog.pg_proc p\n"
788          "       LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n"
789                                           "  WHERE NOT p.proisagg\n",
790                                           gettext_noop("function"));
791
792         if (!showSystem && !pattern)
793                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
794                                                                 "      AND n.nspname <> 'information_schema'\n");
795
796         processSQLNamePattern(pset.db, &buf, pattern, true, false,
797                                                   "n.nspname", "p.proname", NULL,
798                                                   "pg_catalog.pg_function_is_visible(p.oid)");
799
800         /* Operator descriptions (only if operator has its own comment) */
801         appendPQExpBuffer(&buf,
802                                           "UNION ALL\n"
803                                           "  SELECT o.oid as oid, o.tableoid as tableoid,\n"
804                                           "  n.nspname as nspname,\n"
805                                           "  CAST(o.oprname AS pg_catalog.text) as name,"
806                                           "  CAST('%s' AS pg_catalog.text) as object\n"
807                                           "  FROM pg_catalog.pg_operator o\n"
808         "       LEFT JOIN pg_catalog.pg_namespace n ON n.oid = o.oprnamespace\n",
809                                           gettext_noop("operator"));
810
811         if (!showSystem && !pattern)
812                 appendPQExpBuffer(&buf, "WHERE n.nspname <> 'pg_catalog'\n"
813                                                                 "      AND n.nspname <> 'information_schema'\n");
814  
815         processSQLNamePattern(pset.db, &buf, pattern, !showSystem && !pattern, false,
816                                                   "n.nspname", "o.oprname", NULL,
817                                                   "pg_catalog.pg_operator_is_visible(o.oid)");
818
819         /* Type description */
820         appendPQExpBuffer(&buf,
821                                           "UNION ALL\n"
822                                           "  SELECT t.oid as oid, t.tableoid as tableoid,\n"
823                                           "  n.nspname as nspname,\n"
824                                           "  pg_catalog.format_type(t.oid, NULL) as name,"
825                                           "  CAST('%s' AS pg_catalog.text) as object\n"
826                                           "  FROM pg_catalog.pg_type t\n"
827         "       LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n",
828                                           gettext_noop("data type"));
829
830         if (!showSystem && !pattern)
831                 appendPQExpBuffer(&buf, "WHERE n.nspname <> 'pg_catalog'\n"
832                                                                 "      AND n.nspname <> 'information_schema'\n");
833
834         processSQLNamePattern(pset.db, &buf, pattern, !showSystem && !pattern, false,
835                                                   "n.nspname", "pg_catalog.format_type(t.oid, NULL)",
836                                                   NULL,
837                                                   "pg_catalog.pg_type_is_visible(t.oid)");
838
839         /* Relation (tables, views, indexes, sequences) descriptions */
840         appendPQExpBuffer(&buf,
841                                           "UNION ALL\n"
842                                           "  SELECT c.oid as oid, c.tableoid as tableoid,\n"
843                                           "  n.nspname as nspname,\n"
844                                           "  CAST(c.relname AS pg_catalog.text) as name,\n"
845                                           "  CAST(\n"
846                                           "    CASE c.relkind WHEN 'r' THEN '%s' WHEN 'v' THEN '%s' WHEN 'i' THEN '%s' WHEN 'S' THEN '%s' END"
847                                           "  AS pg_catalog.text) as object\n"
848                                           "  FROM pg_catalog.pg_class c\n"
849          "       LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"
850                                           "  WHERE c.relkind IN ('r', 'v', 'i', 'S')\n",
851                                           gettext_noop("table"),
852                                           gettext_noop("view"),
853                                           gettext_noop("index"),
854                                           gettext_noop("sequence"));
855
856         if (!showSystem && !pattern)
857                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
858                                                                 "      AND n.nspname <> 'information_schema'\n");
859
860         processSQLNamePattern(pset.db, &buf, pattern, true, false,
861                                                   "n.nspname", "c.relname", NULL,
862                                                   "pg_catalog.pg_table_is_visible(c.oid)");
863
864         /* Rule description (ignore rules for views) */
865         appendPQExpBuffer(&buf,
866                                           "UNION ALL\n"
867                                           "  SELECT r.oid as oid, r.tableoid as tableoid,\n"
868                                           "  n.nspname as nspname,\n"
869                                           "  CAST(r.rulename AS pg_catalog.text) as name,"
870                                           "  CAST('%s' AS pg_catalog.text) as object\n"
871                                           "  FROM pg_catalog.pg_rewrite r\n"
872                                   "       JOIN pg_catalog.pg_class c ON c.oid = r.ev_class\n"
873          "       LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"
874                                           "  WHERE r.rulename != '_RETURN'\n",
875                                           gettext_noop("rule"));
876
877         if (!showSystem && !pattern)
878                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
879                                                                 "      AND n.nspname <> 'information_schema'\n");
880
881         /* XXX not sure what to do about visibility rule here? */
882         processSQLNamePattern(pset.db, &buf, pattern, true, false,
883                                                   "n.nspname", "r.rulename", NULL,
884                                                   "pg_catalog.pg_table_is_visible(c.oid)");
885
886         /* Trigger description */
887         appendPQExpBuffer(&buf,
888                                           "UNION ALL\n"
889                                           "  SELECT t.oid as oid, t.tableoid as tableoid,\n"
890                                           "  n.nspname as nspname,\n"
891                                           "  CAST(t.tgname AS pg_catalog.text) as name,"
892                                           "  CAST('%s' AS pg_catalog.text) as object\n"
893                                           "  FROM pg_catalog.pg_trigger t\n"
894                                    "       JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid\n"
895         "       LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n",
896                                           gettext_noop("trigger"));
897
898         if (!showSystem && !pattern)
899                 appendPQExpBuffer(&buf, "WHERE n.nspname <> 'pg_catalog'\n"
900                                                                 "      AND n.nspname <> 'information_schema'\n");
901
902         /* XXX not sure what to do about visibility rule here? */
903         processSQLNamePattern(pset.db, &buf, pattern, !showSystem && !pattern, false,
904                                                   "n.nspname", "t.tgname", NULL,
905                                                   "pg_catalog.pg_table_is_visible(c.oid)");
906
907         appendPQExpBuffer(&buf,
908                                           ") AS tt\n"
909                                           "  JOIN pg_catalog.pg_description d ON (tt.oid = d.objoid AND tt.tableoid = d.classoid AND d.objsubid = 0)\n");
910
911         appendPQExpBuffer(&buf, "ORDER BY 1, 2, 3;");
912
913         res = PSQLexec(buf.data, false);
914         termPQExpBuffer(&buf);
915         if (!res)
916                 return false;
917
918         myopt.nullPrint = NULL;
919         myopt.title = _("Object descriptions");
920         myopt.translate_header = true;
921         myopt.translate_columns = translate_columns;
922
923         printQuery(res, &myopt, pset.queryFout, pset.logfile);
924
925         PQclear(res);
926         return true;
927 }
928
929
930 /*
931  * describeTableDetails (for \d)
932  *
933  * This routine finds the tables to be displayed, and calls
934  * describeOneTableDetails for each one.
935  *
936  * verbose: if true, this is \d+
937  */
938 bool
939 describeTableDetails(const char *pattern, bool verbose, bool showSystem)
940 {
941         PQExpBufferData buf;
942         PGresult   *res;
943         int                     i;
944
945         initPQExpBuffer(&buf);
946
947         printfPQExpBuffer(&buf,
948                                           "SELECT c.oid,\n"
949                                           "  n.nspname,\n"
950                                           "  c.relname\n"
951                                           "FROM pg_catalog.pg_class c\n"
952          "     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n");
953
954         if (!showSystem && !pattern)
955                 appendPQExpBuffer(&buf, "WHERE n.nspname <> 'pg_catalog'\n"
956                                                                 "      AND n.nspname <> 'information_schema'\n");
957
958         processSQLNamePattern(pset.db, &buf, pattern, !showSystem && !pattern, false,
959                                                   "n.nspname", "c.relname", NULL,
960                                                   "pg_catalog.pg_table_is_visible(c.oid)");
961
962         appendPQExpBuffer(&buf, "ORDER BY 2, 3;");
963
964         res = PSQLexec(buf.data, false);
965         termPQExpBuffer(&buf);
966         if (!res)
967                 return false;
968
969         if (PQntuples(res) == 0)
970         {
971                 if (!pset.quiet)
972                         fprintf(stderr, _("Did not find any relation named \"%s\".\n"),
973                                         pattern);
974                 PQclear(res);
975                 return false;
976         }
977
978         for (i = 0; i < PQntuples(res); i++)
979         {
980                 const char *oid;
981                 const char *nspname;
982                 const char *relname;
983
984                 oid = PQgetvalue(res, i, 0);
985                 nspname = PQgetvalue(res, i, 1);
986                 relname = PQgetvalue(res, i, 2);
987
988                 if (!describeOneTableDetails(nspname, relname, oid, verbose))
989                 {
990                         PQclear(res);
991                         return false;
992                 }
993                 if (cancel_pressed)
994                 {
995                         PQclear(res);
996                         return false;
997                 }
998         }
999
1000         PQclear(res);
1001         return true;
1002 }
1003
1004 /*
1005  * describeOneTableDetails (for \d)
1006  *
1007  * Unfortunately, the information presented here is so complicated that it
1008  * cannot be done in a single query. So we have to assemble the printed table
1009  * by hand and pass it to the underlying printTable() function.
1010  */
1011 static bool
1012 describeOneTableDetails(const char *schemaname,
1013                                                 const char *relationname,
1014                                                 const char *oid,
1015                                                 bool verbose)
1016 {
1017         PQExpBufferData buf;
1018         PGresult   *res = NULL;
1019         printTableOpt myopt = pset.popt.topt;
1020         printTableContent cont;
1021         bool printTableInitialized = false;
1022         int                     i;
1023         char       *view_def = NULL;
1024         char       *headers[6];
1025         char      **seq_values = NULL;
1026         char      **modifiers = NULL;
1027         char      **ptr;
1028         PQExpBufferData title;
1029         PQExpBufferData tmpbuf;
1030         int                     cols = 0;
1031         int                     numrows = 0;
1032         struct
1033         {
1034                 int16           checks;
1035                 char            relkind;
1036                 bool            hasindex;
1037                 bool            hasrules;
1038                 bool            hastriggers;
1039                 bool            hasoids;
1040                 Oid                     tablespace;
1041                 char       *reloptions;
1042         }                       tableinfo;
1043         bool            show_modifiers = false;
1044         bool            retval;
1045
1046         retval = false;
1047
1048         /* This output looks confusing in expanded mode. */
1049         myopt.expanded = false;
1050
1051         initPQExpBuffer(&buf);
1052         initPQExpBuffer(&title);
1053         initPQExpBuffer(&tmpbuf);
1054
1055         /* Get general table info */
1056         if (pset.sversion >= 80400)
1057         {
1058                 printfPQExpBuffer(&buf,
1059                                                   "SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, "
1060                                                   "c.relhastriggers, c.relhasoids, "
1061                                                   "%s, c.reltablespace\n"
1062                                                   "FROM pg_catalog.pg_class c\n "
1063                                                   "LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid)\n"
1064                                                   "WHERE c.oid = '%s'\n",
1065                                                   (verbose ?
1066                                                   "pg_catalog.array_to_string(c.reloptions || "
1067                                                   "array(select 'toast.' || x from pg_catalog.unnest(tc.reloptions) x), ', ')\n"
1068                                                   : "''"),
1069                                                   oid);
1070         }
1071         else if (pset.sversion >= 80200)
1072         {
1073                 printfPQExpBuffer(&buf,
1074                                                   "SELECT relchecks, relkind, relhasindex, relhasrules, "
1075                                                   "reltriggers <> 0, relhasoids, "
1076                                                   "%s, reltablespace\n"
1077                                                   "FROM pg_catalog.pg_class WHERE oid = '%s'",
1078                                                   (verbose ?
1079                                                    "pg_catalog.array_to_string(reloptions, E', ')" : "''"),
1080                                                   oid);
1081         }
1082         else if (pset.sversion >= 80000)
1083         {
1084                 printfPQExpBuffer(&buf,
1085                                                   "SELECT relchecks, relkind, relhasindex, relhasrules, "
1086                                                   "reltriggers <> 0, relhasoids, "
1087                                                   "'', reltablespace\n"
1088                                                   "FROM pg_catalog.pg_class WHERE oid = '%s'",
1089                                                   oid);
1090         }
1091         else
1092         {
1093                 printfPQExpBuffer(&buf,
1094                                                   "SELECT relchecks, relkind, relhasindex, relhasrules, "
1095                                                   "reltriggers <> 0, relhasoids, "
1096                                                   "'', ''\n"
1097                                                   "FROM pg_catalog.pg_class WHERE oid = '%s'",
1098                                                   oid);
1099         }
1100
1101         res = PSQLexec(buf.data, false);
1102         if (!res)
1103                 goto error_return;
1104
1105         /* Did we get anything? */
1106         if (PQntuples(res) == 0)
1107         {
1108                 if (!pset.quiet)
1109                         fprintf(stderr, _("Did not find any relation with OID %s.\n"),
1110                                         oid);
1111                 goto error_return;
1112         }
1113
1114         tableinfo.checks = atoi(PQgetvalue(res, 0, 0));
1115         tableinfo.relkind = *(PQgetvalue(res, 0, 1));
1116         tableinfo.hasindex = strcmp(PQgetvalue(res, 0, 2), "t") == 0;
1117         tableinfo.hasrules = strcmp(PQgetvalue(res, 0, 3), "t") == 0;
1118         tableinfo.hastriggers = strcmp(PQgetvalue(res, 0, 4), "t") == 0;
1119         tableinfo.hasoids = strcmp(PQgetvalue(res, 0, 5), "t") == 0;
1120         tableinfo.reloptions = pset.sversion >= 80200 ?
1121                                                         strdup(PQgetvalue(res, 0, 6)) : 0;
1122         tableinfo.tablespace = (pset.sversion >= 80000) ?
1123                                                                 atooid(PQgetvalue(res, 0, 7)) : 0;
1124         PQclear(res);
1125         res = NULL;
1126         
1127         /*
1128          * If it's a sequence, fetch its values and store into an
1129          * array that will be used later.
1130          */
1131         if (tableinfo.relkind == 'S')
1132         {
1133                 PGresult   *result;
1134                 
1135 #define SEQ_NUM_COLS 10
1136                 printfPQExpBuffer(&buf,
1137                                                   "SELECT sequence_name, last_value,\n"
1138                                                   "       start_value, increment_by,\n"
1139                                                   "       max_value, min_value, cache_value,\n"
1140                                                   "       log_cnt, is_cycled, is_called\n"
1141                                                   "FROM %s",
1142                                                   fmtId(schemaname));
1143                 /* must be separate because fmtId isn't reentrant */
1144                 appendPQExpBuffer(&buf, ".%s", fmtId(relationname));
1145                 
1146                 result = PSQLexec(buf.data, false);
1147                 if (!result)
1148                         goto error_return;
1149                 
1150                 seq_values = pg_malloc_zero((SEQ_NUM_COLS+1) * sizeof(*seq_values));
1151                 
1152                 for (i = 0; i < SEQ_NUM_COLS; i++) 
1153                         seq_values[i] = pg_strdup(PQgetvalue(result, 0, i));
1154                 
1155                 PQclear(result);
1156         }
1157
1158         /* Get column info (index requires additional checks) */
1159         printfPQExpBuffer(&buf, "SELECT a.attname,");
1160         appendPQExpBuffer(&buf, "\n  pg_catalog.format_type(a.atttypid, a.atttypmod),"
1161                                           "\n  (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)"
1162                                           "\n   FROM pg_catalog.pg_attrdef d"
1163                                           "\n   WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef),"
1164                                           "\n  a.attnotnull, a.attnum");
1165         if (verbose)
1166                 appendPQExpBuffer(&buf, ", a.attstorage, pg_catalog.col_description(a.attrelid, a.attnum)");
1167         appendPQExpBuffer(&buf, "\nFROM pg_catalog.pg_attribute a");
1168         if (tableinfo.relkind == 'i')
1169                 appendPQExpBuffer(&buf, ", pg_catalog.pg_index i");
1170         appendPQExpBuffer(&buf, "\nWHERE a.attrelid = '%s' AND a.attnum > 0 AND NOT a.attisdropped", oid);
1171         if (tableinfo.relkind == 'i')
1172                 appendPQExpBuffer(&buf, " AND a.attrelid = i.indexrelid");
1173         appendPQExpBuffer(&buf, "\nORDER BY a.attnum");
1174
1175         res = PSQLexec(buf.data, false);
1176         if (!res)
1177                 goto error_return;
1178         numrows = PQntuples(res);
1179
1180         /* Make title */
1181         switch (tableinfo.relkind)
1182         {
1183                 case 'r':
1184                         printfPQExpBuffer(&title, _("Table \"%s.%s\""),
1185                                                           schemaname, relationname);
1186                         break;
1187                 case 'v':
1188                         printfPQExpBuffer(&title, _("View \"%s.%s\""),
1189                                                           schemaname, relationname);
1190                         break;
1191                 case 'S':
1192                         printfPQExpBuffer(&title, _("Sequence \"%s.%s\""),
1193                                                           schemaname, relationname);
1194                         break;
1195                 case 'i':
1196                         printfPQExpBuffer(&title, _("Index \"%s.%s\""),
1197                                                           schemaname, relationname);
1198                         break;
1199                 case 's':
1200                         /* not used as of 8.2, but keep it for backwards compatibility */
1201                         printfPQExpBuffer(&title, _("Special relation \"%s.%s\""),
1202                                                           schemaname, relationname);
1203                         break;
1204                 case 't':
1205                         printfPQExpBuffer(&title, _("TOAST table \"%s.%s\""),
1206                                                           schemaname, relationname);
1207                         break;
1208                 case 'c':
1209                         printfPQExpBuffer(&title, _("Composite type \"%s.%s\""),
1210                                                           schemaname, relationname);
1211                         break;
1212                 default:
1213                         /* untranslated unknown relkind */
1214                         printfPQExpBuffer(&title, "?%c? \"%s.%s\"",
1215                                                           tableinfo.relkind, schemaname, relationname);
1216                         break;
1217         }
1218
1219         /* Set the number of columns, and their names */
1220         cols += 2;
1221         headers[0] = gettext_noop("Column");
1222         headers[1] = gettext_noop("Type");
1223
1224         if (tableinfo.relkind == 'r' || tableinfo.relkind == 'v')
1225         {
1226                 show_modifiers = true;
1227                 headers[cols++] = gettext_noop("Modifiers");
1228                 modifiers = pg_malloc_zero((numrows + 1) * sizeof(*modifiers));
1229         }
1230
1231         if (tableinfo.relkind == 'S')
1232                 headers[cols++] = gettext_noop("Value");
1233                 
1234         if (verbose)
1235         {
1236                 headers[cols++] = gettext_noop("Storage");
1237                 headers[cols++] = gettext_noop("Description");
1238         }
1239         
1240         printTableInit(&cont, &myopt, title.data, cols, numrows);
1241         printTableInitialized = true;
1242
1243         for (i = 0; i < cols; i++)
1244                 printTableAddHeader(&cont, headers[i], true, 'l');
1245
1246         /* Check if table is a view */
1247         if (tableinfo.relkind == 'v')
1248         {
1249                 PGresult   *result;
1250
1251                 printfPQExpBuffer(&buf,
1252                                                   "SELECT pg_catalog.pg_get_viewdef('%s'::pg_catalog.oid, true)",
1253                                                   oid);
1254                 result = PSQLexec(buf.data, false);
1255                 if (!result)
1256                         goto error_return;
1257
1258                 if (PQntuples(result) > 0)
1259                         view_def = pg_strdup(PQgetvalue(result, 0, 0));
1260
1261                 PQclear(result);
1262         }
1263
1264         /* Generate table cells to be printed */
1265         for (i = 0; i < numrows; i++)
1266         {
1267                 /* Column */
1268                 printTableAddCell(&cont, PQgetvalue(res, i, 0), false);
1269
1270                 /* Type */
1271                 printTableAddCell(&cont, PQgetvalue(res, i, 1), false);
1272
1273                 /* Modifiers: not null and default */
1274                 if (show_modifiers)
1275                 {
1276                         resetPQExpBuffer(&tmpbuf);
1277                         if (strcmp(PQgetvalue(res, i, 3), "t") == 0)
1278                                 appendPQExpBufferStr(&tmpbuf, _("not null"));
1279
1280                         /* handle "default" here */
1281                         /* (note: above we cut off the 'default' string at 128) */
1282                         if (strlen(PQgetvalue(res, i, 2)) != 0)
1283                         {
1284                                 if (tmpbuf.len > 0)
1285                                         appendPQExpBufferStr(&tmpbuf, " ");
1286                                 /* translator: default values of column definitions */
1287                                 appendPQExpBuffer(&tmpbuf, _("default %s"),
1288                                                                   PQgetvalue(res, i, 2));
1289                         }
1290
1291                         modifiers[i] = pg_strdup(tmpbuf.data);
1292                         printTableAddCell(&cont, modifiers[i], false);
1293                 }
1294
1295                 /* Value: for sequences only */
1296                 if (tableinfo.relkind == 'S')
1297                         printTableAddCell(&cont, seq_values[i], false);
1298
1299                 /* Storage and Description */
1300                 if (verbose)
1301                 {
1302                         char *storage = PQgetvalue(res, i, 5);
1303
1304                         /* these strings are literal in our syntax, so not translated. */
1305                         printTableAddCell(&cont, (storage[0]=='p' ? "plain" :
1306                                                                           (storage[0]=='m' ? "main" :
1307                                                                            (storage[0]=='x' ? "extended" :
1308                                                                                 (storage[0]=='e' ? "external" :
1309                                                                                  "???")))),
1310                                                           false);
1311                         printTableAddCell(&cont, PQgetvalue(res, i, 6), false);
1312                 }
1313         }
1314
1315         /* Make footers */
1316         if (tableinfo.relkind == 'i')
1317         {
1318                 /* Footer information about an index */
1319                 PGresult   *result;
1320
1321                 printfPQExpBuffer(&buf,
1322                                                   "SELECT i.indisunique, i.indisprimary, i.indisclustered, ");
1323                 if (pset.sversion >= 80200)
1324                         appendPQExpBuffer(&buf, "i.indisvalid, ");
1325                 else
1326                         appendPQExpBuffer(&buf, "true as indisvalid, ");
1327                 appendPQExpBuffer(&buf, "a.amname, c2.relname,\n"
1328                                         "  pg_catalog.pg_get_expr(i.indpred, i.indrelid, true)\n"
1329                                                   "FROM pg_catalog.pg_index i, pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_am a\n"
1330                   "WHERE i.indexrelid = c.oid AND c.oid = '%s' AND c.relam = a.oid\n"
1331                                                   "AND i.indrelid = c2.oid",
1332                                                   oid);
1333
1334                 result = PSQLexec(buf.data, false);
1335                 if (!result)
1336                         goto error_return;
1337                 else if (PQntuples(result) != 1)
1338                 {
1339                         PQclear(result);
1340                         goto error_return;
1341                 }
1342                 else
1343                 {
1344                         char       *indisunique = PQgetvalue(result, 0, 0);
1345                         char       *indisprimary = PQgetvalue(result, 0, 1);
1346                         char       *indisclustered = PQgetvalue(result, 0, 2);
1347                         char       *indisvalid = PQgetvalue(result, 0, 3);
1348                         char       *indamname = PQgetvalue(result, 0, 4);
1349                         char       *indtable = PQgetvalue(result, 0, 5);
1350                         char       *indpred = PQgetvalue(result, 0, 6);
1351
1352                         if (strcmp(indisprimary, "t") == 0)
1353                                 printfPQExpBuffer(&tmpbuf, _("primary key, "));
1354                         else if (strcmp(indisunique, "t") == 0)
1355                                 printfPQExpBuffer(&tmpbuf, _("unique, "));
1356                         else
1357                                 resetPQExpBuffer(&tmpbuf);
1358                         appendPQExpBuffer(&tmpbuf, "%s, ", indamname);
1359
1360                         /* we assume here that index and table are in same schema */
1361                         appendPQExpBuffer(&tmpbuf, _("for table \"%s.%s\""),
1362                                                           schemaname, indtable);
1363
1364                         if (strlen(indpred))
1365                                 appendPQExpBuffer(&tmpbuf, _(", predicate (%s)"), indpred);
1366
1367                         if (strcmp(indisclustered, "t") == 0)
1368                                 appendPQExpBuffer(&tmpbuf, _(", clustered"));
1369
1370                         if (strcmp(indisvalid, "t") != 0)
1371                                 appendPQExpBuffer(&tmpbuf, _(", invalid"));
1372
1373                         printTableAddFooter(&cont, tmpbuf.data);
1374                         add_tablespace_footer(&cont, tableinfo.relkind,
1375                                                                   tableinfo.tablespace, true);
1376                 }
1377
1378                 PQclear(result);
1379         }
1380         else if (view_def)
1381         {
1382                 PGresult   *result = NULL;
1383
1384                 /* Footer information about a view */
1385                 printTableAddFooter(&cont, _("View definition:"));
1386                 printTableAddFooter(&cont, view_def);
1387
1388                 /* print rules */
1389                 if (tableinfo.hasrules)
1390                 {
1391                         printfPQExpBuffer(&buf,
1392                                                           "SELECT r.rulename, trim(trailing ';' from pg_catalog.pg_get_ruledef(r.oid, true))\n"
1393                                                           "FROM pg_catalog.pg_rewrite r\n"
1394                         "WHERE r.ev_class = '%s' AND r.rulename != '_RETURN' ORDER BY 1",
1395                                                           oid);
1396                         result = PSQLexec(buf.data, false);
1397                         if (!result)
1398                                 goto error_return;
1399
1400                         if (PQntuples(result) > 0)
1401                         {
1402                                 printTableAddFooter(&cont, _("Rules:"));
1403                                 for (i = 0; i < PQntuples(result); i++)
1404                                 {
1405                                         const char *ruledef;
1406
1407                                         /* Everything after "CREATE RULE" is echoed verbatim */
1408                                         ruledef = PQgetvalue(result, i, 1);
1409                                         ruledef += 12;
1410
1411                                         printfPQExpBuffer(&buf, " %s", ruledef);
1412                                         printTableAddFooter(&cont, buf.data);
1413                                 }
1414                         }
1415                         PQclear(result);
1416                 }
1417         }
1418         else if (tableinfo.relkind == 'r')
1419         {
1420                 /* Footer information about a table */
1421                 PGresult   *result = NULL;
1422                 int                     tuples = 0;
1423
1424                 /* print indexes */
1425                 if (tableinfo.hasindex)
1426                 {
1427                         printfPQExpBuffer(&buf,
1428                                                           "SELECT c2.relname, i.indisprimary, i.indisunique, i.indisclustered, ");
1429             if (pset.sversion >= 80200)
1430                                 appendPQExpBuffer(&buf, "i.indisvalid, ");
1431             else
1432                                 appendPQExpBuffer(&buf, "true as indisvalid, ");
1433                         appendPQExpBuffer(&buf, "pg_catalog.pg_get_indexdef(i.indexrelid, 0, true)");
1434             if (pset.sversion >= 80000)
1435                                 appendPQExpBuffer(&buf, ", c2.reltablespace");
1436                         appendPQExpBuffer(&buf,
1437                                                           "\nFROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i\n"
1438                                                           "WHERE c.oid = '%s' AND c.oid = i.indrelid AND i.indexrelid = c2.oid\n"
1439                           "ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname",
1440                                                           oid);
1441                         result = PSQLexec(buf.data, false);
1442                         if (!result)
1443                                 goto error_return;
1444                         else
1445                                 tuples = PQntuples(result);
1446
1447                         if (tuples > 0)
1448                         {
1449                                 printTableAddFooter(&cont, _("Indexes:"));
1450                                 for (i = 0; i < tuples; i++)
1451                                 {
1452                                         const char *indexdef;
1453                                         const char *usingpos;
1454
1455                                         /* untranslated index name */
1456                                         printfPQExpBuffer(&buf, "    \"%s\"",
1457                                                                           PQgetvalue(result, i, 0));
1458
1459                                         /* Label as primary key or unique (but not both) */
1460                                         appendPQExpBuffer(&buf,
1461                                                                           strcmp(PQgetvalue(result, i, 1), "t") == 0
1462                                                                           ? " PRIMARY KEY," :
1463                                                                           (strcmp(PQgetvalue(result, i, 2), "t") == 0
1464                                                                            ? " UNIQUE,"
1465                                                                            : ""));
1466                                         /* Everything after "USING" is echoed verbatim */
1467                                         indexdef = PQgetvalue(result, i, 5);
1468                                         usingpos = strstr(indexdef, " USING ");
1469                                         if (usingpos)
1470                                                 indexdef = usingpos + 7;
1471
1472                                         appendPQExpBuffer(&buf, " %s", indexdef);
1473
1474                                         if (strcmp(PQgetvalue(result, i, 3), "t") == 0)
1475                                                 appendPQExpBuffer(&buf, " CLUSTER");
1476
1477                                         if (strcmp(PQgetvalue(result, i, 4), "t") != 0)
1478                                                 appendPQExpBuffer(&buf, " INVALID");
1479
1480                                         printTableAddFooter(&cont, buf.data);
1481
1482                                         /* Print tablespace of the index on the same line */
1483                                         if (pset.sversion >= 80000)
1484                                             add_tablespace_footer(&cont, 'i',
1485                                                                                           atooid(PQgetvalue(result, i, 6)),
1486                                                                                           false);
1487                                 }
1488                         }
1489                         PQclear(result);
1490                 }
1491
1492                 /* print table (and column) check constraints */
1493                 if (tableinfo.checks)
1494                 {
1495                         printfPQExpBuffer(&buf,
1496                                                           "SELECT r.conname, "
1497                                                           "pg_catalog.pg_get_constraintdef(r.oid, true)\n"
1498                                                           "FROM pg_catalog.pg_constraint r\n"
1499                                         "WHERE r.conrelid = '%s' AND r.contype = 'c'\nORDER BY 1",
1500                                                           oid);
1501                         result = PSQLexec(buf.data, false);
1502                         if (!result)
1503                                 goto error_return;
1504                         else
1505                                 tuples = PQntuples(result);
1506
1507                         if (tuples > 0)
1508                         {
1509                                 printTableAddFooter(&cont, _("Check constraints:"));
1510                                 for (i = 0; i < tuples; i++)
1511                                 {
1512                                         /* untranslated contraint name and def */
1513                                         printfPQExpBuffer(&buf, "    \"%s\" %s",
1514                                                                           PQgetvalue(result, i, 0),
1515                                                                           PQgetvalue(result, i, 1));
1516
1517                                         printTableAddFooter(&cont, buf.data);
1518                                 }
1519                         }
1520                         PQclear(result);
1521                 }
1522
1523                 /* print foreign-key constraints (there are none if no triggers) */
1524                 if (tableinfo.hastriggers)
1525                 {
1526                         printfPQExpBuffer(&buf,
1527                                                           "SELECT conname,\n"
1528                                    "  pg_catalog.pg_get_constraintdef(r.oid, true) as condef\n"
1529                                                           "FROM pg_catalog.pg_constraint r\n"
1530                                         "WHERE r.conrelid = '%s' AND r.contype = 'f' ORDER BY 1",
1531                                                           oid);
1532                         result = PSQLexec(buf.data, false);
1533                         if (!result)
1534                                 goto error_return;
1535                         else
1536                                 tuples = PQntuples(result);
1537
1538                         if (tuples > 0)
1539                         {
1540                                 printTableAddFooter(&cont, _("Foreign-key constraints:"));
1541                                 for (i = 0; i < tuples; i++)
1542                                 {
1543                                         /* untranslated constraint name and def */
1544                                         printfPQExpBuffer(&buf, "    \"%s\" %s",
1545                                                                           PQgetvalue(result, i, 0),
1546                                                                           PQgetvalue(result, i, 1));
1547
1548                                         printTableAddFooter(&cont, buf.data);
1549                                 }
1550                         }
1551                         PQclear(result);
1552                 }
1553
1554                 /* print incoming foreign-key references (none if no triggers) */
1555                 if (tableinfo.hastriggers)
1556                 {
1557                         printfPQExpBuffer(&buf,
1558                                                           "SELECT conname, conrelid::pg_catalog.regclass,\n"
1559                                                           "  pg_catalog.pg_get_constraintdef(c.oid, true) as condef\n"
1560                                                           "FROM pg_catalog.pg_constraint c\n"
1561                                                           "WHERE c.confrelid = '%s' AND c.contype = 'f' ORDER BY 1",
1562                                                           oid);
1563                         result = PSQLexec(buf.data, false);
1564                         if (!result)
1565                                 goto error_return;
1566                         else
1567                                 tuples = PQntuples(result);
1568
1569                         if (tuples > 0)
1570                         {
1571                                 printTableAddFooter(&cont, _("Referenced by:"));
1572                                 for (i = 0; i < tuples; i++)
1573                                 {
1574                                         /* translator: the first %s is a FK name, the following are
1575                                          * a table name and the FK definition */
1576                                         printfPQExpBuffer(&buf, _("  \"%s\" IN %s %s"),
1577                                                                           PQgetvalue(result, i, 0),
1578                                                                           PQgetvalue(result, i, 1),
1579                                                                           PQgetvalue(result, i, 2));
1580
1581                                         printTableAddFooter(&cont, buf.data);
1582                                 }
1583                         }
1584                         PQclear(result);
1585                 }
1586
1587                 /* print rules */
1588                 if (tableinfo.hasrules)
1589                 {
1590                         if (pset.sversion >= 80300)
1591                         {
1592                                 printfPQExpBuffer(&buf,
1593                                                                   "SELECT r.rulename, trim(trailing ';' from pg_catalog.pg_get_ruledef(r.oid, true)), "
1594                                                                   "ev_enabled\n"
1595                                                                   "FROM pg_catalog.pg_rewrite r\n"
1596                                                                   "WHERE r.ev_class = '%s' ORDER BY 1",
1597                                                                   oid);
1598                         }
1599                         else
1600                         {
1601                                 printfPQExpBuffer(&buf,
1602                                                                   "SELECT r.rulename, trim(trailing ';' from pg_catalog.pg_get_ruledef(r.oid, true)), "
1603                                                                   "'O'::char AS ev_enabled\n"
1604                                                                   "FROM pg_catalog.pg_rewrite r\n"
1605                                                                   "WHERE r.ev_class = '%s' ORDER BY 1",
1606                                                                   oid);
1607                         }
1608                         result = PSQLexec(buf.data, false);
1609                         if (!result)
1610                                 goto error_return;
1611                         else
1612                                 tuples = PQntuples(result);
1613
1614                         if (tuples > 0)
1615                         {
1616                                 bool            have_heading;
1617                                 int                     category;
1618
1619                                 for (category = 0; category < 4; category++)
1620                                 {
1621                                         have_heading = false;
1622
1623                                         for (i = 0; i < tuples; i++)
1624                                         {
1625                                                 const char *ruledef;
1626                                                 bool            list_rule = false;
1627
1628                                                 switch (category)
1629                                                 {
1630                                                         case 0:
1631                                                                 if (*PQgetvalue(result, i, 2) == 'O')
1632                                                                         list_rule = true;
1633                                                                 break;
1634                                                         case 1:
1635                                                                 if (*PQgetvalue(result, i, 2) == 'D')
1636                                                                         list_rule = true;
1637                                                                 break;
1638                                                         case 2:
1639                                                                 if (*PQgetvalue(result, i, 2) == 'A')
1640                                                                         list_rule = true;
1641                                                                 break;
1642                                                         case 3:
1643                                                                 if (*PQgetvalue(result, i, 2) == 'R')
1644                                                                         list_rule = true;
1645                                                                 break;
1646                                                 }
1647                                                 if (!list_rule)
1648                                                         continue;
1649
1650                                                 if (!have_heading)
1651                                                 {
1652                                                         switch (category)
1653                                                         {
1654                                                                 case 0:
1655                                                                         printfPQExpBuffer(&buf, _("Rules:"));
1656                                                                         break;
1657                                                                 case 1:
1658                                                                         printfPQExpBuffer(&buf, _("Disabled rules:"));
1659                                                                         break;
1660                                                                 case 2:
1661                                                                         printfPQExpBuffer(&buf, _("Rules firing always:"));
1662                                                                         break;
1663                                                                 case 3:
1664                                                                         printfPQExpBuffer(&buf, _("Rules firing on replica only:"));
1665                                                                         break;
1666                                                         }
1667                                                         printTableAddFooter(&cont, buf.data);
1668                                                         have_heading = true;
1669                                                 }
1670
1671                                                 /* Everything after "CREATE RULE" is echoed verbatim */
1672                                                 ruledef = PQgetvalue(result, i, 1);
1673                                                 ruledef += 12;
1674                                                 printfPQExpBuffer(&buf, "    %s", ruledef);
1675                                                 printTableAddFooter(&cont, buf.data);
1676                                         }
1677                                 }
1678                         }
1679                         PQclear(result);
1680                 }
1681
1682                 /* print triggers (but ignore foreign-key triggers) */
1683                 if (tableinfo.hastriggers)
1684                 {
1685                         printfPQExpBuffer(&buf,
1686                                                           "SELECT t.tgname, "
1687                                                           "pg_catalog.pg_get_triggerdef(t.oid), "
1688                                                           "t.tgenabled\n"
1689                                                           "FROM pg_catalog.pg_trigger t\n"
1690                                                           "WHERE t.tgrelid = '%s' AND ",
1691                                                           oid);
1692                         if (pset.sversion >= 80300)
1693                                 appendPQExpBuffer(&buf, "t.tgconstraint = 0");
1694                         else
1695                                 appendPQExpBuffer(&buf,
1696                                                                   "(NOT tgisconstraint "
1697                                                                   " OR NOT EXISTS"
1698                                                                   "  (SELECT 1 FROM pg_catalog.pg_depend d "
1699                                                                   "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
1700                                                                   "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))");
1701                         appendPQExpBuffer(&buf, "\nORDER BY 1");
1702
1703                         result = PSQLexec(buf.data, false);
1704                         if (!result)
1705                                 goto error_return;
1706                         else
1707                                 tuples = PQntuples(result);
1708
1709                         if (tuples > 0)
1710                         {
1711                                 bool            have_heading;
1712                                 int                     category;
1713
1714                                 /*
1715                                  * split the output into 4 different categories. Enabled triggers,
1716                                  * disabled triggers and the two special ALWAYS and REPLICA
1717                                  * configurations.
1718                                  */
1719                                 for (category = 0; category < 4; category++)
1720                                 {
1721                                         have_heading = false;
1722                                         for (i = 0; i < tuples; i++)
1723                                         {
1724                                                 bool            list_trigger;
1725                                                 const char *tgdef;
1726                                                 const char *usingpos;
1727                                                 const char *tgenabled;
1728
1729                                                 /* Check if this trigger falls into the current category */
1730                                                 tgenabled = PQgetvalue(result, i, 2);
1731                                                 list_trigger = false;
1732                                                 switch (category)
1733                                                 {
1734                                                         case 0:
1735                                                                 if (*tgenabled == 'O' || *tgenabled == 't')
1736                                                                         list_trigger = true;
1737                                                                 break;
1738                                                         case 1:
1739                                                                 if (*tgenabled == 'D' || *tgenabled == 'f')
1740                                                                         list_trigger = true;
1741                                                                 break;
1742                                                         case 2:
1743                                                                 if (*tgenabled == 'A')
1744                                                                         list_trigger = true;
1745                                                                 break;
1746                                                         case 3:
1747                                                                 if (*tgenabled == 'R')
1748                                                                         list_trigger = true;
1749                                                                 break;
1750                                                 }
1751                                                 if (list_trigger == false)
1752                                                         continue;
1753
1754                                                 /* Print the category heading once */
1755                                                 if (have_heading == false)
1756                                                 {
1757                                                         switch (category)
1758                                                         {
1759                                                                 case 0:
1760                                                                         printfPQExpBuffer(&buf, _("Triggers:"));
1761                                                                         break;
1762                                                                 case 1:
1763                                                                         printfPQExpBuffer(&buf, _("Disabled triggers:"));
1764                                                                         break;
1765                                                                 case 2:
1766                                                                         printfPQExpBuffer(&buf, _("Triggers firing always:"));
1767                                                                         break;
1768                                                                 case 3:
1769                                                                         printfPQExpBuffer(&buf, _("Triggers firing on replica only:"));
1770                                                                         break;
1771
1772                                                         }
1773                                                         printTableAddFooter(&cont, buf.data);
1774                                                         have_heading = true;
1775                                                 }
1776
1777                                                 /* Everything after "TRIGGER" is echoed verbatim */
1778                                                 tgdef = PQgetvalue(result, i, 1);
1779                                                 usingpos = strstr(tgdef, " TRIGGER ");
1780                                                 if (usingpos)
1781                                                         tgdef = usingpos + 9;
1782
1783                                                 printfPQExpBuffer(&buf, "    %s", tgdef);
1784                                                 printTableAddFooter(&cont, buf.data);
1785                                         }
1786                                 }
1787                         }
1788                         PQclear(result);
1789                 }
1790
1791                 /* print inherited tables */
1792                 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);
1793
1794                 result = PSQLexec(buf.data, false);
1795                 if (!result)
1796                         goto error_return;
1797                 else
1798                         tuples = PQntuples(result);
1799
1800                 for (i = 0; i < tuples; i++)
1801                 {
1802                         const char *s = _("Inherits");
1803
1804                         if (i == 0)
1805                                 printfPQExpBuffer(&buf, "%s: %s", s, PQgetvalue(result, i, 0));
1806                         else
1807                                 printfPQExpBuffer(&buf, "%*s  %s", (int) strlen(s), "", PQgetvalue(result, i, 0));
1808                         if (i < tuples - 1)
1809                                 appendPQExpBuffer(&buf, ",");
1810
1811                         printTableAddFooter(&cont, buf.data);
1812                 }
1813                 PQclear(result);
1814
1815                 if (verbose)
1816                 {
1817                         const char *s = _("Has OIDs");
1818
1819                         printfPQExpBuffer(&buf, "%s: %s", s,
1820                                                           (tableinfo.hasoids ? _("yes") : _("no")));
1821                         printTableAddFooter(&cont, buf.data);
1822
1823                         /* print reloptions */
1824                         if (pset.sversion >= 80200)
1825                         {
1826                                 if (tableinfo.reloptions && tableinfo.reloptions[0] != '\0')
1827                                 {
1828                                         const char *t = _("Options");
1829
1830                                         printfPQExpBuffer(&buf, "%s: %s", t,
1831                                                                           tableinfo.reloptions);
1832                                         printTableAddFooter(&cont, buf.data);
1833                                 }
1834                         }
1835                 }
1836
1837                 add_tablespace_footer(&cont, tableinfo.relkind, tableinfo.tablespace,
1838                                                           true);
1839         }
1840
1841         printTable(&cont, pset.queryFout, pset.logfile);
1842         printTableCleanup(&cont);
1843
1844         retval = true;
1845
1846 error_return:
1847
1848         /* clean up */
1849         if (printTableInitialized)
1850                 printTableCleanup(&cont);
1851         termPQExpBuffer(&buf);
1852         termPQExpBuffer(&title);
1853         termPQExpBuffer(&tmpbuf);
1854         
1855         if (seq_values)
1856         {
1857                 for (ptr = seq_values; *ptr; ptr++)
1858                         free(*ptr);
1859                 free(seq_values);
1860         }
1861     
1862         if (modifiers)
1863         {
1864                 for (ptr = modifiers; *ptr; ptr++)
1865                         free(*ptr);
1866                 free(modifiers);
1867         }
1868
1869         if (view_def)
1870                 free(view_def);
1871
1872         if (res)
1873                 PQclear(res);
1874
1875         return retval;
1876 }
1877
1878 /*
1879  * Add a tablespace description to a footer.  If 'newline' is true, it is added
1880  * in a new line; otherwise it's appended to the current value of the last
1881  * footer.
1882  */
1883 static void
1884 add_tablespace_footer(printTableContent *const cont, char relkind,
1885                                           Oid tablespace, const bool newline)
1886 {
1887         /* relkinds for which we support tablespaces */
1888         if (relkind == 'r' || relkind == 'i')
1889         {
1890                 /*
1891                  * We ignore the database default tablespace so that users not using
1892                  * tablespaces don't need to know about them.  This case also covers
1893                  * pre-8.0 servers, for which tablespace will always be 0.
1894                  */
1895                 if (tablespace != 0)
1896                 {
1897                         PGresult   *result = NULL;
1898                         PQExpBufferData buf;
1899
1900                         initPQExpBuffer(&buf);
1901                         printfPQExpBuffer(&buf,
1902                                                           "SELECT spcname FROM pg_catalog.pg_tablespace\n"
1903                                                           "WHERE oid = '%u'", tablespace);
1904                         result = PSQLexec(buf.data, false);
1905                         if (!result)
1906                                 return;
1907                         /* Should always be the case, but.... */
1908                         if (PQntuples(result) > 0)
1909                         {
1910                                 if (newline)
1911                                 {
1912                                         /* Add the tablespace as a new footer */
1913                                         printfPQExpBuffer(&buf, _("Tablespace: \"%s\""),
1914                                                                           PQgetvalue(result, 0, 0));
1915                                         printTableAddFooter(cont, buf.data);
1916                                 }
1917                                 else
1918                                 {
1919                                         /* Append the tablespace to the latest footer */
1920                                         printfPQExpBuffer(&buf, "%s", cont->footer->data);
1921                                         /* translator: before this string there's an index
1922                                          * description like '"foo_pkey" PRIMARY KEY, btree (a)' */
1923                                         appendPQExpBuffer(&buf, _(", tablespace \"%s\""),
1924                                                                           PQgetvalue(result, 0, 0));
1925                                         printTableSetFooter(cont, buf.data);
1926                                 }
1927                         }
1928                         PQclear(result);
1929                         termPQExpBuffer(&buf);
1930                 }
1931         }
1932 }
1933
1934 /*
1935  * \du or \dg
1936  *
1937  * Describes roles.  Any schema portion of the pattern is ignored.
1938  */
1939 bool
1940 describeRoles(const char *pattern, bool verbose)
1941 {
1942         PQExpBufferData buf;
1943         PGresult   *res;
1944         printTableContent cont;
1945         printTableOpt myopt = pset.popt.topt;
1946         int                     ncols = 3;
1947         int                     nrows = 0;
1948         int                     i;
1949         int                     conns;
1950         const char      align = 'l';
1951         char      **attr;
1952
1953         initPQExpBuffer(&buf);
1954
1955         if (pset.sversion >= 80100)
1956         {
1957                 printfPQExpBuffer(&buf,
1958                                              "SELECT r.rolname, r.rolsuper, r.rolinherit,\n"
1959                                                  "  r.rolcreaterole, r.rolcreatedb, r.rolcanlogin,\n"
1960                                                  "  r.rolconnlimit,\n"
1961                                              "  ARRAY(SELECT b.rolname\n"
1962                                              "        FROM pg_catalog.pg_auth_members m\n"
1963                                              "        JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)\n"
1964                                              "        WHERE m.member = r.oid) as memberof");
1965
1966                 if (verbose && pset.sversion >= 80200)
1967                 {
1968                         appendPQExpBufferStr(&buf, "\n, pg_catalog.shobj_description(r.oid, 'pg_authid') AS description");
1969                         ncols++;
1970                 }
1971
1972                 appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_roles r\n");
1973
1974                 processSQLNamePattern(pset.db, &buf, pattern, false, false,
1975                                                           NULL, "r.rolname", NULL, NULL);
1976     }
1977     else
1978     {
1979             printfPQExpBuffer(&buf,
1980                                           "SELECT u.usename AS rolname,\n"
1981                                           "  u.usesuper AS rolsuper,\n"
1982                                           "  true AS rolinherit, false AS rolcreaterole,\n"
1983                                           "  u.usecreatedb AS rolcreatedb, true AS rolcanlogin,\n"
1984                                           "  -1 AS rolconnlimit,\n"
1985                                           "  ARRAY(SELECT g.groname FROM pg_catalog.pg_group g WHERE u.usesysid = ANY(g.grolist)) as memberof"
1986                                           "\nFROM pg_catalog.pg_user u\n");
1987
1988                 processSQLNamePattern(pset.db, &buf, pattern, false, false,
1989                                                           NULL, "u.usename", NULL, NULL);
1990     }
1991
1992         appendPQExpBuffer(&buf, "ORDER BY 1;");
1993
1994         res = PSQLexec(buf.data, false);
1995         if (!res)
1996                 return false;
1997
1998         nrows = PQntuples(res);
1999         attr = pg_malloc_zero((nrows + 1) * sizeof(*attr));
2000
2001         printTableInit(&cont, &myopt, _("List of roles"), ncols, nrows);
2002
2003         printTableAddHeader(&cont, gettext_noop("Role name"), true, align);
2004         printTableAddHeader(&cont, gettext_noop("Attributes"), true, align);
2005         printTableAddHeader(&cont, gettext_noop("Member of"), true, align);
2006
2007         if (verbose && pset.sversion >= 80200)
2008                 printTableAddHeader(&cont, gettext_noop("Description"), true, align);
2009
2010         for (i = 0; i < nrows; i++)
2011         {
2012                 printTableAddCell(&cont, PQgetvalue(res, i, 0), false);
2013
2014                 resetPQExpBuffer(&buf);
2015                 if (strcmp(PQgetvalue(res, i, 1), "t") == 0)
2016                         add_role_attribute(&buf, _("Superuser"));
2017
2018                 if (strcmp(PQgetvalue(res, i, 2), "t") != 0)
2019                         add_role_attribute(&buf, _("No inheritance"));
2020
2021                 if (strcmp(PQgetvalue(res, i, 3), "t") == 0)
2022                         add_role_attribute(&buf, _("Create role"));
2023
2024                 if (strcmp(PQgetvalue(res, i, 4), "t") == 0)
2025                         add_role_attribute(&buf, _("Create DB"));
2026
2027                 if (strcmp(PQgetvalue(res, i, 5), "t") != 0)
2028                         add_role_attribute(&buf, _("Cannot login"));
2029
2030                 conns = atoi(PQgetvalue(res, i, 6));
2031                 if (conns >= 0)
2032                 {
2033                         if (buf.len > 0)
2034                                 appendPQExpBufferStr(&buf, "\n");
2035
2036                         if (conns == 0)
2037                                 appendPQExpBuffer(&buf, _("No connections"));
2038                         else
2039                                 appendPQExpBuffer(&buf, ngettext("1 connection", "%d connections", conns), conns);
2040                 }
2041
2042                 attr[i] = pg_strdup(buf.data);
2043
2044                 printTableAddCell(&cont, attr[i], false);
2045
2046                 printTableAddCell(&cont, PQgetvalue(res, i, 7), false);
2047
2048                 if (verbose && pset.sversion >= 80200)
2049                         printTableAddCell(&cont, PQgetvalue(res, i, 8), false);
2050         }
2051         termPQExpBuffer(&buf);
2052
2053         printTable(&cont, pset.queryFout, pset.logfile);
2054         printTableCleanup(&cont);
2055
2056         for (i = 0; i < nrows; i++)
2057                 free(attr[i]);
2058         free(attr);
2059
2060         PQclear(res);
2061         return true;
2062 }
2063
2064 void
2065 add_role_attribute(PQExpBuffer buf, const char *const str)
2066 {
2067         if (buf->len > 0)
2068                 appendPQExpBufferStr(buf, "\n");
2069
2070         appendPQExpBufferStr(buf, str);
2071 }
2072
2073
2074 /*
2075  * listTables()
2076  *
2077  * handler for \dt, \di, etc.
2078  *
2079  * tabtypes is an array of characters, specifying what info is desired:
2080  * t - tables
2081  * i - indexes
2082  * v - views
2083  * s - sequences
2084  * (any order of the above is fine)
2085  * If tabtypes is empty, we default to \dtvs.
2086  */
2087 bool
2088 listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem)
2089 {
2090         bool            showTables = strchr(tabtypes, 't') != NULL;
2091         bool            showIndexes = strchr(tabtypes, 'i') != NULL;
2092         bool            showViews = strchr(tabtypes, 'v') != NULL;
2093         bool            showSeq = strchr(tabtypes, 's') != NULL;
2094
2095         PQExpBufferData buf;
2096         PGresult   *res;
2097         printQueryOpt myopt = pset.popt;
2098         static const bool translate_columns[] = {false, false, true, false, false, false, false};
2099
2100         if (!(showTables || showIndexes || showViews || showSeq))
2101                 showTables = showViews = showSeq = true;
2102
2103         initPQExpBuffer(&buf);
2104
2105         /*
2106          * Note: as of Pg 8.2, we no longer use relkind 's', but we keep it here
2107          * for backwards compatibility.
2108          */
2109         printfPQExpBuffer(&buf,
2110                                           "SELECT n.nspname as \"%s\",\n"
2111                                           "  c.relname as \"%s\",\n"
2112                                           "  CASE c.relkind WHEN 'r' THEN '%s' WHEN 'v' THEN '%s' WHEN 'i' THEN '%s' WHEN 'S' THEN '%s' WHEN 's' THEN '%s' END as \"%s\",\n"
2113                                           "  pg_catalog.pg_get_userbyid(c.relowner) as \"%s\"",
2114                                           gettext_noop("Schema"),
2115                                           gettext_noop("Name"),
2116                                           gettext_noop("table"),
2117                                           gettext_noop("view"),
2118                                           gettext_noop("index"),
2119                                           gettext_noop("sequence"),
2120                                           gettext_noop("special"),
2121                                           gettext_noop("Type"),
2122                                           gettext_noop("Owner"));
2123
2124         if (showIndexes)
2125                 appendPQExpBuffer(&buf,
2126                                                   ",\n c2.relname as \"%s\"",
2127                                                   gettext_noop("Table"));
2128
2129         if (verbose && pset.sversion >= 80100)
2130                 appendPQExpBuffer(&buf,
2131                                                   ",\n  pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(c.oid)) as \"%s\"",
2132                                                   gettext_noop("Size"));
2133         if (verbose)
2134                 appendPQExpBuffer(&buf,
2135                           ",\n  pg_catalog.obj_description(c.oid, 'pg_class') as \"%s\"",
2136                                                   gettext_noop("Description"));
2137
2138         appendPQExpBuffer(&buf,
2139                                           "\nFROM pg_catalog.pg_class c"
2140          "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace");
2141         if (showIndexes)
2142                 appendPQExpBuffer(&buf,
2143                          "\n     LEFT JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid"
2144                    "\n     LEFT JOIN pg_catalog.pg_class c2 ON i.indrelid = c2.oid");
2145
2146         appendPQExpBuffer(&buf, "\nWHERE c.relkind IN (");
2147         if (showTables)
2148                 appendPQExpBuffer(&buf, "'r',");
2149         if (showViews)
2150                 appendPQExpBuffer(&buf, "'v',");
2151         if (showIndexes)
2152                 appendPQExpBuffer(&buf, "'i',");
2153         if (showSeq)
2154                 appendPQExpBuffer(&buf, "'S',");
2155         if (showSystem || pattern)
2156                 appendPQExpBuffer(&buf, "'s',");        /* was RELKIND_SPECIAL in <= 8.1 */
2157         appendPQExpBuffer(&buf, "''");          /* dummy */
2158         appendPQExpBuffer(&buf, ")\n");
2159
2160         if (!showSystem && !pattern)
2161                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
2162                                                                 "      AND n.nspname <> 'information_schema'\n");
2163
2164         /*
2165          * TOAST objects are suppressed unconditionally.  Since we don't provide
2166          * any way to select relkind 't' above, we would never show toast tables
2167          * in any case; it seems a bit confusing to allow their indexes to be
2168          * shown. Use plain \d if you really need to look at a TOAST table/index.
2169          */
2170         appendPQExpBuffer(&buf, "      AND n.nspname !~ '^pg_toast'\n");
2171
2172         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2173                                                   "n.nspname", "c.relname", NULL,
2174                                                   "pg_catalog.pg_table_is_visible(c.oid)");
2175
2176         appendPQExpBuffer(&buf, "ORDER BY 1,2;");
2177
2178         res = PSQLexec(buf.data, false);
2179         termPQExpBuffer(&buf);
2180         if (!res)
2181                 return false;
2182
2183         if (PQntuples(res) == 0 && !pset.quiet)
2184         {
2185                 if (pattern)
2186                         fprintf(pset.queryFout, _("No matching relations found.\n"));
2187                 else
2188                         fprintf(pset.queryFout, _("No relations found.\n"));
2189         }
2190         else
2191         {
2192                 myopt.nullPrint = NULL;
2193                 myopt.title = _("List of relations");
2194                 myopt.translate_header = true;
2195                 myopt.translate_columns = translate_columns;
2196
2197                 printQuery(res, &myopt, pset.queryFout, pset.logfile);
2198         }
2199
2200         PQclear(res);
2201         return true;
2202 }
2203
2204
2205 /*
2206  * \dD
2207  *
2208  * Describes domains.
2209  */
2210 bool
2211 listDomains(const char *pattern, bool showSystem)
2212 {
2213         PQExpBufferData buf;
2214         PGresult   *res;
2215         printQueryOpt myopt = pset.popt;
2216
2217         initPQExpBuffer(&buf);
2218
2219         printfPQExpBuffer(&buf,
2220                                           "SELECT n.nspname as \"%s\",\n"
2221                                           "       t.typname as \"%s\",\n"
2222          "       pg_catalog.format_type(t.typbasetype, t.typtypmod) as \"%s\",\n"
2223                                           "       CASE WHEN t.typnotnull AND t.typdefault IS NOT NULL THEN 'not null default '||t.typdefault\n"
2224         "            WHEN t.typnotnull AND t.typdefault IS NULL THEN 'not null'\n"
2225                                           "            WHEN NOT t.typnotnull AND t.typdefault IS NOT NULL THEN 'default '||t.typdefault\n"
2226                                           "            ELSE ''\n"
2227                                           "       END as \"%s\",\n"
2228                                           "       pg_catalog.array_to_string(ARRAY(\n"
2229                                           "         SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM pg_catalog.pg_constraint r WHERE t.oid = r.contypid\n"
2230                                           "       ), ' ') as \"%s\"\n"
2231                                           "FROM pg_catalog.pg_type t\n"
2232            "     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n"
2233                                           "WHERE t.typtype = 'd'\n",
2234                                           gettext_noop("Schema"),
2235                                           gettext_noop("Name"),
2236                                           gettext_noop("Type"),
2237                                           gettext_noop("Modifier"),
2238                                           gettext_noop("Check"));
2239
2240         if (!showSystem && !pattern)
2241                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
2242                                                                 "      AND n.nspname <> 'information_schema'\n");
2243
2244         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2245                                                   "n.nspname", "t.typname", NULL,
2246                                                   "pg_catalog.pg_type_is_visible(t.oid)");
2247
2248         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
2249
2250         res = PSQLexec(buf.data, false);
2251         termPQExpBuffer(&buf);
2252         if (!res)
2253                 return false;
2254
2255         myopt.nullPrint = NULL;
2256         myopt.title = _("List of domains");
2257         myopt.translate_header = true;
2258
2259         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2260
2261         PQclear(res);
2262         return true;
2263 }
2264
2265 /*
2266  * \dc
2267  *
2268  * Describes conversions.
2269  */
2270 bool
2271 listConversions(const char *pattern, bool showSystem)
2272 {
2273         PQExpBufferData buf;
2274         PGresult   *res;
2275         printQueryOpt myopt = pset.popt;
2276         static const bool translate_columns[] = {false, false, false, false, true};
2277
2278         initPQExpBuffer(&buf);
2279
2280         printfPQExpBuffer(&buf,
2281                                           "SELECT n.nspname AS \"%s\",\n"
2282                                           "       c.conname AS \"%s\",\n"
2283            "       pg_catalog.pg_encoding_to_char(c.conforencoding) AS \"%s\",\n"
2284                 "       pg_catalog.pg_encoding_to_char(c.contoencoding) AS \"%s\",\n"
2285                                           "       CASE WHEN c.condefault THEN '%s'\n"
2286                                           "       ELSE '%s' END AS \"%s\"\n"
2287                            "FROM pg_catalog.pg_conversion c, pg_catalog.pg_namespace n\n"
2288                                           "WHERE n.oid = c.connamespace\n",
2289                                           gettext_noop("Schema"),
2290                                           gettext_noop("Name"),
2291                                           gettext_noop("Source"),
2292                                           gettext_noop("Destination"),
2293                                           gettext_noop("yes"), gettext_noop("no"),
2294                                           gettext_noop("Default?"));
2295
2296         if (!showSystem && !pattern)
2297                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
2298                                                                 "      AND n.nspname <> 'information_schema'\n");
2299
2300         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2301                                                   "n.nspname", "c.conname", NULL,
2302                                                   "pg_catalog.pg_conversion_is_visible(c.oid)");
2303
2304         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
2305
2306         res = PSQLexec(buf.data, false);
2307         termPQExpBuffer(&buf);
2308         if (!res)
2309                 return false;
2310
2311         myopt.nullPrint = NULL;
2312         myopt.title = _("List of conversions");
2313         myopt.translate_header = true;
2314         myopt.translate_columns = translate_columns;
2315
2316         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2317
2318         PQclear(res);
2319         return true;
2320 }
2321
2322 /*
2323  * \dC
2324  *
2325  * Describes casts.
2326  */
2327 bool
2328 listCasts(const char *pattern)
2329 {
2330         PQExpBufferData buf;
2331         PGresult   *res;
2332         printQueryOpt myopt = pset.popt;
2333         static const bool translate_columns[] = {false, false, false, true};
2334
2335         initPQExpBuffer(&buf);
2336         /*
2337          * We need a left join to pg_proc for binary casts; the others are just
2338          * paranoia.  Also note that we don't attempt to localize '(binary
2339          * coercible)', because there's too much risk of gettext translating a
2340          * function name that happens to match some string in the PO database.
2341          */
2342         printfPQExpBuffer(&buf,
2343                            "SELECT pg_catalog.format_type(castsource, NULL) AS \"%s\",\n"
2344                            "       pg_catalog.format_type(casttarget, NULL) AS \"%s\",\n"
2345                                           "       CASE WHEN castfunc = 0 THEN '(binary coercible)'\n"
2346                                           "            ELSE p.proname\n"
2347                                           "       END as \"%s\",\n"
2348                                           "       CASE WHEN c.castcontext = 'e' THEN '%s'\n"
2349                                           "            WHEN c.castcontext = 'a' THEN '%s'\n"
2350                                           "            ELSE '%s'\n"
2351                                           "       END as \"%s\"\n"
2352                                  "FROM pg_catalog.pg_cast c LEFT JOIN pg_catalog.pg_proc p\n"
2353                                           "     ON c.castfunc = p.oid\n"
2354                                           "     LEFT JOIN pg_catalog.pg_type ts\n"
2355                                           "     ON c.castsource = ts.oid\n"
2356                                           "     LEFT JOIN pg_catalog.pg_namespace ns\n"
2357                                           "     ON ns.oid = ts.typnamespace\n"
2358                                           "     LEFT JOIN pg_catalog.pg_type tt\n"
2359                                           "     ON c.casttarget = tt.oid\n"
2360                                           "     LEFT JOIN pg_catalog.pg_namespace nt\n"
2361                                           "     ON nt.oid = tt.typnamespace\n"
2362                                           "WHERE (true",
2363                                           gettext_noop("Source type"),
2364                                           gettext_noop("Target type"),
2365                                           gettext_noop("Function"),
2366                                           gettext_noop("no"), gettext_noop("in assignment"), gettext_noop("yes"),
2367                                           gettext_noop("Implicit?"));
2368
2369         /*
2370          * Match name pattern against either internal or external name of either
2371          * castsource or casttarget
2372          */
2373         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2374                                                   "ns.nspname", "ts.typname",
2375                                                   "pg_catalog.format_type(ts.oid, NULL)",
2376                                                   "pg_catalog.pg_type_is_visible(ts.oid)");
2377
2378         appendPQExpBuffer(&buf, ") OR (true");
2379
2380         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2381                                                   "nt.nspname", "tt.typname",
2382                                                   "pg_catalog.format_type(tt.oid, NULL)",
2383                                                   "pg_catalog.pg_type_is_visible(tt.oid)");
2384
2385         appendPQExpBuffer(&buf, ")\nORDER BY 1, 2;");
2386
2387         res = PSQLexec(buf.data, false);
2388         termPQExpBuffer(&buf);
2389         if (!res)
2390                 return false;
2391
2392         myopt.nullPrint = NULL;
2393         myopt.title = _("List of casts");
2394         myopt.translate_header = true;
2395         myopt.translate_columns = translate_columns;
2396
2397         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2398
2399         PQclear(res);
2400         return true;
2401 }
2402
2403 /*
2404  * \dn
2405  *
2406  * Describes schemas (namespaces)
2407  */
2408 bool
2409 listSchemas(const char *pattern, bool verbose)
2410 {
2411         PQExpBufferData buf;
2412         PGresult   *res;
2413         printQueryOpt myopt = pset.popt;
2414
2415         initPQExpBuffer(&buf);
2416         printfPQExpBuffer(&buf,
2417                                           "SELECT n.nspname AS \"%s\",\n"
2418                                           "  pg_catalog.pg_get_userbyid(n.nspowner) AS \"%s\"",
2419                                           gettext_noop("Name"),
2420                                           gettext_noop("Owner"));
2421
2422         if (verbose)
2423         {
2424                 appendPQExpBuffer(&buf, ",\n  ");
2425                 printACLColumn(&buf, "n.nspacl");
2426                 appendPQExpBuffer(&buf,
2427                         ",\n  pg_catalog.obj_description(n.oid, 'pg_namespace') AS \"%s\"",
2428                                                   gettext_noop("Description"));
2429         }
2430
2431         appendPQExpBuffer(&buf,
2432                           "\nFROM pg_catalog.pg_namespace n\n"
2433                                           "WHERE        (n.nspname !~ '^pg_temp_' OR\n"
2434                    "             n.nspname = (pg_catalog.current_schemas(true))[1])\n");                /* temp schema is first */
2435
2436         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2437                                                   NULL, "n.nspname", NULL,
2438                                                   NULL);
2439
2440         appendPQExpBuffer(&buf, "ORDER BY 1;");
2441
2442         res = PSQLexec(buf.data, false);
2443         termPQExpBuffer(&buf);
2444         if (!res)
2445                 return false;
2446
2447         myopt.nullPrint = NULL;
2448         myopt.title = _("List of schemas");
2449         myopt.translate_header = true;
2450
2451         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2452
2453         PQclear(res);
2454         return true;
2455 }
2456
2457
2458 /*
2459  * \dFp
2460  * list text search parsers
2461  */
2462 bool
2463 listTSParsers(const char *pattern, bool verbose)
2464 {
2465         PQExpBufferData buf;
2466         PGresult   *res;
2467         printQueryOpt myopt = pset.popt;
2468
2469         if (pset.sversion < 80300)
2470         {
2471                 fprintf(stderr, _("The server (version %d.%d) does not support full text search.\n"),
2472                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
2473                 return true;
2474         }
2475
2476         if (verbose)
2477                 return listTSParsersVerbose(pattern);
2478
2479         initPQExpBuffer(&buf);
2480
2481         printfPQExpBuffer(&buf,
2482                                           "SELECT \n"
2483                                           "  n.nspname as \"%s\",\n"
2484                                           "  p.prsname as \"%s\",\n"
2485                         "  pg_catalog.obj_description(p.oid, 'pg_ts_parser') as \"%s\"\n"
2486                                           "FROM pg_catalog.pg_ts_parser p \n"
2487                    "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.prsnamespace\n",
2488                                           gettext_noop("Schema"),
2489                                           gettext_noop("Name"),
2490                                           gettext_noop("Description")
2491                 );
2492
2493         processSQLNamePattern(pset.db, &buf, pattern, false, false,
2494                                                   "n.nspname", "p.prsname", NULL,
2495                                                   "pg_catalog.pg_ts_parser_is_visible(p.oid)");
2496
2497         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
2498
2499         res = PSQLexec(buf.data, false);
2500         termPQExpBuffer(&buf);
2501         if (!res)
2502                 return false;
2503
2504         myopt.nullPrint = NULL;
2505         myopt.title = _("List of text search parsers");
2506         myopt.translate_header = true;
2507
2508         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2509
2510         PQclear(res);
2511         return true;
2512 }
2513
2514 /*
2515  * full description of parsers
2516  */
2517 static bool
2518 listTSParsersVerbose(const char *pattern)
2519 {
2520         PQExpBufferData buf;
2521         PGresult   *res;
2522         int                     i;
2523
2524         initPQExpBuffer(&buf);
2525
2526         printfPQExpBuffer(&buf,
2527                                           "SELECT p.oid, \n"
2528                                           "  n.nspname, \n"
2529                                           "  p.prsname \n"
2530                                           "FROM pg_catalog.pg_ts_parser p\n"
2531                         "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.prsnamespace\n"
2532                 );
2533
2534         processSQLNamePattern(pset.db, &buf, pattern, false, false,
2535                                                   "n.nspname", "p.prsname", NULL,
2536                                                   "pg_catalog.pg_ts_parser_is_visible(p.oid)");
2537
2538         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
2539
2540         res = PSQLexec(buf.data, false);
2541         termPQExpBuffer(&buf);
2542         if (!res)
2543                 return false;
2544
2545         if (PQntuples(res) == 0)
2546         {
2547                 if (!pset.quiet)
2548                         fprintf(stderr, _("Did not find any text search parser named \"%s\".\n"),
2549                                         pattern);
2550                 PQclear(res);
2551                 return false;
2552         }
2553
2554         for (i = 0; i < PQntuples(res); i++)
2555         {
2556                 const char *oid;
2557                 const char *nspname = NULL;
2558                 const char *prsname;
2559
2560                 oid = PQgetvalue(res, i, 0);
2561                 if (!PQgetisnull(res, i, 1))
2562                         nspname = PQgetvalue(res, i, 1);
2563                 prsname = PQgetvalue(res, i, 2);
2564
2565                 if (!describeOneTSParser(oid, nspname, prsname))
2566                 {
2567                         PQclear(res);
2568                         return false;
2569                 }
2570
2571                 if (cancel_pressed)
2572                 {
2573                         PQclear(res);
2574                         return false;
2575                 }
2576         }
2577
2578         PQclear(res);
2579         return true;
2580 }
2581
2582 static bool
2583 describeOneTSParser(const char *oid, const char *nspname, const char *prsname)
2584 {
2585         PQExpBufferData buf;
2586         PGresult   *res;
2587         char            title[1024];
2588         printQueryOpt myopt = pset.popt;
2589         static const bool translate_columns[] = {true, false, false};
2590
2591         initPQExpBuffer(&buf);
2592
2593         printfPQExpBuffer(&buf,
2594                                           "SELECT '%s' AS \"%s\", \n"
2595                                           "   p.prsstart::pg_catalog.regproc AS \"%s\", \n"
2596                   "   pg_catalog.obj_description(p.prsstart, 'pg_proc') as \"%s\" \n"
2597                                           " FROM pg_catalog.pg_ts_parser p \n"
2598                                           " WHERE p.oid = '%s' \n"
2599                                           "UNION ALL \n"
2600                                           "SELECT '%s', \n"
2601                                           "   p.prstoken::pg_catalog.regproc, \n"
2602                                         "   pg_catalog.obj_description(p.prstoken, 'pg_proc') \n"
2603                                           " FROM pg_catalog.pg_ts_parser p \n"
2604                                           " WHERE p.oid = '%s' \n"
2605                                           "UNION ALL \n"
2606                                           "SELECT '%s', \n"
2607                                           "   p.prsend::pg_catalog.regproc, \n"
2608                                           "   pg_catalog.obj_description(p.prsend, 'pg_proc') \n"
2609                                           " FROM pg_catalog.pg_ts_parser p \n"
2610                                           " WHERE p.oid = '%s' \n"
2611                                           "UNION ALL \n"
2612                                           "SELECT '%s', \n"
2613                                           "   p.prsheadline::pg_catalog.regproc, \n"
2614                                  "   pg_catalog.obj_description(p.prsheadline, 'pg_proc') \n"
2615                                           " FROM pg_catalog.pg_ts_parser p \n"
2616                                           " WHERE p.oid = '%s' \n"
2617                                           "UNION ALL \n"
2618                                           "SELECT '%s', \n"
2619                                           "   p.prslextype::pg_catalog.regproc, \n"
2620                                   "   pg_catalog.obj_description(p.prslextype, 'pg_proc') \n"
2621                                           " FROM pg_catalog.pg_ts_parser p \n"
2622                                           " WHERE p.oid = '%s' \n",
2623                                           gettext_noop("Start parse"),
2624                                           gettext_noop("Method"),
2625                                           gettext_noop("Function"),
2626                                           gettext_noop("Description"),
2627                                           oid,
2628                                           gettext_noop("Get next token"),
2629                                           oid,
2630                                           gettext_noop("End parse"),
2631                                           oid,
2632                                           gettext_noop("Get headline"),
2633                                           oid,
2634                                           gettext_noop("Get token types"),
2635                                           oid);
2636
2637         res = PSQLexec(buf.data, false);
2638         termPQExpBuffer(&buf);
2639         if (!res)
2640                 return false;
2641
2642         myopt.nullPrint = NULL;
2643         if (nspname)
2644                 sprintf(title, _("Text search parser \"%s.%s\""), nspname, prsname);
2645         else
2646                 sprintf(title, _("Text search parser \"%s\""), prsname);
2647         myopt.title = title;
2648         myopt.footers = NULL;
2649         myopt.default_footer = false;
2650         myopt.translate_header = true;
2651         myopt.translate_columns = translate_columns;
2652
2653         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2654
2655         PQclear(res);
2656
2657         initPQExpBuffer(&buf);
2658
2659         printfPQExpBuffer(&buf,
2660                                           "SELECT t.alias as \"%s\", \n"
2661                                           "  t.description as \"%s\" \n"
2662                           "FROM pg_catalog.ts_token_type( '%s'::pg_catalog.oid ) as t \n"
2663                                           "ORDER BY 1;",
2664                                           gettext_noop("Token name"),
2665                                           gettext_noop("Description"),
2666                                           oid);
2667
2668         res = PSQLexec(buf.data, false);
2669         termPQExpBuffer(&buf);
2670         if (!res)
2671                 return false;
2672
2673         myopt.nullPrint = NULL;
2674         if (nspname)
2675                 sprintf(title, _("Token types for parser \"%s.%s\""), nspname, prsname);
2676         else
2677                 sprintf(title, _("Token types for parser \"%s\""), prsname);
2678         myopt.title = title;
2679         myopt.footers = NULL;
2680         myopt.default_footer = true;
2681         myopt.translate_header = true;
2682         myopt.translate_columns = NULL;
2683
2684         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2685
2686         PQclear(res);
2687         return true;
2688 }
2689
2690
2691 /*
2692  * \dFd
2693  * list text search dictionaries
2694  */
2695 bool
2696 listTSDictionaries(const char *pattern, bool verbose)
2697 {
2698         PQExpBufferData buf;
2699         PGresult   *res;
2700         printQueryOpt myopt = pset.popt;
2701
2702         if (pset.sversion < 80300)
2703         {
2704                 fprintf(stderr, _("The server (version %d.%d) does not support full text search.\n"),
2705                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
2706                 return true;
2707         }
2708
2709         initPQExpBuffer(&buf);
2710
2711         printfPQExpBuffer(&buf,
2712                                           "SELECT \n"
2713                                           "  n.nspname as \"%s\",\n"
2714                                           "  d.dictname as \"%s\",\n",
2715                                           gettext_noop("Schema"),
2716                                           gettext_noop("Name"));
2717
2718         if (verbose)
2719         {
2720                 appendPQExpBuffer(&buf,
2721                                                   "  ( SELECT COALESCE(nt.nspname, '(null)')::pg_catalog.text || '.' || t.tmplname FROM \n"
2722                                                   "    pg_catalog.pg_ts_template t \n"
2723                                                   "                      LEFT JOIN pg_catalog.pg_namespace nt ON nt.oid = t.tmplnamespace \n"
2724                                                   "                      WHERE d.dicttemplate = t.oid ) AS  \"%s\", \n"
2725                                                   "  d.dictinitoption as \"%s\", \n",
2726                                                   gettext_noop("Template"),
2727                                                   gettext_noop("Init options"));
2728         }
2729
2730         appendPQExpBuffer(&buf,
2731                          "  pg_catalog.obj_description(d.oid, 'pg_ts_dict') as \"%s\"\n",
2732                                           gettext_noop("Description"));
2733
2734         appendPQExpBuffer(&buf, "FROM pg_catalog.pg_ts_dict d\n"
2735                  "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = d.dictnamespace\n");
2736
2737         processSQLNamePattern(pset.db, &buf, pattern, false, false,
2738                                                   "n.nspname", "d.dictname", NULL,
2739                                                   "pg_catalog.pg_ts_dict_is_visible(d.oid)");
2740
2741         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
2742
2743         res = PSQLexec(buf.data, false);
2744         termPQExpBuffer(&buf);
2745         if (!res)
2746                 return false;
2747
2748         myopt.nullPrint = NULL;
2749         myopt.title = _("List of text search dictionaries");
2750         myopt.translate_header = true;
2751
2752         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2753
2754         PQclear(res);
2755         return true;
2756 }
2757
2758
2759 /*
2760  * \dFt
2761  * list text search templates
2762  */
2763 bool
2764 listTSTemplates(const char *pattern, bool verbose)
2765 {
2766         PQExpBufferData buf;
2767         PGresult   *res;
2768         printQueryOpt myopt = pset.popt;
2769
2770         if (pset.sversion < 80300)
2771         {
2772                 fprintf(stderr, _("The server (version %d.%d) does not support full text search.\n"),
2773                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
2774                 return true;
2775         }
2776
2777         initPQExpBuffer(&buf);
2778
2779         if (verbose)
2780                 printfPQExpBuffer(&buf,
2781                                                   "SELECT \n"
2782                                                   "  n.nspname AS \"%s\",\n"
2783                                                   "  t.tmplname AS \"%s\",\n"
2784                                                   "  t.tmplinit::pg_catalog.regproc AS \"%s\",\n"
2785                                                   "  t.tmpllexize::pg_catalog.regproc AS \"%s\",\n"
2786                  "  pg_catalog.obj_description(t.oid, 'pg_ts_template') AS \"%s\"\n",
2787                                                   gettext_noop("Schema"),
2788                                                   gettext_noop("Name"),
2789                                                   gettext_noop("Init"),
2790                                                   gettext_noop("Lexize"),
2791                                                   gettext_noop("Description"));
2792         else
2793                 printfPQExpBuffer(&buf,
2794                                                   "SELECT \n"
2795                                                   "  n.nspname AS \"%s\",\n"
2796                                                   "  t.tmplname AS \"%s\",\n"
2797                  "  pg_catalog.obj_description(t.oid, 'pg_ts_template') AS \"%s\"\n",
2798                                                   gettext_noop("Schema"),
2799                                                   gettext_noop("Name"),
2800                                                   gettext_noop("Description"));
2801
2802         appendPQExpBuffer(&buf, "FROM pg_catalog.pg_ts_template t\n"
2803                  "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.tmplnamespace\n");
2804
2805         processSQLNamePattern(pset.db, &buf, pattern, false, false,
2806                                                   "n.nspname", "t.tmplname", NULL,
2807                                                   "pg_catalog.pg_ts_template_is_visible(t.oid)");
2808
2809         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
2810
2811         res = PSQLexec(buf.data, false);
2812         termPQExpBuffer(&buf);
2813         if (!res)
2814                 return false;
2815
2816         myopt.nullPrint = NULL;
2817         myopt.title = _("List of text search templates");
2818         myopt.translate_header = true;
2819
2820         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2821
2822         PQclear(res);
2823         return true;
2824 }
2825
2826
2827 /*
2828  * \dF
2829  * list text search configurations
2830  */
2831 bool
2832 listTSConfigs(const char *pattern, bool verbose)
2833 {
2834         PQExpBufferData buf;
2835         PGresult   *res;
2836         printQueryOpt myopt = pset.popt;
2837
2838         if (pset.sversion < 80300)
2839         {
2840                 fprintf(stderr, _("The server (version %d.%d) does not support full text search.\n"),
2841                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
2842                 return true;
2843         }
2844
2845         if (verbose)
2846                 return listTSConfigsVerbose(pattern);
2847
2848         initPQExpBuffer(&buf);
2849
2850         printfPQExpBuffer(&buf,
2851                                           "SELECT \n"
2852                                           "   n.nspname as \"%s\",\n"
2853                                           "   c.cfgname as \"%s\",\n"
2854                    "   pg_catalog.obj_description(c.oid, 'pg_ts_config') as \"%s\"\n"
2855                                           "FROM pg_catalog.pg_ts_config c\n"
2856                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.cfgnamespace \n",
2857                                           gettext_noop("Schema"),
2858                                           gettext_noop("Name"),
2859                                           gettext_noop("Description")
2860                 );
2861
2862         processSQLNamePattern(pset.db, &buf, pattern, false, false,
2863                                                   "n.nspname", "c.cfgname", NULL,
2864                                                   "pg_catalog.pg_ts_config_is_visible(c.oid)");
2865
2866         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
2867
2868         res = PSQLexec(buf.data, false);
2869         termPQExpBuffer(&buf);
2870         if (!res)
2871                 return false;
2872
2873         myopt.nullPrint = NULL;
2874         myopt.title = _("List of text search configurations");
2875         myopt.translate_header = true;
2876
2877         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2878
2879         PQclear(res);
2880         return true;
2881 }
2882
2883 static bool
2884 listTSConfigsVerbose(const char *pattern)
2885 {
2886         PQExpBufferData buf;
2887         PGresult   *res;
2888         int                     i;
2889
2890         initPQExpBuffer(&buf);
2891
2892         printfPQExpBuffer(&buf,
2893                                           "SELECT c.oid, c.cfgname,\n"
2894                                           "   n.nspname, \n"
2895                                           "   p.prsname, \n"
2896                                           "   np.nspname as pnspname \n"
2897                                           "FROM pg_catalog.pg_ts_config c \n"
2898            "   LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.cfgnamespace, \n"
2899                                           " pg_catalog.pg_ts_parser p \n"
2900           "   LEFT JOIN pg_catalog.pg_namespace np ON np.oid = p.prsnamespace \n"
2901                                           "WHERE  p.oid = c.cfgparser\n"
2902                 );
2903
2904         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2905                                                   "n.nspname", "c.cfgname", NULL,
2906                                                   "pg_catalog.pg_ts_config_is_visible(c.oid)");
2907
2908         appendPQExpBuffer(&buf, "ORDER BY 3, 2;");
2909
2910         res = PSQLexec(buf.data, false);
2911         termPQExpBuffer(&buf);
2912         if (!res)
2913                 return false;
2914
2915         if (PQntuples(res) == 0)
2916         {
2917                 if (!pset.quiet)
2918                         fprintf(stderr, _("Did not find any text search configuration named \"%s\".\n"),
2919                                         pattern);
2920                 PQclear(res);
2921                 return false;
2922         }
2923
2924         for (i = 0; i < PQntuples(res); i++)
2925         {
2926                 const char *oid;
2927                 const char *cfgname;
2928                 const char *nspname = NULL;
2929                 const char *prsname;
2930                 const char *pnspname = NULL;
2931
2932                 oid = PQgetvalue(res, i, 0);
2933                 cfgname = PQgetvalue(res, i, 1);
2934                 if (!PQgetisnull(res, i, 2))
2935                         nspname = PQgetvalue(res, i, 2);
2936                 prsname = PQgetvalue(res, i, 3);
2937                 if (!PQgetisnull(res, i, 4))
2938                         pnspname = PQgetvalue(res, i, 4);
2939
2940                 if (!describeOneTSConfig(oid, nspname, cfgname, pnspname, prsname))
2941                 {
2942                         PQclear(res);
2943                         return false;
2944                 }
2945
2946                 if (cancel_pressed)
2947                 {
2948                         PQclear(res);
2949                         return false;
2950                 }
2951         }
2952
2953         PQclear(res);
2954         return true;
2955 }
2956
2957 static bool
2958 describeOneTSConfig(const char *oid, const char *nspname, const char *cfgname,
2959                                         const char *pnspname, const char *prsname)
2960 {
2961         PQExpBufferData buf,
2962                                 title;
2963         PGresult   *res;
2964         printQueryOpt myopt = pset.popt;
2965
2966         initPQExpBuffer(&buf);
2967
2968         printfPQExpBuffer(&buf,
2969                                           "SELECT \n"
2970                                           "  ( SELECT t.alias FROM \n"
2971                                           "    pg_catalog.ts_token_type(c.cfgparser) AS t \n"
2972                                           "    WHERE t.tokid = m.maptokentype ) AS \"%s\", \n"
2973                                           "  pg_catalog.btrim( \n"
2974                                   "    ARRAY( SELECT mm.mapdict::pg_catalog.regdictionary \n"
2975                                           "           FROM pg_catalog.pg_ts_config_map AS mm \n"
2976                                           "           WHERE mm.mapcfg = m.mapcfg AND mm.maptokentype = m.maptokentype \n"
2977                                           "           ORDER BY mapcfg, maptokentype, mapseqno \n"
2978                                           "    ) :: pg_catalog.text , \n"
2979                                           "  '{}') AS \"%s\" \n"
2980          "FROM pg_catalog.pg_ts_config AS c, pg_catalog.pg_ts_config_map AS m \n"
2981                                           "WHERE c.oid = '%s' AND m.mapcfg = c.oid \n"
2982                                           "GROUP BY m.mapcfg, m.maptokentype, c.cfgparser \n"
2983                                           "ORDER BY 1",
2984                                           gettext_noop("Token"),
2985                                           gettext_noop("Dictionaries"),
2986                                           oid);
2987
2988         res = PSQLexec(buf.data, false);
2989         termPQExpBuffer(&buf);
2990         if (!res)
2991                 return false;
2992
2993         initPQExpBuffer(&title);
2994
2995         if (nspname)
2996                 appendPQExpBuffer(&title, _("Text search configuration \"%s.%s\""),
2997                                                   nspname, cfgname);
2998         else
2999                 appendPQExpBuffer(&title, _("Text search configuration \"%s\""),
3000                                                   cfgname);
3001
3002         if (pnspname)
3003                 appendPQExpBuffer(&title, _("\nParser: \"%s.%s\""),
3004                                                   pnspname, prsname);
3005         else
3006                 appendPQExpBuffer(&title, _("\nParser: \"%s\""),
3007                                                   prsname);
3008
3009         myopt.nullPrint = NULL;
3010         myopt.title = title.data;
3011         myopt.footers = NULL;
3012         myopt.default_footer = false;
3013         myopt.translate_header = true;
3014
3015         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3016
3017         termPQExpBuffer(&title);
3018
3019         PQclear(res);
3020         return true;
3021 }
3022
3023
3024 /*
3025  * \dew
3026  *
3027  * Describes foreign-data wrappers
3028  */
3029 bool
3030 listForeignDataWrappers(const char *pattern, bool verbose)
3031 {
3032         PQExpBufferData buf;
3033         PGresult   *res;
3034         printQueryOpt myopt = pset.popt;
3035
3036         if (pset.sversion < 80400)
3037         {
3038                 fprintf(stderr, _("The server (version %d.%d) does not support foreign-data wrappers.\n"),
3039                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3040                 return true;
3041         }
3042
3043         initPQExpBuffer(&buf);
3044         printfPQExpBuffer(&buf,
3045                                           "SELECT fdwname AS \"%s\",\n"
3046                                           "  pg_catalog.pg_get_userbyid(fdwowner) AS \"%s\",\n"
3047                                           "  fdwvalidator::pg_catalog.regproc AS \"%s\"",
3048                                           gettext_noop("Name"),
3049                                           gettext_noop("Owner"),
3050                                           gettext_noop("Validator"));
3051
3052         if (verbose)
3053         {
3054                 appendPQExpBuffer(&buf, ",\n  ");
3055                 printACLColumn(&buf, "fdwacl");
3056                 appendPQExpBuffer(&buf,
3057                                                   ",\n  fdwoptions AS \"%s\"",
3058                                                   gettext_noop("Options"));
3059         }
3060
3061         appendPQExpBuffer(&buf, "\nFROM pg_catalog.pg_foreign_data_wrapper\n");
3062
3063         processSQLNamePattern(pset.db, &buf, pattern, false, false,
3064                                                   NULL, "fdwname", NULL, NULL);
3065
3066         appendPQExpBuffer(&buf, "ORDER BY 1;");
3067
3068         res = PSQLexec(buf.data, false);
3069         termPQExpBuffer(&buf);
3070         if (!res)
3071                 return false;
3072
3073         myopt.nullPrint = NULL;
3074         myopt.title = _("List of foreign-data wrappers");
3075         myopt.translate_header = true;
3076
3077         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3078
3079         PQclear(res);
3080         return true;
3081 }
3082
3083 /*
3084  * \des
3085  *
3086  * Describes foreign servers.
3087  */
3088 bool
3089 listForeignServers(const char *pattern, bool verbose)
3090 {
3091         PQExpBufferData buf;
3092         PGresult   *res;
3093         printQueryOpt myopt = pset.popt;
3094
3095         if (pset.sversion < 80400)
3096         {
3097                 fprintf(stderr, _("The server (version %d.%d) does not support foreign servers.\n"),
3098                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3099                 return true;
3100         }
3101
3102         initPQExpBuffer(&buf);
3103         printfPQExpBuffer(&buf,
3104                                           "SELECT s.srvname AS \"%s\",\n"
3105                                           "  pg_catalog.pg_get_userbyid(s.srvowner) AS \"%s\",\n"
3106                                           "  f.fdwname AS \"%s\"",
3107                                           gettext_noop("Name"),
3108                                           gettext_noop("Owner"),
3109                                           gettext_noop("Foreign-data wrapper"));
3110
3111         if (verbose)
3112         {
3113                 appendPQExpBuffer(&buf, ",\n  ");
3114                 printACLColumn(&buf, "s.srvacl");
3115                 appendPQExpBuffer(&buf,
3116                                                   ",\n"
3117                                                   "  s.srvtype AS \"%s\",\n"
3118                                                   "  s.srvversion AS \"%s\",\n"
3119                                                   "  s.srvoptions AS \"%s\"",
3120                                                   gettext_noop("Type"),
3121                                                   gettext_noop("Version"),
3122                                                   gettext_noop("Options"));
3123         }
3124
3125         appendPQExpBuffer(&buf,
3126                                           "\nFROM pg_catalog.pg_foreign_server s\n"
3127                                           "     JOIN pg_catalog.pg_foreign_data_wrapper f ON f.oid=s.srvfdw\n");
3128
3129         processSQLNamePattern(pset.db, &buf, pattern, false, false,
3130                                                   NULL, "s.srvname", NULL, NULL);
3131
3132         appendPQExpBuffer(&buf, "ORDER BY 1;");
3133
3134         res = PSQLexec(buf.data, false);
3135         termPQExpBuffer(&buf);
3136         if (!res)
3137                 return false;
3138
3139         myopt.nullPrint = NULL;
3140         myopt.title = _("List of foreign servers");
3141         myopt.translate_header = true;
3142
3143         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3144
3145         PQclear(res);
3146         return true;
3147 }
3148
3149 /*
3150  * \deu
3151  *
3152  * Describes user mappings.
3153  */
3154 bool
3155 listUserMappings(const char *pattern, bool verbose)
3156 {
3157         PQExpBufferData buf;
3158         PGresult   *res;
3159         printQueryOpt myopt = pset.popt;
3160
3161         if (pset.sversion < 80400)
3162         {
3163                 fprintf(stderr, _("The server (version %d.%d) does not support user mappings.\n"),
3164                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3165                 return true;
3166         }
3167
3168         initPQExpBuffer(&buf);
3169         printfPQExpBuffer(&buf,
3170                                           "SELECT um.srvname AS \"%s\",\n"
3171                                           "  um.usename AS \"%s\"",
3172                                           gettext_noop("Server"),
3173                                           gettext_noop("User name"));
3174
3175         if (verbose)
3176                 appendPQExpBuffer(&buf,
3177                                                   ",\n  um.umoptions AS \"%s\"",
3178                                                   gettext_noop("Options"));
3179
3180         appendPQExpBuffer(&buf, "\nFROM pg_catalog.pg_user_mappings um\n");
3181
3182         processSQLNamePattern(pset.db, &buf, pattern, false, false,
3183                                                   NULL, "um.srvname", "um.usename", NULL);
3184
3185         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
3186
3187         res = PSQLexec(buf.data, false);
3188         termPQExpBuffer(&buf);
3189         if (!res)
3190                 return false;
3191
3192         myopt.nullPrint = NULL;
3193         myopt.title = _("List of user mappings");
3194         myopt.translate_header = true;
3195
3196         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3197
3198         PQclear(res);
3199         return true;
3200 }
3201
3202 /*
3203  * printACLColumn
3204  *
3205  * Helper function for consistently formatting ACL (privilege) columns.
3206  * The proper targetlist entry is appended to buf.  Note lack of any
3207  * whitespace or comma decoration.
3208  */
3209 static void
3210 printACLColumn(PQExpBuffer buf, const char *colname)
3211 {
3212         if (pset.sversion >= 80100)
3213                 appendPQExpBuffer(buf,
3214                                                   "pg_catalog.array_to_string(%s, E'\\n') AS \"%s\"",
3215                                                   colname, gettext_noop("Access privileges"));
3216         else
3217                 appendPQExpBuffer(buf,
3218                                                   "pg_catalog.array_to_string(%s, '\\n') AS \"%s\"",
3219                                                   colname, gettext_noop("Access privileges"));
3220 }