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