]> granicus.if.org Git - postgresql/blob - src/bin/psql/describe.c
Mark operator implementation functions as such in their comments.
[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'\n",
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'\n",
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'\n",
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 collname FROM pg_collation WHERE oid = a.attcollation AND collname <> 'default') AS attcollation");
1293         else
1294                 appendPQExpBuffer(&buf, ",\n  NULL AS attcollation");
1295         if (tableinfo.relkind == 'i')
1296                 appendPQExpBuffer(&buf, ",\n  pg_catalog.pg_get_indexdef(a.attrelid, a.attnum, TRUE) AS indexdef");
1297         if (verbose)
1298                 appendPQExpBuffer(&buf, ",\n  a.attstorage, pg_catalog.col_description(a.attrelid, a.attnum)");
1299         appendPQExpBuffer(&buf, "\nFROM pg_catalog.pg_attribute a");
1300         appendPQExpBuffer(&buf, "\nWHERE a.attrelid = '%s' AND a.attnum > 0 AND NOT a.attisdropped", oid);
1301         appendPQExpBuffer(&buf, "\nORDER BY a.attnum");
1302
1303         res = PSQLexec(buf.data, false);
1304         if (!res)
1305                 goto error_return;
1306         numrows = PQntuples(res);
1307
1308         /* Make title */
1309         switch (tableinfo.relkind)
1310         {
1311                 case 'r':
1312                         if (tableinfo.relpersistence == 'u')
1313                                 printfPQExpBuffer(&title, _("Unlogged table \"%s.%s\""),
1314                                                                   schemaname, relationname);
1315                         else
1316                                 printfPQExpBuffer(&title, _("Table \"%s.%s\""),
1317                                                                   schemaname, relationname);
1318                         break;
1319                 case 'v':
1320                         printfPQExpBuffer(&title, _("View \"%s.%s\""),
1321                                                           schemaname, relationname);
1322                         break;
1323                 case 'S':
1324                         printfPQExpBuffer(&title, _("Sequence \"%s.%s\""),
1325                                                           schemaname, relationname);
1326                         break;
1327                 case 'i':
1328                         if (tableinfo.relpersistence == 'u')
1329                                 printfPQExpBuffer(&title, _("Unlogged index \"%s.%s\""),
1330                                                                   schemaname, relationname);
1331                         else
1332                                 printfPQExpBuffer(&title, _("Index \"%s.%s\""),
1333                                                                   schemaname, relationname);
1334                         break;
1335                 case 's':
1336                         /* not used as of 8.2, but keep it for backwards compatibility */
1337                         printfPQExpBuffer(&title, _("Special relation \"%s.%s\""),
1338                                                           schemaname, relationname);
1339                         break;
1340                 case 't':
1341                         printfPQExpBuffer(&title, _("TOAST table \"%s.%s\""),
1342                                                           schemaname, relationname);
1343                         break;
1344                 case 'c':
1345                         printfPQExpBuffer(&title, _("Composite type \"%s.%s\""),
1346                                                           schemaname, relationname);
1347                         break;
1348                 case 'f':
1349                         printfPQExpBuffer(&title, _("Foreign table \"%s.%s\""),
1350                                                           schemaname, relationname);
1351                         break;
1352                 default:
1353                         /* untranslated unknown relkind */
1354                         printfPQExpBuffer(&title, "?%c? \"%s.%s\"",
1355                                                           tableinfo.relkind, schemaname, relationname);
1356                         break;
1357         }
1358
1359         /* Set the number of columns, and their names */
1360         headers[0] = gettext_noop("Column");
1361         headers[1] = gettext_noop("Type");
1362         cols = 2;
1363
1364         if (tableinfo.relkind == 'r' || tableinfo.relkind == 'v' ||
1365                 tableinfo.relkind == 'f')
1366         {
1367                 show_modifiers = true;
1368                 headers[cols++] = gettext_noop("Modifiers");
1369                 modifiers = pg_malloc_zero((numrows + 1) * sizeof(*modifiers));
1370         }
1371
1372         if (tableinfo.relkind == 'S')
1373                 headers[cols++] = gettext_noop("Value");
1374
1375         if (tableinfo.relkind == 'i')
1376                 headers[cols++] = gettext_noop("Definition");
1377
1378         if (verbose)
1379         {
1380                 headers[cols++] = gettext_noop("Storage");
1381                 headers[cols++] = gettext_noop("Description");
1382         }
1383
1384         printTableInit(&cont, &myopt, title.data, cols, numrows);
1385         printTableInitialized = true;
1386
1387         for (i = 0; i < cols; i++)
1388                 printTableAddHeader(&cont, headers[i], true, 'l');
1389
1390         /* Check if table is a view */
1391         if (tableinfo.relkind == 'v' && verbose)
1392         {
1393                 PGresult   *result;
1394
1395                 printfPQExpBuffer(&buf,
1396                           "SELECT pg_catalog.pg_get_viewdef('%s'::pg_catalog.oid, true)",
1397                                                   oid);
1398                 result = PSQLexec(buf.data, false);
1399                 if (!result)
1400                         goto error_return;
1401
1402                 if (PQntuples(result) > 0)
1403                         view_def = pg_strdup(PQgetvalue(result, 0, 0));
1404
1405                 PQclear(result);
1406         }
1407
1408         /* Generate table cells to be printed */
1409         for (i = 0; i < numrows; i++)
1410         {
1411                 /* Column */
1412                 printTableAddCell(&cont, PQgetvalue(res, i, 0), false, false);
1413
1414                 /* Type */
1415                 printTableAddCell(&cont, PQgetvalue(res, i, 1), false, false);
1416
1417                 /* Modifiers: collate, not null, default */
1418                 if (show_modifiers)
1419                 {
1420                         resetPQExpBuffer(&tmpbuf);
1421
1422                         if (!PQgetisnull(res, i, 5))
1423                         {
1424                                 if (tmpbuf.len > 0)
1425                                         appendPQExpBufferStr(&tmpbuf, " ");
1426                                 appendPQExpBuffer(&tmpbuf, _("collate %s"),
1427                                                                   PQgetvalue(res, i, 5));
1428                         }
1429
1430                         if (strcmp(PQgetvalue(res, i, 3), "t") == 0)
1431                         {
1432                                 if (tmpbuf.len > 0)
1433                                         appendPQExpBufferStr(&tmpbuf, " ");
1434                                 appendPQExpBufferStr(&tmpbuf, _("not null"));
1435                         }
1436
1437                         /* handle "default" here */
1438                         /* (note: above we cut off the 'default' string at 128) */
1439                         if (strlen(PQgetvalue(res, i, 2)) != 0)
1440                         {
1441                                 if (tmpbuf.len > 0)
1442                                         appendPQExpBufferStr(&tmpbuf, " ");
1443                                 /* translator: default values of column definitions */
1444                                 appendPQExpBuffer(&tmpbuf, _("default %s"),
1445                                                                   PQgetvalue(res, i, 2));
1446                         }
1447
1448                         modifiers[i] = pg_strdup(tmpbuf.data);
1449                         printTableAddCell(&cont, modifiers[i], false, false);
1450                 }
1451
1452                 /* Value: for sequences only */
1453                 if (tableinfo.relkind == 'S')
1454                         printTableAddCell(&cont, seq_values[i], false, false);
1455
1456                 /* Expression for index column */
1457                 if (tableinfo.relkind == 'i')
1458                         printTableAddCell(&cont, PQgetvalue(res, i, 6), false, false);
1459
1460                 /* Storage and Description */
1461                 if (verbose)
1462                 {
1463                         int                     firstvcol = (tableinfo.relkind == 'i' ? 7 : 6);
1464                         char       *storage = PQgetvalue(res, i, firstvcol);
1465
1466                         /* these strings are literal in our syntax, so not translated. */
1467                         printTableAddCell(&cont, (storage[0] == 'p' ? "plain" :
1468                                                                           (storage[0] == 'm' ? "main" :
1469                                                                            (storage[0] == 'x' ? "extended" :
1470                                                                                 (storage[0] == 'e' ? "external" :
1471                                                                                  "???")))),
1472                                                           false, false);
1473                         printTableAddCell(&cont, PQgetvalue(res, i, firstvcol + 1),
1474                                                           false, false);
1475                 }
1476         }
1477
1478         /* Make footers */
1479         if (tableinfo.relkind == 'i')
1480         {
1481                 /* Footer information about an index */
1482                 PGresult   *result;
1483
1484                 printfPQExpBuffer(&buf,
1485                                  "SELECT i.indisunique, i.indisprimary, i.indisclustered, ");
1486                 if (pset.sversion >= 80200)
1487                         appendPQExpBuffer(&buf, "i.indisvalid,\n");
1488                 else
1489                         appendPQExpBuffer(&buf, "true AS indisvalid,\n");
1490                 if (pset.sversion >= 90000)
1491                         appendPQExpBuffer(&buf,
1492                                                           "  (NOT i.indimmediate) AND "
1493                                                         "EXISTS (SELECT 1 FROM pg_catalog.pg_constraint "
1494                                                           "WHERE conrelid = i.indrelid AND "
1495                                                           "conindid = i.indexrelid AND "
1496                                                           "contype IN ('p','u','x') AND "
1497                                                           "condeferrable) AS condeferrable,\n"
1498                                                           "  (NOT i.indimmediate) AND "
1499                                                         "EXISTS (SELECT 1 FROM pg_catalog.pg_constraint "
1500                                                           "WHERE conrelid = i.indrelid AND "
1501                                                           "conindid = i.indexrelid AND "
1502                                                           "contype IN ('p','u','x') AND "
1503                                                           "condeferred) AS condeferred,\n");
1504                 else
1505                         appendPQExpBuffer(&buf,
1506                                                 "  false AS condeferrable, false AS condeferred,\n");
1507                 appendPQExpBuffer(&buf, "  a.amname, c2.relname, "
1508                                           "pg_catalog.pg_get_expr(i.indpred, i.indrelid, true)\n"
1509                                                   "FROM pg_catalog.pg_index i, pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_am a\n"
1510                   "WHERE i.indexrelid = c.oid AND c.oid = '%s' AND c.relam = a.oid\n"
1511                                                   "AND i.indrelid = c2.oid",
1512                                                   oid);
1513
1514                 result = PSQLexec(buf.data, false);
1515                 if (!result)
1516                         goto error_return;
1517                 else if (PQntuples(result) != 1)
1518                 {
1519                         PQclear(result);
1520                         goto error_return;
1521                 }
1522                 else
1523                 {
1524                         char       *indisunique = PQgetvalue(result, 0, 0);
1525                         char       *indisprimary = PQgetvalue(result, 0, 1);
1526                         char       *indisclustered = PQgetvalue(result, 0, 2);
1527                         char       *indisvalid = PQgetvalue(result, 0, 3);
1528                         char       *deferrable = PQgetvalue(result, 0, 4);
1529                         char       *deferred = PQgetvalue(result, 0, 5);
1530                         char       *indamname = PQgetvalue(result, 0, 6);
1531                         char       *indtable = PQgetvalue(result, 0, 7);
1532                         char       *indpred = PQgetvalue(result, 0, 8);
1533
1534                         if (strcmp(indisprimary, "t") == 0)
1535                                 printfPQExpBuffer(&tmpbuf, _("primary key, "));
1536                         else if (strcmp(indisunique, "t") == 0)
1537                                 printfPQExpBuffer(&tmpbuf, _("unique, "));
1538                         else
1539                                 resetPQExpBuffer(&tmpbuf);
1540                         appendPQExpBuffer(&tmpbuf, "%s, ", indamname);
1541
1542                         /* we assume here that index and table are in same schema */
1543                         appendPQExpBuffer(&tmpbuf, _("for table \"%s.%s\""),
1544                                                           schemaname, indtable);
1545
1546                         if (strlen(indpred))
1547                                 appendPQExpBuffer(&tmpbuf, _(", predicate (%s)"), indpred);
1548
1549                         if (strcmp(indisclustered, "t") == 0)
1550                                 appendPQExpBuffer(&tmpbuf, _(", clustered"));
1551
1552                         if (strcmp(indisvalid, "t") != 0)
1553                                 appendPQExpBuffer(&tmpbuf, _(", invalid"));
1554
1555                         if (strcmp(deferrable, "t") == 0)
1556                                 appendPQExpBuffer(&tmpbuf, _(", deferrable"));
1557
1558                         if (strcmp(deferred, "t") == 0)
1559                                 appendPQExpBuffer(&tmpbuf, _(", initially deferred"));
1560
1561                         printTableAddFooter(&cont, tmpbuf.data);
1562                         add_tablespace_footer(&cont, tableinfo.relkind,
1563                                                                   tableinfo.tablespace, true);
1564                 }
1565
1566                 PQclear(result);
1567         }
1568         else if (view_def)
1569         {
1570                 PGresult   *result = NULL;
1571
1572                 /* Footer information about a view */
1573                 printTableAddFooter(&cont, _("View definition:"));
1574                 printTableAddFooter(&cont, view_def);
1575
1576                 /* print rules */
1577                 if (tableinfo.hasrules)
1578                 {
1579                         printfPQExpBuffer(&buf,
1580                                                           "SELECT r.rulename, trim(trailing ';' from pg_catalog.pg_get_ruledef(r.oid, true))\n"
1581                                                           "FROM pg_catalog.pg_rewrite r\n"
1582                         "WHERE r.ev_class = '%s' AND r.rulename != '_RETURN' ORDER BY 1",
1583                                                           oid);
1584                         result = PSQLexec(buf.data, false);
1585                         if (!result)
1586                                 goto error_return;
1587
1588                         if (PQntuples(result) > 0)
1589                         {
1590                                 printTableAddFooter(&cont, _("Rules:"));
1591                                 for (i = 0; i < PQntuples(result); i++)
1592                                 {
1593                                         const char *ruledef;
1594
1595                                         /* Everything after "CREATE RULE" is echoed verbatim */
1596                                         ruledef = PQgetvalue(result, i, 1);
1597                                         ruledef += 12;
1598
1599                                         printfPQExpBuffer(&buf, " %s", ruledef);
1600                                         printTableAddFooter(&cont, buf.data);
1601                                 }
1602                         }
1603                         PQclear(result);
1604                 }
1605         }
1606         else if (tableinfo.relkind == 'r' || tableinfo.relkind == 'f')
1607         {
1608                 /* Footer information about a table */
1609                 PGresult   *result = NULL;
1610                 int                     tuples = 0;
1611
1612                 /* print indexes */
1613                 if (tableinfo.hasindex)
1614                 {
1615                         printfPQExpBuffer(&buf,
1616                                                           "SELECT c2.relname, i.indisprimary, i.indisunique, i.indisclustered, ");
1617                         if (pset.sversion >= 80200)
1618                                 appendPQExpBuffer(&buf, "i.indisvalid, ");
1619                         else
1620                                 appendPQExpBuffer(&buf, "true as indisvalid, ");
1621                         appendPQExpBuffer(&buf, "pg_catalog.pg_get_indexdef(i.indexrelid, 0, true),\n  ");
1622                         if (pset.sversion >= 90000)
1623                                 appendPQExpBuffer(&buf,
1624                                                    "pg_catalog.pg_get_constraintdef(con.oid, true), "
1625                                                                   "contype, condeferrable, condeferred");
1626                         else
1627                                 appendPQExpBuffer(&buf,
1628                                                                   "null AS constraintdef, null AS contype, "
1629                                                          "false AS condeferrable, false AS condeferred");
1630                         if (pset.sversion >= 80000)
1631                                 appendPQExpBuffer(&buf, ", c2.reltablespace");
1632                         appendPQExpBuffer(&buf,
1633                                                           "\nFROM pg_catalog.pg_class c, pg_catalog.pg_class c2, pg_catalog.pg_index i\n");
1634                         if (pset.sversion >= 90000)
1635                                 appendPQExpBuffer(&buf,
1636                                                                   "  LEFT JOIN pg_catalog.pg_constraint con ON (conrelid = i.indrelid AND conindid = i.indexrelid AND contype IN ('p','u','x'))\n");
1637                         appendPQExpBuffer(&buf,
1638                                                           "WHERE c.oid = '%s' AND c.oid = i.indrelid AND i.indexrelid = c2.oid\n"
1639                           "ORDER BY i.indisprimary DESC, i.indisunique DESC, c2.relname",
1640                                                           oid);
1641                         result = PSQLexec(buf.data, false);
1642                         if (!result)
1643                                 goto error_return;
1644                         else
1645                                 tuples = PQntuples(result);
1646
1647                         if (tuples > 0)
1648                         {
1649                                 printTableAddFooter(&cont, _("Indexes:"));
1650                                 for (i = 0; i < tuples; i++)
1651                                 {
1652                                         /* untranslated index name */
1653                                         printfPQExpBuffer(&buf, "    \"%s\"",
1654                                                                           PQgetvalue(result, i, 0));
1655
1656                                         /* If exclusion constraint, print the constraintdef */
1657                                         if (strcmp(PQgetvalue(result, i, 7), "x") == 0)
1658                                         {
1659                                                 appendPQExpBuffer(&buf, " %s",
1660                                                                                   PQgetvalue(result, i, 6));
1661                                         }
1662                                         else
1663                                         {
1664                                                 const char *indexdef;
1665                                                 const char *usingpos;
1666
1667                                                 /* Label as primary key or unique (but not both) */
1668                                                 if (strcmp(PQgetvalue(result, i, 1), "t") == 0)
1669                                                         appendPQExpBuffer(&buf, " PRIMARY KEY,");
1670                                                 else if (strcmp(PQgetvalue(result, i, 2), "t") == 0)
1671                                                 {
1672                                                         if (strcmp(PQgetvalue(result, i, 7), "u") == 0)
1673                                                                 appendPQExpBuffer(&buf, " UNIQUE CONSTRAINT,");
1674                                                         else
1675                                                                 appendPQExpBuffer(&buf, " UNIQUE,");
1676                                                 }
1677
1678                                                 /* Everything after "USING" is echoed verbatim */
1679                                                 indexdef = PQgetvalue(result, i, 5);
1680                                                 usingpos = strstr(indexdef, " USING ");
1681                                                 if (usingpos)
1682                                                         indexdef = usingpos + 7;
1683                                                 appendPQExpBuffer(&buf, " %s", indexdef);
1684
1685                                                 /* Need these for deferrable PK/UNIQUE indexes */
1686                                                 if (strcmp(PQgetvalue(result, i, 8), "t") == 0)
1687                                                         appendPQExpBuffer(&buf, " DEFERRABLE");
1688
1689                                                 if (strcmp(PQgetvalue(result, i, 9), "t") == 0)
1690                                                         appendPQExpBuffer(&buf, " INITIALLY DEFERRED");
1691                                         }
1692
1693                                         /* Add these for all cases */
1694                                         if (strcmp(PQgetvalue(result, i, 3), "t") == 0)
1695                                                 appendPQExpBuffer(&buf, " CLUSTER");
1696
1697                                         if (strcmp(PQgetvalue(result, i, 4), "t") != 0)
1698                                                 appendPQExpBuffer(&buf, " INVALID");
1699
1700                                         printTableAddFooter(&cont, buf.data);
1701
1702                                         /* Print tablespace of the index on the same line */
1703                                         if (pset.sversion >= 80000)
1704                                                 add_tablespace_footer(&cont, 'i',
1705                                                                                    atooid(PQgetvalue(result, i, 10)),
1706                                                                                           false);
1707                                 }
1708                         }
1709                         PQclear(result);
1710                 }
1711
1712                 /* print table (and column) check constraints */
1713                 if (tableinfo.checks)
1714                 {
1715                         printfPQExpBuffer(&buf,
1716                                                           "SELECT r.conname, "
1717                                                           "pg_catalog.pg_get_constraintdef(r.oid, true)\n"
1718                                                           "FROM pg_catalog.pg_constraint r\n"
1719                                    "WHERE r.conrelid = '%s' AND r.contype = 'c'\nORDER BY 1",
1720                                                           oid);
1721                         result = PSQLexec(buf.data, false);
1722                         if (!result)
1723                                 goto error_return;
1724                         else
1725                                 tuples = PQntuples(result);
1726
1727                         if (tuples > 0)
1728                         {
1729                                 printTableAddFooter(&cont, _("Check constraints:"));
1730                                 for (i = 0; i < tuples; i++)
1731                                 {
1732                                         /* untranslated contraint name and def */
1733                                         printfPQExpBuffer(&buf, "    \"%s\" %s",
1734                                                                           PQgetvalue(result, i, 0),
1735                                                                           PQgetvalue(result, i, 1));
1736
1737                                         printTableAddFooter(&cont, buf.data);
1738                                 }
1739                         }
1740                         PQclear(result);
1741                 }
1742
1743                 /* print foreign-key constraints (there are none if no triggers) */
1744                 if (tableinfo.hastriggers)
1745                 {
1746                         printfPQExpBuffer(&buf,
1747                                                           "SELECT conname,\n"
1748                                  "  pg_catalog.pg_get_constraintdef(r.oid, true) as condef\n");
1749                         if (pset.sversion >= 90100)
1750                                 appendPQExpBuffer(&buf, "  ,convalidated\n");
1751                         appendPQExpBuffer(&buf, "FROM pg_catalog.pg_constraint r\n"
1752                                         "WHERE r.conrelid = '%s' AND r.contype = 'f' ORDER BY 1",
1753                                                           oid);
1754                         result = PSQLexec(buf.data, false);
1755                         if (!result)
1756                                 goto error_return;
1757                         else
1758                                 tuples = PQntuples(result);
1759
1760                         if (tuples > 0)
1761                         {
1762                                 printTableAddFooter(&cont, _("Foreign-key constraints:"));
1763                                 for (i = 0; i < tuples; i++)
1764                                 {
1765                                         /* untranslated constraint name and def */
1766                                         printfPQExpBuffer(&buf, "    \"%s\" %s",
1767                                                                           PQgetvalue(result, i, 0),
1768                                                                           PQgetvalue(result, i, 1));
1769
1770                                         if (pset.sversion >= 90100 && strcmp(PQgetvalue(result, i, 2), "f") == 0)
1771                                                 appendPQExpBuffer(&buf, " NOT VALID");
1772
1773                                         printTableAddFooter(&cont, buf.data);
1774                                 }
1775                         }
1776                         PQclear(result);
1777                 }
1778
1779                 /* print incoming foreign-key references (none if no triggers) */
1780                 if (tableinfo.hastriggers)
1781                 {
1782                         printfPQExpBuffer(&buf,
1783                                                    "SELECT conname, conrelid::pg_catalog.regclass,\n"
1784                                  "  pg_catalog.pg_get_constraintdef(c.oid, true) as condef\n"
1785                                                           "FROM pg_catalog.pg_constraint c\n"
1786                                    "WHERE c.confrelid = '%s' AND c.contype = 'f' ORDER BY 1",
1787                                                           oid);
1788                         result = PSQLexec(buf.data, false);
1789                         if (!result)
1790                                 goto error_return;
1791                         else
1792                                 tuples = PQntuples(result);
1793
1794                         if (tuples > 0)
1795                         {
1796                                 printTableAddFooter(&cont, _("Referenced by:"));
1797                                 for (i = 0; i < tuples; i++)
1798                                 {
1799                                         printfPQExpBuffer(&buf, "    TABLE \"%s\" CONSTRAINT \"%s\" %s",
1800                                                                           PQgetvalue(result, i, 1),
1801                                                                           PQgetvalue(result, i, 0),
1802                                                                           PQgetvalue(result, i, 2));
1803
1804                                         printTableAddFooter(&cont, buf.data);
1805                                 }
1806                         }
1807                         PQclear(result);
1808                 }
1809
1810                 /* print rules */
1811                 if (tableinfo.hasrules)
1812                 {
1813                         if (pset.sversion >= 80300)
1814                         {
1815                                 printfPQExpBuffer(&buf,
1816                                                                   "SELECT r.rulename, trim(trailing ';' from pg_catalog.pg_get_ruledef(r.oid, true)), "
1817                                                                   "ev_enabled\n"
1818                                                                   "FROM pg_catalog.pg_rewrite r\n"
1819                                                                   "WHERE r.ev_class = '%s' ORDER BY 1",
1820                                                                   oid);
1821                         }
1822                         else
1823                         {
1824                                 printfPQExpBuffer(&buf,
1825                                                                   "SELECT r.rulename, trim(trailing ';' from pg_catalog.pg_get_ruledef(r.oid, true)), "
1826                                                                   "'O'::char AS ev_enabled\n"
1827                                                                   "FROM pg_catalog.pg_rewrite r\n"
1828                                                                   "WHERE r.ev_class = '%s' ORDER BY 1",
1829                                                                   oid);
1830                         }
1831                         result = PSQLexec(buf.data, false);
1832                         if (!result)
1833                                 goto error_return;
1834                         else
1835                                 tuples = PQntuples(result);
1836
1837                         if (tuples > 0)
1838                         {
1839                                 bool            have_heading;
1840                                 int                     category;
1841
1842                                 for (category = 0; category < 4; category++)
1843                                 {
1844                                         have_heading = false;
1845
1846                                         for (i = 0; i < tuples; i++)
1847                                         {
1848                                                 const char *ruledef;
1849                                                 bool            list_rule = false;
1850
1851                                                 switch (category)
1852                                                 {
1853                                                         case 0:
1854                                                                 if (*PQgetvalue(result, i, 2) == 'O')
1855                                                                         list_rule = true;
1856                                                                 break;
1857                                                         case 1:
1858                                                                 if (*PQgetvalue(result, i, 2) == 'D')
1859                                                                         list_rule = true;
1860                                                                 break;
1861                                                         case 2:
1862                                                                 if (*PQgetvalue(result, i, 2) == 'A')
1863                                                                         list_rule = true;
1864                                                                 break;
1865                                                         case 3:
1866                                                                 if (*PQgetvalue(result, i, 2) == 'R')
1867                                                                         list_rule = true;
1868                                                                 break;
1869                                                 }
1870                                                 if (!list_rule)
1871                                                         continue;
1872
1873                                                 if (!have_heading)
1874                                                 {
1875                                                         switch (category)
1876                                                         {
1877                                                                 case 0:
1878                                                                         printfPQExpBuffer(&buf, _("Rules:"));
1879                                                                         break;
1880                                                                 case 1:
1881                                                                         printfPQExpBuffer(&buf, _("Disabled rules:"));
1882                                                                         break;
1883                                                                 case 2:
1884                                                                         printfPQExpBuffer(&buf, _("Rules firing always:"));
1885                                                                         break;
1886                                                                 case 3:
1887                                                                         printfPQExpBuffer(&buf, _("Rules firing on replica only:"));
1888                                                                         break;
1889                                                         }
1890                                                         printTableAddFooter(&cont, buf.data);
1891                                                         have_heading = true;
1892                                                 }
1893
1894                                                 /* Everything after "CREATE RULE" is echoed verbatim */
1895                                                 ruledef = PQgetvalue(result, i, 1);
1896                                                 ruledef += 12;
1897                                                 printfPQExpBuffer(&buf, "    %s", ruledef);
1898                                                 printTableAddFooter(&cont, buf.data);
1899                                         }
1900                                 }
1901                         }
1902                         PQclear(result);
1903                 }
1904         }
1905
1906         /*
1907          * Print triggers next, if any (but only user-defined triggers).  This
1908          * could apply to either a table or a view.
1909          */
1910         if (tableinfo.hastriggers)
1911         {
1912                         PGresult   *result;
1913                         int                     tuples;
1914
1915                         printfPQExpBuffer(&buf,
1916                                                           "SELECT t.tgname, "
1917                                                           "pg_catalog.pg_get_triggerdef(t.oid%s), "
1918                                                           "t.tgenabled\n"
1919                                                           "FROM pg_catalog.pg_trigger t\n"
1920                                                           "WHERE t.tgrelid = '%s' AND ",
1921                                                           (pset.sversion >= 90000 ? ", true" : ""),
1922                                                           oid);
1923                         if (pset.sversion >= 90000)
1924                                 appendPQExpBuffer(&buf, "NOT t.tgisinternal");
1925                         else if (pset.sversion >= 80300)
1926                                 appendPQExpBuffer(&buf, "t.tgconstraint = 0");
1927                         else
1928                                 appendPQExpBuffer(&buf,
1929                                                                   "(NOT tgisconstraint "
1930                                                                   " OR NOT EXISTS"
1931                                                                   "  (SELECT 1 FROM pg_catalog.pg_depend d "
1932                                                                   "   JOIN pg_catalog.pg_constraint c ON (d.refclassid = c.tableoid AND d.refobjid = c.oid) "
1933                                                                   "   WHERE d.classid = t.tableoid AND d.objid = t.oid AND d.deptype = 'i' AND c.contype = 'f'))");
1934                         appendPQExpBuffer(&buf, "\nORDER BY 1");
1935
1936                         result = PSQLexec(buf.data, false);
1937                         if (!result)
1938                                 goto error_return;
1939                         else
1940                                 tuples = PQntuples(result);
1941
1942                         if (tuples > 0)
1943                         {
1944                                 bool            have_heading;
1945                                 int                     category;
1946
1947                                 /*
1948                                  * split the output into 4 different categories. Enabled
1949                                  * triggers, disabled triggers and the two special ALWAYS and
1950                                  * REPLICA configurations.
1951                                  */
1952                                 for (category = 0; category < 4; category++)
1953                                 {
1954                                         have_heading = false;
1955                                         for (i = 0; i < tuples; i++)
1956                                         {
1957                                                 bool            list_trigger;
1958                                                 const char *tgdef;
1959                                                 const char *usingpos;
1960                                                 const char *tgenabled;
1961
1962                                                 /*
1963                                                  * Check if this trigger falls into the current
1964                                                  * category
1965                                                  */
1966                                                 tgenabled = PQgetvalue(result, i, 2);
1967                                                 list_trigger = false;
1968                                                 switch (category)
1969                                                 {
1970                                                         case 0:
1971                                                                 if (*tgenabled == 'O' || *tgenabled == 't')
1972                                                                         list_trigger = true;
1973                                                                 break;
1974                                                         case 1:
1975                                                                 if (*tgenabled == 'D' || *tgenabled == 'f')
1976                                                                         list_trigger = true;
1977                                                                 break;
1978                                                         case 2:
1979                                                                 if (*tgenabled == 'A')
1980                                                                         list_trigger = true;
1981                                                                 break;
1982                                                         case 3:
1983                                                                 if (*tgenabled == 'R')
1984                                                                         list_trigger = true;
1985                                                                 break;
1986                                                 }
1987                                                 if (list_trigger == false)
1988                                                         continue;
1989
1990                                                 /* Print the category heading once */
1991                                                 if (have_heading == false)
1992                                                 {
1993                                                         switch (category)
1994                                                         {
1995                                                                 case 0:
1996                                                                         printfPQExpBuffer(&buf, _("Triggers:"));
1997                                                                         break;
1998                                                                 case 1:
1999                                                                         printfPQExpBuffer(&buf, _("Disabled triggers:"));
2000                                                                         break;
2001                                                                 case 2:
2002                                                                         printfPQExpBuffer(&buf, _("Triggers firing always:"));
2003                                                                         break;
2004                                                                 case 3:
2005                                                                         printfPQExpBuffer(&buf, _("Triggers firing on replica only:"));
2006                                                                         break;
2007
2008                                                         }
2009                                                         printTableAddFooter(&cont, buf.data);
2010                                                         have_heading = true;
2011                                                 }
2012
2013                                                 /* Everything after "TRIGGER" is echoed verbatim */
2014                                                 tgdef = PQgetvalue(result, i, 1);
2015                                                 usingpos = strstr(tgdef, " TRIGGER ");
2016                                                 if (usingpos)
2017                                                         tgdef = usingpos + 9;
2018
2019                                                 printfPQExpBuffer(&buf, "    %s", tgdef);
2020                                                 printTableAddFooter(&cont, buf.data);
2021                                         }
2022                                 }
2023                         }
2024                         PQclear(result);
2025         }
2026
2027         /*
2028          * Finish printing the footer information about a table.
2029          */
2030         if (tableinfo.relkind == 'r' || tableinfo.relkind == 'f')
2031         {
2032                 PGresult   *result;
2033                 int                     tuples;
2034
2035                 /* print foreign server name */
2036                 if (tableinfo.relkind == 'f')
2037                 {
2038                         /* Footer information about foreign table */
2039                         printfPQExpBuffer(&buf,
2040                                                           "SELECT s.srvname\n"
2041                                                           "FROM pg_catalog.pg_foreign_table f,\n"
2042                                                           "     pg_catalog.pg_foreign_server s\n"
2043                                                           "WHERE f.ftrelid = %s AND s.oid = f.ftserver",
2044                                                           oid);
2045                         result = PSQLexec(buf.data, false);
2046                         if (!result)
2047                                 goto error_return;
2048                         else if (PQntuples(result) != 1)
2049                         {
2050                                 PQclear(result);
2051                                 goto error_return;
2052                         }
2053
2054                         printfPQExpBuffer(&buf, "Server: %s",
2055                                 PQgetvalue(result, 0, 0));
2056                         printTableAddFooter(&cont, buf.data);
2057                         PQclear(result);
2058                 }
2059
2060                 /* print inherited tables */
2061                 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);
2062
2063                 result = PSQLexec(buf.data, false);
2064                 if (!result)
2065                         goto error_return;
2066                 else
2067                         tuples = PQntuples(result);
2068
2069                 for (i = 0; i < tuples; i++)
2070                 {
2071                         const char *s = _("Inherits");
2072
2073                         if (i == 0)
2074                                 printfPQExpBuffer(&buf, "%s: %s", s, PQgetvalue(result, i, 0));
2075                         else
2076                                 printfPQExpBuffer(&buf, "%*s  %s", (int) strlen(s), "", PQgetvalue(result, i, 0));
2077                         if (i < tuples - 1)
2078                                 appendPQExpBuffer(&buf, ",");
2079
2080                         printTableAddFooter(&cont, buf.data);
2081                 }
2082                 PQclear(result);
2083
2084                 /* print child tables */
2085                 if (pset.sversion >= 80300)
2086                         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);
2087                 else
2088                         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);
2089
2090                 result = PSQLexec(buf.data, false);
2091                 if (!result)
2092                         goto error_return;
2093                 else
2094                         tuples = PQntuples(result);
2095
2096                 if (!verbose)
2097                 {
2098                         /* print the number of child tables, if any */
2099                         if (tuples > 0)
2100                         {
2101                                 printfPQExpBuffer(&buf, _("Number of child tables: %d (Use \\d+ to list them.)"), tuples);
2102                                 printTableAddFooter(&cont, buf.data);
2103                         }
2104                 }
2105                 else
2106                 {
2107                         /* display the list of child tables */
2108                         const char *ct = _("Child tables");
2109
2110                         for (i = 0; i < tuples; i++)
2111                         {
2112                                 if (i == 0)
2113                                         printfPQExpBuffer(&buf, "%s: %s",
2114                                                                           ct, PQgetvalue(result, i, 0));
2115                                 else
2116                                         printfPQExpBuffer(&buf, "%*s  %s",
2117                                                                           (int) strlen(ct), "",
2118                                                                           PQgetvalue(result, i, 0));
2119                                 if (i < tuples - 1)
2120                                         appendPQExpBuffer(&buf, ",");
2121
2122                                 printTableAddFooter(&cont, buf.data);
2123                         }
2124                 }
2125                 PQclear(result);
2126
2127                 /* Table type */
2128                 if (tableinfo.reloftype)
2129                 {
2130                         printfPQExpBuffer(&buf, _("Typed table of type: %s"), tableinfo.reloftype);
2131                         printTableAddFooter(&cont, buf.data);
2132                 }
2133
2134                 /* OIDs and options */
2135                 if (verbose)
2136                 {
2137                         const char *s = _("Has OIDs");
2138
2139                         printfPQExpBuffer(&buf, "%s: %s", s,
2140                                                           (tableinfo.hasoids ? _("yes") : _("no")));
2141                         printTableAddFooter(&cont, buf.data);
2142
2143                         /* print reloptions */
2144                         if (pset.sversion >= 80200)
2145                         {
2146                                 if (tableinfo.reloptions && tableinfo.reloptions[0] != '\0')
2147                                 {
2148                                         const char *t = _("Options");
2149
2150                                         printfPQExpBuffer(&buf, "%s: %s", t,
2151                                                                           tableinfo.reloptions);
2152                                         printTableAddFooter(&cont, buf.data);
2153                                 }
2154                         }
2155                 }
2156
2157                 add_tablespace_footer(&cont, tableinfo.relkind, tableinfo.tablespace,
2158                                                           true);
2159         }
2160
2161         printTable(&cont, pset.queryFout, pset.logfile);
2162         printTableCleanup(&cont);
2163
2164         retval = true;
2165
2166 error_return:
2167
2168         /* clean up */
2169         if (printTableInitialized)
2170                 printTableCleanup(&cont);
2171         termPQExpBuffer(&buf);
2172         termPQExpBuffer(&title);
2173         termPQExpBuffer(&tmpbuf);
2174
2175         if (seq_values)
2176         {
2177                 for (ptr = seq_values; *ptr; ptr++)
2178                         free(*ptr);
2179                 free(seq_values);
2180         }
2181
2182         if (modifiers)
2183         {
2184                 for (ptr = modifiers; *ptr; ptr++)
2185                         free(*ptr);
2186                 free(modifiers);
2187         }
2188
2189         if (view_def)
2190                 free(view_def);
2191
2192         if (res)
2193                 PQclear(res);
2194
2195         return retval;
2196 }
2197
2198 /*
2199  * Add a tablespace description to a footer.  If 'newline' is true, it is added
2200  * in a new line; otherwise it's appended to the current value of the last
2201  * footer.
2202  */
2203 static void
2204 add_tablespace_footer(printTableContent *const cont, char relkind,
2205                                           Oid tablespace, const bool newline)
2206 {
2207         /* relkinds for which we support tablespaces */
2208         if (relkind == 'r' || relkind == 'i')
2209         {
2210                 /*
2211                  * We ignore the database default tablespace so that users not using
2212                  * tablespaces don't need to know about them.  This case also covers
2213                  * pre-8.0 servers, for which tablespace will always be 0.
2214                  */
2215                 if (tablespace != 0)
2216                 {
2217                         PGresult   *result = NULL;
2218                         PQExpBufferData buf;
2219
2220                         initPQExpBuffer(&buf);
2221                         printfPQExpBuffer(&buf,
2222                                                           "SELECT spcname FROM pg_catalog.pg_tablespace\n"
2223                                                           "WHERE oid = '%u'", tablespace);
2224                         result = PSQLexec(buf.data, false);
2225                         if (!result)
2226                                 return;
2227                         /* Should always be the case, but.... */
2228                         if (PQntuples(result) > 0)
2229                         {
2230                                 if (newline)
2231                                 {
2232                                         /* Add the tablespace as a new footer */
2233                                         printfPQExpBuffer(&buf, _("Tablespace: \"%s\""),
2234                                                                           PQgetvalue(result, 0, 0));
2235                                         printTableAddFooter(cont, buf.data);
2236                                 }
2237                                 else
2238                                 {
2239                                         /* Append the tablespace to the latest footer */
2240                                         printfPQExpBuffer(&buf, "%s", cont->footer->data);
2241
2242                                         /*
2243                                          * translator: before this string there's an index
2244                                          * description like '"foo_pkey" PRIMARY KEY, btree (a)'
2245                                          */
2246                                         appendPQExpBuffer(&buf, _(", tablespace \"%s\""),
2247                                                                           PQgetvalue(result, 0, 0));
2248                                         printTableSetFooter(cont, buf.data);
2249                                 }
2250                         }
2251                         PQclear(result);
2252                         termPQExpBuffer(&buf);
2253                 }
2254         }
2255 }
2256
2257 /*
2258  * \du or \dg
2259  *
2260  * Describes roles.  Any schema portion of the pattern is ignored.
2261  */
2262 bool
2263 describeRoles(const char *pattern, bool verbose)
2264 {
2265         PQExpBufferData buf;
2266         PGresult   *res;
2267         printTableContent cont;
2268         printTableOpt myopt = pset.popt.topt;
2269         int                     ncols = 3;
2270         int                     nrows = 0;
2271         int                     i;
2272         int                     conns;
2273         const char      align = 'l';
2274         char      **attr;
2275
2276         initPQExpBuffer(&buf);
2277
2278         if (pset.sversion >= 80100)
2279         {
2280                 printfPQExpBuffer(&buf,
2281                                                   "SELECT r.rolname, r.rolsuper, r.rolinherit,\n"
2282                                                   "  r.rolcreaterole, r.rolcreatedb, r.rolcanlogin,\n"
2283                                                   "  r.rolconnlimit,\n"
2284                                                   "  ARRAY(SELECT b.rolname\n"
2285                                                   "        FROM pg_catalog.pg_auth_members m\n"
2286                                  "        JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid)\n"
2287                                                   "        WHERE m.member = r.oid) as memberof");
2288
2289                 if (verbose && pset.sversion >= 80200)
2290                 {
2291                         appendPQExpBufferStr(&buf, "\n, pg_catalog.shobj_description(r.oid, 'pg_authid') AS description");
2292                         ncols++;
2293                 }
2294                 if (pset.sversion >= 90100)
2295                 {
2296                         appendPQExpBufferStr(&buf,"\n, r.rolreplication");
2297                 }
2298
2299                 appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_roles r\n");
2300
2301                 processSQLNamePattern(pset.db, &buf, pattern, false, false,
2302                                                           NULL, "r.rolname", NULL, NULL);
2303         }
2304         else
2305         {
2306                 printfPQExpBuffer(&buf,
2307                                                   "SELECT u.usename AS rolname,\n"
2308                                                   "  u.usesuper AS rolsuper,\n"
2309                                                   "  true AS rolinherit, false AS rolcreaterole,\n"
2310                                          "  u.usecreatedb AS rolcreatedb, true AS rolcanlogin,\n"
2311                                                   "  -1 AS rolconnlimit,\n"
2312                                                   "  ARRAY(SELECT g.groname FROM pg_catalog.pg_group g WHERE u.usesysid = ANY(g.grolist)) as memberof"
2313                                                   "\nFROM pg_catalog.pg_user u\n");
2314
2315                 processSQLNamePattern(pset.db, &buf, pattern, false, false,
2316                                                           NULL, "u.usename", NULL, NULL);
2317         }
2318
2319         appendPQExpBuffer(&buf, "ORDER BY 1;");
2320
2321         res = PSQLexec(buf.data, false);
2322         if (!res)
2323                 return false;
2324
2325         nrows = PQntuples(res);
2326         attr = pg_malloc_zero((nrows + 1) * sizeof(*attr));
2327
2328         printTableInit(&cont, &myopt, _("List of roles"), ncols, nrows);
2329
2330         printTableAddHeader(&cont, gettext_noop("Role name"), true, align);
2331         printTableAddHeader(&cont, gettext_noop("Attributes"), true, align);
2332         printTableAddHeader(&cont, gettext_noop("Member of"), true, align);
2333
2334         if (verbose && pset.sversion >= 80200)
2335                 printTableAddHeader(&cont, gettext_noop("Description"), true, align);
2336
2337         for (i = 0; i < nrows; i++)
2338         {
2339                 printTableAddCell(&cont, PQgetvalue(res, i, 0), false, false);
2340
2341                 resetPQExpBuffer(&buf);
2342                 if (strcmp(PQgetvalue(res, i, 1), "t") == 0)
2343                         add_role_attribute(&buf, _("Superuser"));
2344
2345                 if (strcmp(PQgetvalue(res, i, 2), "t") != 0)
2346                         add_role_attribute(&buf, _("No inheritance"));
2347
2348                 if (strcmp(PQgetvalue(res, i, 3), "t") == 0)
2349                         add_role_attribute(&buf, _("Create role"));
2350
2351                 if (strcmp(PQgetvalue(res, i, 4), "t") == 0)
2352                         add_role_attribute(&buf, _("Create DB"));
2353
2354                 if (strcmp(PQgetvalue(res, i, 5), "t") != 0)
2355                         add_role_attribute(&buf, _("Cannot login"));
2356
2357                 if (pset.sversion >= 90100)
2358                         if (strcmp(PQgetvalue(res, i, (verbose ? 9 : 8)), "t") == 0)
2359                                 add_role_attribute(&buf, _("Replication"));
2360
2361                 conns = atoi(PQgetvalue(res, i, 6));
2362                 if (conns >= 0)
2363                 {
2364                         if (buf.len > 0)
2365                                 appendPQExpBufferStr(&buf, "\n");
2366
2367                         if (conns == 0)
2368                                 appendPQExpBuffer(&buf, _("No connections"));
2369                         else
2370                                 appendPQExpBuffer(&buf, ngettext("%d connection",
2371                                                                                                  "%d connections",
2372                                                                                                  conns),
2373                                                                   conns);
2374                 }
2375
2376                 attr[i] = pg_strdup(buf.data);
2377
2378                 printTableAddCell(&cont, attr[i], false, false);
2379
2380                 printTableAddCell(&cont, PQgetvalue(res, i, 7), false, false);
2381
2382                 if (verbose && pset.sversion >= 80200)
2383                         printTableAddCell(&cont, PQgetvalue(res, i, 8), false, false);
2384         }
2385         termPQExpBuffer(&buf);
2386
2387         printTable(&cont, pset.queryFout, pset.logfile);
2388         printTableCleanup(&cont);
2389
2390         for (i = 0; i < nrows; i++)
2391                 free(attr[i]);
2392         free(attr);
2393
2394         PQclear(res);
2395         return true;
2396 }
2397
2398 static void
2399 add_role_attribute(PQExpBuffer buf, const char *const str)
2400 {
2401         if (buf->len > 0)
2402                 appendPQExpBufferStr(buf, ", ");
2403
2404         appendPQExpBufferStr(buf, str);
2405 }
2406
2407 /*
2408  * \drds
2409  */
2410 bool
2411 listDbRoleSettings(const char *pattern, const char *pattern2)
2412 {
2413         PQExpBufferData buf;
2414         PGresult   *res;
2415         printQueryOpt myopt = pset.popt;
2416
2417         initPQExpBuffer(&buf);
2418
2419         if (pset.sversion >= 90000)
2420         {
2421                 bool            havewhere;
2422
2423                 printfPQExpBuffer(&buf, "SELECT rolname AS role, datname AS database,\n"
2424                                 "pg_catalog.array_to_string(setconfig, E'\\n') AS settings\n"
2425                                                   "FROM pg_db_role_setting AS s\n"
2426                                    "LEFT JOIN pg_database ON pg_database.oid = setdatabase\n"
2427                                                   "LEFT JOIN pg_roles ON pg_roles.oid = setrole\n");
2428                 havewhere = processSQLNamePattern(pset.db, &buf, pattern, false, false,
2429                                                                            NULL, "pg_roles.rolname", NULL, NULL);
2430                 processSQLNamePattern(pset.db, &buf, pattern2, havewhere, false,
2431                                                           NULL, "pg_database.datname", NULL, NULL);
2432                 appendPQExpBufferStr(&buf, "ORDER BY role, database");
2433         }
2434         else
2435         {
2436                 fprintf(pset.queryFout,
2437                 _("No per-database role settings support in this server version.\n"));
2438                 return false;
2439         }
2440
2441         res = PSQLexec(buf.data, false);
2442         if (!res)
2443                 return false;
2444
2445         if (PQntuples(res) == 0 && !pset.quiet)
2446         {
2447                 if (pattern)
2448                         fprintf(pset.queryFout, _("No matching settings found.\n"));
2449                 else
2450                         fprintf(pset.queryFout, _("No settings found.\n"));
2451         }
2452         else
2453         {
2454                 myopt.nullPrint = NULL;
2455                 myopt.title = _("List of settings");
2456                 myopt.translate_header = true;
2457
2458                 printQuery(res, &myopt, pset.queryFout, pset.logfile);
2459         }
2460
2461         PQclear(res);
2462         resetPQExpBuffer(&buf);
2463         return true;
2464 }
2465
2466
2467 /*
2468  * listTables()
2469  *
2470  * handler for \dt, \di, etc.
2471  *
2472  * tabtypes is an array of characters, specifying what info is desired:
2473  * t - tables
2474  * i - indexes
2475  * v - views
2476  * s - sequences
2477  * E - foreign table (Note: different from 'f', the relkind value)
2478  * (any order of the above is fine)
2479  * If tabtypes is empty, we default to \dtvsE.
2480  */
2481 bool
2482 listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSystem)
2483 {
2484         bool            showTables = strchr(tabtypes, 't') != NULL;
2485         bool            showIndexes = strchr(tabtypes, 'i') != NULL;
2486         bool            showViews = strchr(tabtypes, 'v') != NULL;
2487         bool            showSeq = strchr(tabtypes, 's') != NULL;
2488         bool            showForeign = strchr(tabtypes, 'E') != NULL;
2489
2490         PQExpBufferData buf;
2491         PGresult   *res;
2492         printQueryOpt myopt = pset.popt;
2493         static const bool translate_columns[] = {false, false, true, false, false, false, false};
2494
2495         if (!(showTables || showIndexes || showViews || showSeq || showForeign))
2496                 showTables = showViews = showSeq = showForeign = true;
2497
2498         initPQExpBuffer(&buf);
2499
2500         /*
2501          * Note: as of Pg 8.2, we no longer use relkind 's', but we keep it here
2502          * for backwards compatibility.
2503          */
2504         printfPQExpBuffer(&buf,
2505                                           "SELECT n.nspname as \"%s\",\n"
2506                                           "  c.relname as \"%s\",\n"
2507                                           "  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"
2508                                           "  pg_catalog.pg_get_userbyid(c.relowner) as \"%s\"",
2509                                           gettext_noop("Schema"),
2510                                           gettext_noop("Name"),
2511                                           gettext_noop("table"),
2512                                           gettext_noop("view"),
2513                                           gettext_noop("index"),
2514                                           gettext_noop("sequence"),
2515                                           gettext_noop("special"),
2516                                           gettext_noop("foreign table"),
2517                                           gettext_noop("Type"),
2518                                           gettext_noop("Owner"));
2519
2520         if (showIndexes)
2521                 appendPQExpBuffer(&buf,
2522                                                   ",\n c2.relname as \"%s\"",
2523                                                   gettext_noop("Table"));
2524
2525         if (verbose && pset.sversion >= 80100)
2526                 appendPQExpBuffer(&buf,
2527                                                   ",\n  pg_catalog.pg_size_pretty(pg_catalog.pg_relation_size(c.oid)) as \"%s\"",
2528                                                   gettext_noop("Size"));
2529         if (verbose)
2530                 appendPQExpBuffer(&buf,
2531                           ",\n  pg_catalog.obj_description(c.oid, 'pg_class') as \"%s\"",
2532                                                   gettext_noop("Description"));
2533
2534         appendPQExpBuffer(&buf,
2535                                           "\nFROM pg_catalog.pg_class c"
2536          "\n     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace");
2537         if (showIndexes)
2538                 appendPQExpBuffer(&buf,
2539                          "\n     LEFT JOIN pg_catalog.pg_index i ON i.indexrelid = c.oid"
2540                    "\n     LEFT JOIN pg_catalog.pg_class c2 ON i.indrelid = c2.oid");
2541
2542         appendPQExpBuffer(&buf, "\nWHERE c.relkind IN (");
2543         if (showTables)
2544                 appendPQExpBuffer(&buf, "'r',");
2545         if (showViews)
2546                 appendPQExpBuffer(&buf, "'v',");
2547         if (showIndexes)
2548                 appendPQExpBuffer(&buf, "'i',");
2549         if (showSeq)
2550                 appendPQExpBuffer(&buf, "'S',");
2551         if (showSystem || pattern)
2552                 appendPQExpBuffer(&buf, "'s',");                /* was RELKIND_SPECIAL in <=
2553                                                                                                  * 8.1 */
2554         if (showForeign)
2555                 appendPQExpBuffer(&buf, "'f',");
2556
2557         appendPQExpBuffer(&buf, "''");          /* dummy */
2558         appendPQExpBuffer(&buf, ")\n");
2559
2560         if (!showSystem && !pattern)
2561                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
2562                                                   "      AND n.nspname <> 'information_schema'\n");
2563
2564         /*
2565          * TOAST objects are suppressed unconditionally.  Since we don't provide
2566          * any way to select relkind 't' above, we would never show toast tables
2567          * in any case; it seems a bit confusing to allow their indexes to be
2568          * shown. Use plain \d if you really need to look at a TOAST table/index.
2569          */
2570         appendPQExpBuffer(&buf, "      AND n.nspname !~ '^pg_toast'\n");
2571
2572         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2573                                                   "n.nspname", "c.relname", NULL,
2574                                                   "pg_catalog.pg_table_is_visible(c.oid)");
2575
2576         appendPQExpBuffer(&buf, "ORDER BY 1,2;");
2577
2578         res = PSQLexec(buf.data, false);
2579         termPQExpBuffer(&buf);
2580         if (!res)
2581                 return false;
2582
2583         if (PQntuples(res) == 0 && !pset.quiet)
2584         {
2585                 if (pattern)
2586                         fprintf(pset.queryFout, _("No matching relations found.\n"));
2587                 else
2588                         fprintf(pset.queryFout, _("No relations found.\n"));
2589         }
2590         else
2591         {
2592                 myopt.nullPrint = NULL;
2593                 myopt.title = _("List of relations");
2594                 myopt.translate_header = true;
2595                 myopt.translate_columns = translate_columns;
2596
2597                 printQuery(res, &myopt, pset.queryFout, pset.logfile);
2598         }
2599
2600         PQclear(res);
2601         return true;
2602 }
2603
2604
2605 /*
2606  * \dL
2607  *
2608  * Describes languages.
2609  */
2610 bool
2611 listLanguages(const char *pattern, bool verbose, bool showSystem)
2612 {
2613         PQExpBufferData buf;
2614         PGresult *res;
2615         printQueryOpt myopt = pset.popt;
2616
2617         initPQExpBuffer(&buf);
2618
2619         printfPQExpBuffer(&buf,
2620                                           "SELECT l.lanname AS \"%s\",\n",
2621                                           gettext_noop("Name"));
2622         if (pset.sversion >= 80300)
2623                         appendPQExpBuffer(&buf,
2624                                                           "       pg_catalog.pg_get_userbyid(l.lanowner) as \"%s\",\n",
2625                                                           gettext_noop("Owner"));
2626
2627         appendPQExpBuffer(&buf,
2628                                           "       l.lanpltrusted AS \"%s\"",
2629                                           gettext_noop("Trusted"));
2630
2631         if (verbose)
2632         {
2633                         appendPQExpBuffer(&buf,
2634                                                           ",\n       NOT l.lanispl AS \"%s\",\n"
2635                                                           "       l.lanplcallfoid::regprocedure AS \"%s\",\n"
2636                                                           "       l.lanvalidator::regprocedure AS \"%s\",\n       ",
2637                                                           gettext_noop("Internal Language"),
2638                                                           gettext_noop("Call Handler"),
2639                                                           gettext_noop("Validator"));
2640                         if (pset.sversion >= 90000)
2641                                 appendPQExpBuffer(&buf, "l.laninline::regprocedure AS \"%s\",\n       ",
2642                                                                   gettext_noop("Inline Handler"));
2643                         printACLColumn(&buf, "l.lanacl");
2644         }
2645
2646         appendPQExpBuffer(&buf,
2647                                           "\nFROM pg_catalog.pg_language l\n");
2648
2649         processSQLNamePattern(pset.db, &buf, pattern, false, false,
2650                                                   NULL, "l.lanname", NULL, NULL);
2651
2652         if (!showSystem && !pattern)
2653                 appendPQExpBuffer(&buf, "WHERE lanplcallfoid != 0\n");
2654
2655         appendPQExpBuffer(&buf, "ORDER BY 1;");
2656
2657         res = PSQLexec(buf.data, false);
2658         termPQExpBuffer(&buf);
2659         if (!res)
2660                 return false;
2661
2662         myopt.nullPrint = NULL;
2663         myopt.title = _("List of languages");
2664         myopt.translate_header = true;
2665
2666         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2667
2668         PQclear(res);
2669         return true;
2670 }
2671
2672
2673 /*
2674  * \dD
2675  *
2676  * Describes domains.
2677  */
2678 bool
2679 listDomains(const char *pattern, bool showSystem)
2680 {
2681         PQExpBufferData buf;
2682         PGresult   *res;
2683         printQueryOpt myopt = pset.popt;
2684
2685         initPQExpBuffer(&buf);
2686
2687         printfPQExpBuffer(&buf,
2688                                           "SELECT n.nspname as \"%s\",\n"
2689                                           "       t.typname as \"%s\",\n"
2690          "       pg_catalog.format_type(t.typbasetype, t.typtypmod) as \"%s\",\n"
2691                                           "       CASE WHEN t.typnotnull AND t.typdefault IS NOT NULL THEN 'not null default '||t.typdefault\n"
2692         "            WHEN t.typnotnull AND t.typdefault IS NULL THEN 'not null'\n"
2693                                           "            WHEN NOT t.typnotnull AND t.typdefault IS NOT NULL THEN 'default '||t.typdefault\n"
2694                                           "            ELSE ''\n"
2695                                           "       END as \"%s\",\n"
2696                                           "       pg_catalog.array_to_string(ARRAY(\n"
2697                                           "         SELECT pg_catalog.pg_get_constraintdef(r.oid, true) FROM pg_catalog.pg_constraint r WHERE t.oid = r.contypid\n"
2698                                           "       ), ' ') as \"%s\"\n"
2699                                           "FROM pg_catalog.pg_type t\n"
2700            "     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n"
2701                                           "WHERE t.typtype = 'd'\n",
2702                                           gettext_noop("Schema"),
2703                                           gettext_noop("Name"),
2704                                           gettext_noop("Type"),
2705                                           gettext_noop("Modifier"),
2706                                           gettext_noop("Check"));
2707
2708         if (!showSystem && !pattern)
2709                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
2710                                                   "      AND n.nspname <> 'information_schema'\n");
2711
2712         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2713                                                   "n.nspname", "t.typname", NULL,
2714                                                   "pg_catalog.pg_type_is_visible(t.oid)");
2715
2716         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
2717
2718         res = PSQLexec(buf.data, false);
2719         termPQExpBuffer(&buf);
2720         if (!res)
2721                 return false;
2722
2723         myopt.nullPrint = NULL;
2724         myopt.title = _("List of domains");
2725         myopt.translate_header = true;
2726
2727         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2728
2729         PQclear(res);
2730         return true;
2731 }
2732
2733 /*
2734  * \dc
2735  *
2736  * Describes conversions.
2737  */
2738 bool
2739 listConversions(const char *pattern, bool showSystem)
2740 {
2741         PQExpBufferData buf;
2742         PGresult   *res;
2743         printQueryOpt myopt = pset.popt;
2744         static const bool translate_columns[] = {false, false, false, false, true};
2745
2746         initPQExpBuffer(&buf);
2747
2748         printfPQExpBuffer(&buf,
2749                                           "SELECT n.nspname AS \"%s\",\n"
2750                                           "       c.conname AS \"%s\",\n"
2751            "       pg_catalog.pg_encoding_to_char(c.conforencoding) AS \"%s\",\n"
2752                 "       pg_catalog.pg_encoding_to_char(c.contoencoding) AS \"%s\",\n"
2753                                           "       CASE WHEN c.condefault THEN '%s'\n"
2754                                           "       ELSE '%s' END AS \"%s\"\n"
2755                            "FROM pg_catalog.pg_conversion c, pg_catalog.pg_namespace n\n"
2756                                           "WHERE n.oid = c.connamespace\n",
2757                                           gettext_noop("Schema"),
2758                                           gettext_noop("Name"),
2759                                           gettext_noop("Source"),
2760                                           gettext_noop("Destination"),
2761                                           gettext_noop("yes"), gettext_noop("no"),
2762                                           gettext_noop("Default?"));
2763
2764         if (!showSystem && !pattern)
2765                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
2766                                                   "      AND n.nspname <> 'information_schema'\n");
2767
2768         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2769                                                   "n.nspname", "c.conname", NULL,
2770                                                   "pg_catalog.pg_conversion_is_visible(c.oid)");
2771
2772         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
2773
2774         res = PSQLexec(buf.data, false);
2775         termPQExpBuffer(&buf);
2776         if (!res)
2777                 return false;
2778
2779         myopt.nullPrint = NULL;
2780         myopt.title = _("List of conversions");
2781         myopt.translate_header = true;
2782         myopt.translate_columns = translate_columns;
2783
2784         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2785
2786         PQclear(res);
2787         return true;
2788 }
2789
2790 /*
2791  * \dC
2792  *
2793  * Describes casts.
2794  */
2795 bool
2796 listCasts(const char *pattern)
2797 {
2798         PQExpBufferData buf;
2799         PGresult   *res;
2800         printQueryOpt myopt = pset.popt;
2801         static const bool translate_columns[] = {false, false, false, true};
2802
2803         initPQExpBuffer(&buf);
2804
2805         /*
2806          * We need a left join to pg_proc for binary casts; the others are just
2807          * paranoia.  Also note that we don't attempt to localize '(binary
2808          * coercible)', because there's too much risk of gettext translating a
2809          * function name that happens to match some string in the PO database.
2810          */
2811         printfPQExpBuffer(&buf,
2812                            "SELECT pg_catalog.format_type(castsource, NULL) AS \"%s\",\n"
2813                            "       pg_catalog.format_type(casttarget, NULL) AS \"%s\",\n"
2814                                   "       CASE WHEN castfunc = 0 THEN '(binary coercible)'\n"
2815                                           "            ELSE p.proname\n"
2816                                           "       END as \"%s\",\n"
2817                                           "       CASE WHEN c.castcontext = 'e' THEN '%s'\n"
2818                                           "            WHEN c.castcontext = 'a' THEN '%s'\n"
2819                                           "            ELSE '%s'\n"
2820                                           "       END as \"%s\"\n"
2821                                  "FROM pg_catalog.pg_cast c LEFT JOIN pg_catalog.pg_proc p\n"
2822                                           "     ON c.castfunc = p.oid\n"
2823                                           "     LEFT JOIN pg_catalog.pg_type ts\n"
2824                                           "     ON c.castsource = ts.oid\n"
2825                                           "     LEFT JOIN pg_catalog.pg_namespace ns\n"
2826                                           "     ON ns.oid = ts.typnamespace\n"
2827                                           "     LEFT JOIN pg_catalog.pg_type tt\n"
2828                                           "     ON c.casttarget = tt.oid\n"
2829                                           "     LEFT JOIN pg_catalog.pg_namespace nt\n"
2830                                           "     ON nt.oid = tt.typnamespace\n"
2831                                           "WHERE (true",
2832                                           gettext_noop("Source type"),
2833                                           gettext_noop("Target type"),
2834                                           gettext_noop("Function"),
2835           gettext_noop("no"), gettext_noop("in assignment"), gettext_noop("yes"),
2836                                           gettext_noop("Implicit?"));
2837
2838         /*
2839          * Match name pattern against either internal or external name of either
2840          * castsource or casttarget
2841          */
2842         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2843                                                   "ns.nspname", "ts.typname",
2844                                                   "pg_catalog.format_type(ts.oid, NULL)",
2845                                                   "pg_catalog.pg_type_is_visible(ts.oid)");
2846
2847         appendPQExpBuffer(&buf, ") OR (true");
2848
2849         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2850                                                   "nt.nspname", "tt.typname",
2851                                                   "pg_catalog.format_type(tt.oid, NULL)",
2852                                                   "pg_catalog.pg_type_is_visible(tt.oid)");
2853
2854         appendPQExpBuffer(&buf, ")\nORDER BY 1, 2;");
2855
2856         res = PSQLexec(buf.data, false);
2857         termPQExpBuffer(&buf);
2858         if (!res)
2859                 return false;
2860
2861         myopt.nullPrint = NULL;
2862         myopt.title = _("List of casts");
2863         myopt.translate_header = true;
2864         myopt.translate_columns = translate_columns;
2865
2866         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2867
2868         PQclear(res);
2869         return true;
2870 }
2871
2872 /*
2873  * \dO
2874  *
2875  * Describes collations
2876  */
2877 bool
2878 listCollations(const char *pattern, bool verbose, bool showSystem)
2879 {
2880         PQExpBufferData buf;
2881         PGresult   *res;
2882         printQueryOpt myopt = pset.popt;
2883         static const bool translate_columns[] = {false, false, false, false, false};
2884
2885         initPQExpBuffer(&buf);
2886
2887         printfPQExpBuffer(&buf,
2888                                           "SELECT n.nspname AS \"%s\",\n"
2889                                           "       c.collname AS \"%s\",\n"
2890                                           "       c.collcollate AS \"%s\",\n"
2891                                           "       c.collctype AS \"%s\"",
2892                                           gettext_noop("Schema"),
2893                                           gettext_noop("Name"),
2894                                           gettext_noop("Collate"),
2895                                           gettext_noop("Ctype"));
2896
2897         if (verbose)
2898                 appendPQExpBuffer(&buf,
2899                   ",\n  pg_catalog.obj_description(c.oid, 'pg_collation') AS \"%s\"",
2900                                                   gettext_noop("Description"));
2901
2902         appendPQExpBuffer(&buf,
2903                                           "FROM pg_catalog.pg_collation c, pg_catalog.pg_namespace n\n"
2904                                           "WHERE n.oid = c.collnamespace\n");
2905
2906         if (!showSystem && !pattern)
2907                 appendPQExpBuffer(&buf, "      AND n.nspname <> 'pg_catalog'\n"
2908                                                   "      AND n.nspname <> 'information_schema'\n");
2909
2910         processSQLNamePattern(pset.db, &buf, pattern, true, false,
2911                                                   "n.nspname", "c.collname", NULL,
2912                                                   "pg_catalog.pg_collation_is_visible(c.oid)");
2913
2914         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
2915
2916         res = PSQLexec(buf.data, false);
2917         termPQExpBuffer(&buf);
2918         if (!res)
2919                 return false;
2920
2921         myopt.nullPrint = NULL;
2922         myopt.title = _("List of collations");
2923         myopt.translate_header = true;
2924         myopt.translate_columns = translate_columns;
2925
2926         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2927
2928         PQclear(res);
2929         return true;
2930 }
2931
2932 /*
2933  * \dn
2934  *
2935  * Describes schemas (namespaces)
2936  */
2937 bool
2938 listSchemas(const char *pattern, bool verbose, bool showSystem)
2939 {
2940         PQExpBufferData buf;
2941         PGresult   *res;
2942         printQueryOpt myopt = pset.popt;
2943
2944         initPQExpBuffer(&buf);
2945         printfPQExpBuffer(&buf,
2946                                           "SELECT n.nspname AS \"%s\",\n"
2947                                           "  pg_catalog.pg_get_userbyid(n.nspowner) AS \"%s\"",
2948                                           gettext_noop("Name"),
2949                                           gettext_noop("Owner"));
2950
2951         if (verbose)
2952         {
2953                 appendPQExpBuffer(&buf, ",\n  ");
2954                 printACLColumn(&buf, "n.nspacl");
2955                 appendPQExpBuffer(&buf,
2956                   ",\n  pg_catalog.obj_description(n.oid, 'pg_namespace') AS \"%s\"",
2957                                                   gettext_noop("Description"));
2958         }
2959
2960         appendPQExpBuffer(&buf,
2961                                           "\nFROM pg_catalog.pg_namespace n\n");
2962
2963         if (!showSystem && !pattern)
2964                 appendPQExpBuffer(&buf,
2965                                                   "WHERE n.nspname !~ '^pg_' AND n.nspname <> 'information_schema'\n");
2966
2967         processSQLNamePattern(pset.db, &buf, pattern,
2968                                                   !showSystem && !pattern, false,
2969                                                   NULL, "n.nspname", NULL,
2970                                                   NULL);
2971
2972         appendPQExpBuffer(&buf, "ORDER BY 1;");
2973
2974         res = PSQLexec(buf.data, false);
2975         termPQExpBuffer(&buf);
2976         if (!res)
2977                 return false;
2978
2979         myopt.nullPrint = NULL;
2980         myopt.title = _("List of schemas");
2981         myopt.translate_header = true;
2982
2983         printQuery(res, &myopt, pset.queryFout, pset.logfile);
2984
2985         PQclear(res);
2986         return true;
2987 }
2988
2989
2990 /*
2991  * \dFp
2992  * list text search parsers
2993  */
2994 bool
2995 listTSParsers(const char *pattern, bool verbose)
2996 {
2997         PQExpBufferData buf;
2998         PGresult   *res;
2999         printQueryOpt myopt = pset.popt;
3000
3001         if (pset.sversion < 80300)
3002         {
3003                 fprintf(stderr, _("The server (version %d.%d) does not support full text search.\n"),
3004                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3005                 return true;
3006         }
3007
3008         if (verbose)
3009                 return listTSParsersVerbose(pattern);
3010
3011         initPQExpBuffer(&buf);
3012
3013         printfPQExpBuffer(&buf,
3014                                           "SELECT \n"
3015                                           "  n.nspname as \"%s\",\n"
3016                                           "  p.prsname as \"%s\",\n"
3017                         "  pg_catalog.obj_description(p.oid, 'pg_ts_parser') as \"%s\"\n"
3018                                           "FROM pg_catalog.pg_ts_parser p \n"
3019                    "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.prsnamespace\n",
3020                                           gettext_noop("Schema"),
3021                                           gettext_noop("Name"),
3022                                           gettext_noop("Description")
3023                 );
3024
3025         processSQLNamePattern(pset.db, &buf, pattern, false, false,
3026                                                   "n.nspname", "p.prsname", NULL,
3027                                                   "pg_catalog.pg_ts_parser_is_visible(p.oid)");
3028
3029         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
3030
3031         res = PSQLexec(buf.data, false);
3032         termPQExpBuffer(&buf);
3033         if (!res)
3034                 return false;
3035
3036         myopt.nullPrint = NULL;
3037         myopt.title = _("List of text search parsers");
3038         myopt.translate_header = true;
3039
3040         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3041
3042         PQclear(res);
3043         return true;
3044 }
3045
3046 /*
3047  * full description of parsers
3048  */
3049 static bool
3050 listTSParsersVerbose(const char *pattern)
3051 {
3052         PQExpBufferData buf;
3053         PGresult   *res;
3054         int                     i;
3055
3056         initPQExpBuffer(&buf);
3057
3058         printfPQExpBuffer(&buf,
3059                                           "SELECT p.oid, \n"
3060                                           "  n.nspname, \n"
3061                                           "  p.prsname \n"
3062                                           "FROM pg_catalog.pg_ts_parser p\n"
3063                         "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.prsnamespace\n"
3064                 );
3065
3066         processSQLNamePattern(pset.db, &buf, pattern, false, false,
3067                                                   "n.nspname", "p.prsname", NULL,
3068                                                   "pg_catalog.pg_ts_parser_is_visible(p.oid)");
3069
3070         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
3071
3072         res = PSQLexec(buf.data, false);
3073         termPQExpBuffer(&buf);
3074         if (!res)
3075                 return false;
3076
3077         if (PQntuples(res) == 0)
3078         {
3079                 if (!pset.quiet)
3080                         fprintf(stderr, _("Did not find any text search parser named \"%s\".\n"),
3081                                         pattern);
3082                 PQclear(res);
3083                 return false;
3084         }
3085
3086         for (i = 0; i < PQntuples(res); i++)
3087         {
3088                 const char *oid;
3089                 const char *nspname = NULL;
3090                 const char *prsname;
3091
3092                 oid = PQgetvalue(res, i, 0);
3093                 if (!PQgetisnull(res, i, 1))
3094                         nspname = PQgetvalue(res, i, 1);
3095                 prsname = PQgetvalue(res, i, 2);
3096
3097                 if (!describeOneTSParser(oid, nspname, prsname))
3098                 {
3099                         PQclear(res);
3100                         return false;
3101                 }
3102
3103                 if (cancel_pressed)
3104                 {
3105                         PQclear(res);
3106                         return false;
3107                 }
3108         }
3109
3110         PQclear(res);
3111         return true;
3112 }
3113
3114 static bool
3115 describeOneTSParser(const char *oid, const char *nspname, const char *prsname)
3116 {
3117         PQExpBufferData buf;
3118         PGresult   *res;
3119         char            title[1024];
3120         printQueryOpt myopt = pset.popt;
3121         static const bool translate_columns[] = {true, false, false};
3122
3123         initPQExpBuffer(&buf);
3124
3125         printfPQExpBuffer(&buf,
3126                                           "SELECT '%s' AS \"%s\", \n"
3127                                           "   p.prsstart::pg_catalog.regproc AS \"%s\", \n"
3128                   "   pg_catalog.obj_description(p.prsstart, 'pg_proc') as \"%s\" \n"
3129                                           " FROM pg_catalog.pg_ts_parser p \n"
3130                                           " WHERE p.oid = '%s' \n"
3131                                           "UNION ALL \n"
3132                                           "SELECT '%s', \n"
3133                                           "   p.prstoken::pg_catalog.regproc, \n"
3134                                         "   pg_catalog.obj_description(p.prstoken, 'pg_proc') \n"
3135                                           " FROM pg_catalog.pg_ts_parser p \n"
3136                                           " WHERE p.oid = '%s' \n"
3137                                           "UNION ALL \n"
3138                                           "SELECT '%s', \n"
3139                                           "   p.prsend::pg_catalog.regproc, \n"
3140                                           "   pg_catalog.obj_description(p.prsend, 'pg_proc') \n"
3141                                           " FROM pg_catalog.pg_ts_parser p \n"
3142                                           " WHERE p.oid = '%s' \n"
3143                                           "UNION ALL \n"
3144                                           "SELECT '%s', \n"
3145                                           "   p.prsheadline::pg_catalog.regproc, \n"
3146                                  "   pg_catalog.obj_description(p.prsheadline, 'pg_proc') \n"
3147                                           " FROM pg_catalog.pg_ts_parser p \n"
3148                                           " WHERE p.oid = '%s' \n"
3149                                           "UNION ALL \n"
3150                                           "SELECT '%s', \n"
3151                                           "   p.prslextype::pg_catalog.regproc, \n"
3152                                   "   pg_catalog.obj_description(p.prslextype, 'pg_proc') \n"
3153                                           " FROM pg_catalog.pg_ts_parser p \n"
3154                                           " WHERE p.oid = '%s' \n",
3155                                           gettext_noop("Start parse"),
3156                                           gettext_noop("Method"),
3157                                           gettext_noop("Function"),
3158                                           gettext_noop("Description"),
3159                                           oid,
3160                                           gettext_noop("Get next token"),
3161                                           oid,
3162                                           gettext_noop("End parse"),
3163                                           oid,
3164                                           gettext_noop("Get headline"),
3165                                           oid,
3166                                           gettext_noop("Get token types"),
3167                                           oid);
3168
3169         res = PSQLexec(buf.data, false);
3170         termPQExpBuffer(&buf);
3171         if (!res)
3172                 return false;
3173
3174         myopt.nullPrint = NULL;
3175         if (nspname)
3176                 sprintf(title, _("Text search parser \"%s.%s\""), nspname, prsname);
3177         else
3178                 sprintf(title, _("Text search parser \"%s\""), prsname);
3179         myopt.title = title;
3180         myopt.footers = NULL;
3181         myopt.default_footer = false;
3182         myopt.translate_header = true;
3183         myopt.translate_columns = translate_columns;
3184
3185         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3186
3187         PQclear(res);
3188
3189         initPQExpBuffer(&buf);
3190
3191         printfPQExpBuffer(&buf,
3192                                           "SELECT t.alias as \"%s\", \n"
3193                                           "  t.description as \"%s\" \n"
3194                           "FROM pg_catalog.ts_token_type( '%s'::pg_catalog.oid ) as t \n"
3195                                           "ORDER BY 1;",
3196                                           gettext_noop("Token name"),
3197                                           gettext_noop("Description"),
3198                                           oid);
3199
3200         res = PSQLexec(buf.data, false);
3201         termPQExpBuffer(&buf);
3202         if (!res)
3203                 return false;
3204
3205         myopt.nullPrint = NULL;
3206         if (nspname)
3207                 sprintf(title, _("Token types for parser \"%s.%s\""), nspname, prsname);
3208         else
3209                 sprintf(title, _("Token types for parser \"%s\""), prsname);
3210         myopt.title = title;
3211         myopt.footers = NULL;
3212         myopt.default_footer = true;
3213         myopt.translate_header = true;
3214         myopt.translate_columns = NULL;
3215
3216         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3217
3218         PQclear(res);
3219         return true;
3220 }
3221
3222
3223 /*
3224  * \dFd
3225  * list text search dictionaries
3226  */
3227 bool
3228 listTSDictionaries(const char *pattern, bool verbose)
3229 {
3230         PQExpBufferData buf;
3231         PGresult   *res;
3232         printQueryOpt myopt = pset.popt;
3233
3234         if (pset.sversion < 80300)
3235         {
3236                 fprintf(stderr, _("The server (version %d.%d) does not support full text search.\n"),
3237                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3238                 return true;
3239         }
3240
3241         initPQExpBuffer(&buf);
3242
3243         printfPQExpBuffer(&buf,
3244                                           "SELECT \n"
3245                                           "  n.nspname as \"%s\",\n"
3246                                           "  d.dictname as \"%s\",\n",
3247                                           gettext_noop("Schema"),
3248                                           gettext_noop("Name"));
3249
3250         if (verbose)
3251         {
3252                 appendPQExpBuffer(&buf,
3253                                                   "  ( SELECT COALESCE(nt.nspname, '(null)')::pg_catalog.text || '.' || t.tmplname FROM \n"
3254                                                   "    pg_catalog.pg_ts_template t \n"
3255                                                   "                      LEFT JOIN pg_catalog.pg_namespace nt ON nt.oid = t.tmplnamespace \n"
3256                                                   "                      WHERE d.dicttemplate = t.oid ) AS  \"%s\", \n"
3257                                                   "  d.dictinitoption as \"%s\", \n",
3258                                                   gettext_noop("Template"),
3259                                                   gettext_noop("Init options"));
3260         }
3261
3262         appendPQExpBuffer(&buf,
3263                          "  pg_catalog.obj_description(d.oid, 'pg_ts_dict') as \"%s\"\n",
3264                                           gettext_noop("Description"));
3265
3266         appendPQExpBuffer(&buf, "FROM pg_catalog.pg_ts_dict d\n"
3267                  "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = d.dictnamespace\n");
3268
3269         processSQLNamePattern(pset.db, &buf, pattern, false, false,
3270                                                   "n.nspname", "d.dictname", NULL,
3271                                                   "pg_catalog.pg_ts_dict_is_visible(d.oid)");
3272
3273         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
3274
3275         res = PSQLexec(buf.data, false);
3276         termPQExpBuffer(&buf);
3277         if (!res)
3278                 return false;
3279
3280         myopt.nullPrint = NULL;
3281         myopt.title = _("List of text search dictionaries");
3282         myopt.translate_header = true;
3283
3284         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3285
3286         PQclear(res);
3287         return true;
3288 }
3289
3290
3291 /*
3292  * \dFt
3293  * list text search templates
3294  */
3295 bool
3296 listTSTemplates(const char *pattern, bool verbose)
3297 {
3298         PQExpBufferData buf;
3299         PGresult   *res;
3300         printQueryOpt myopt = pset.popt;
3301
3302         if (pset.sversion < 80300)
3303         {
3304                 fprintf(stderr, _("The server (version %d.%d) does not support full text search.\n"),
3305                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3306                 return true;
3307         }
3308
3309         initPQExpBuffer(&buf);
3310
3311         if (verbose)
3312                 printfPQExpBuffer(&buf,
3313                                                   "SELECT \n"
3314                                                   "  n.nspname AS \"%s\",\n"
3315                                                   "  t.tmplname AS \"%s\",\n"
3316                                                   "  t.tmplinit::pg_catalog.regproc AS \"%s\",\n"
3317                                                   "  t.tmpllexize::pg_catalog.regproc AS \"%s\",\n"
3318                  "  pg_catalog.obj_description(t.oid, 'pg_ts_template') AS \"%s\"\n",
3319                                                   gettext_noop("Schema"),
3320                                                   gettext_noop("Name"),
3321                                                   gettext_noop("Init"),
3322                                                   gettext_noop("Lexize"),
3323                                                   gettext_noop("Description"));
3324         else
3325                 printfPQExpBuffer(&buf,
3326                                                   "SELECT \n"
3327                                                   "  n.nspname AS \"%s\",\n"
3328                                                   "  t.tmplname AS \"%s\",\n"
3329                  "  pg_catalog.obj_description(t.oid, 'pg_ts_template') AS \"%s\"\n",
3330                                                   gettext_noop("Schema"),
3331                                                   gettext_noop("Name"),
3332                                                   gettext_noop("Description"));
3333
3334         appendPQExpBuffer(&buf, "FROM pg_catalog.pg_ts_template t\n"
3335                  "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.tmplnamespace\n");
3336
3337         processSQLNamePattern(pset.db, &buf, pattern, false, false,
3338                                                   "n.nspname", "t.tmplname", NULL,
3339                                                   "pg_catalog.pg_ts_template_is_visible(t.oid)");
3340
3341         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
3342
3343         res = PSQLexec(buf.data, false);
3344         termPQExpBuffer(&buf);
3345         if (!res)
3346                 return false;
3347
3348         myopt.nullPrint = NULL;
3349         myopt.title = _("List of text search templates");
3350         myopt.translate_header = true;
3351
3352         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3353
3354         PQclear(res);
3355         return true;
3356 }
3357
3358
3359 /*
3360  * \dF
3361  * list text search configurations
3362  */
3363 bool
3364 listTSConfigs(const char *pattern, bool verbose)
3365 {
3366         PQExpBufferData buf;
3367         PGresult   *res;
3368         printQueryOpt myopt = pset.popt;
3369
3370         if (pset.sversion < 80300)
3371         {
3372                 fprintf(stderr, _("The server (version %d.%d) does not support full text search.\n"),
3373                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3374                 return true;
3375         }
3376
3377         if (verbose)
3378                 return listTSConfigsVerbose(pattern);
3379
3380         initPQExpBuffer(&buf);
3381
3382         printfPQExpBuffer(&buf,
3383                                           "SELECT \n"
3384                                           "   n.nspname as \"%s\",\n"
3385                                           "   c.cfgname as \"%s\",\n"
3386                    "   pg_catalog.obj_description(c.oid, 'pg_ts_config') as \"%s\"\n"
3387                                           "FROM pg_catalog.pg_ts_config c\n"
3388                   "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.cfgnamespace \n",
3389                                           gettext_noop("Schema"),
3390                                           gettext_noop("Name"),
3391                                           gettext_noop("Description")
3392                 );
3393
3394         processSQLNamePattern(pset.db, &buf, pattern, false, false,
3395                                                   "n.nspname", "c.cfgname", NULL,
3396                                                   "pg_catalog.pg_ts_config_is_visible(c.oid)");
3397
3398         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
3399
3400         res = PSQLexec(buf.data, false);
3401         termPQExpBuffer(&buf);
3402         if (!res)
3403                 return false;
3404
3405         myopt.nullPrint = NULL;
3406         myopt.title = _("List of text search configurations");
3407         myopt.translate_header = true;
3408
3409         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3410
3411         PQclear(res);
3412         return true;
3413 }
3414
3415 static bool
3416 listTSConfigsVerbose(const char *pattern)
3417 {
3418         PQExpBufferData buf;
3419         PGresult   *res;
3420         int                     i;
3421
3422         initPQExpBuffer(&buf);
3423
3424         printfPQExpBuffer(&buf,
3425                                           "SELECT c.oid, c.cfgname,\n"
3426                                           "   n.nspname, \n"
3427                                           "   p.prsname, \n"
3428                                           "   np.nspname as pnspname \n"
3429                                           "FROM pg_catalog.pg_ts_config c \n"
3430            "   LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.cfgnamespace, \n"
3431                                           " pg_catalog.pg_ts_parser p \n"
3432           "   LEFT JOIN pg_catalog.pg_namespace np ON np.oid = p.prsnamespace \n"
3433                                           "WHERE  p.oid = c.cfgparser\n"
3434                 );
3435
3436         processSQLNamePattern(pset.db, &buf, pattern, true, false,
3437                                                   "n.nspname", "c.cfgname", NULL,
3438                                                   "pg_catalog.pg_ts_config_is_visible(c.oid)");
3439
3440         appendPQExpBuffer(&buf, "ORDER BY 3, 2;");
3441
3442         res = PSQLexec(buf.data, false);
3443         termPQExpBuffer(&buf);
3444         if (!res)
3445                 return false;
3446
3447         if (PQntuples(res) == 0)
3448         {
3449                 if (!pset.quiet)
3450                         fprintf(stderr, _("Did not find any text search configuration named \"%s\".\n"),
3451                                         pattern);
3452                 PQclear(res);
3453                 return false;
3454         }
3455
3456         for (i = 0; i < PQntuples(res); i++)
3457         {
3458                 const char *oid;
3459                 const char *cfgname;
3460                 const char *nspname = NULL;
3461                 const char *prsname;
3462                 const char *pnspname = NULL;
3463
3464                 oid = PQgetvalue(res, i, 0);
3465                 cfgname = PQgetvalue(res, i, 1);
3466                 if (!PQgetisnull(res, i, 2))
3467                         nspname = PQgetvalue(res, i, 2);
3468                 prsname = PQgetvalue(res, i, 3);
3469                 if (!PQgetisnull(res, i, 4))
3470                         pnspname = PQgetvalue(res, i, 4);
3471
3472                 if (!describeOneTSConfig(oid, nspname, cfgname, pnspname, prsname))
3473                 {
3474                         PQclear(res);
3475                         return false;
3476                 }
3477
3478                 if (cancel_pressed)
3479                 {
3480                         PQclear(res);
3481                         return false;
3482                 }
3483         }
3484
3485         PQclear(res);
3486         return true;
3487 }
3488
3489 static bool
3490 describeOneTSConfig(const char *oid, const char *nspname, const char *cfgname,
3491                                         const char *pnspname, const char *prsname)
3492 {
3493         PQExpBufferData buf,
3494                                 title;
3495         PGresult   *res;
3496         printQueryOpt myopt = pset.popt;
3497
3498         initPQExpBuffer(&buf);
3499
3500         printfPQExpBuffer(&buf,
3501                                           "SELECT \n"
3502                                           "  ( SELECT t.alias FROM \n"
3503                                           "    pg_catalog.ts_token_type(c.cfgparser) AS t \n"
3504                                           "    WHERE t.tokid = m.maptokentype ) AS \"%s\", \n"
3505                                           "  pg_catalog.btrim( \n"
3506                                   "    ARRAY( SELECT mm.mapdict::pg_catalog.regdictionary \n"
3507                                           "           FROM pg_catalog.pg_ts_config_map AS mm \n"
3508                                           "           WHERE mm.mapcfg = m.mapcfg AND mm.maptokentype = m.maptokentype \n"
3509                                           "           ORDER BY mapcfg, maptokentype, mapseqno \n"
3510                                           "    ) :: pg_catalog.text , \n"
3511                                           "  '{}') AS \"%s\" \n"
3512          "FROM pg_catalog.pg_ts_config AS c, pg_catalog.pg_ts_config_map AS m \n"
3513                                           "WHERE c.oid = '%s' AND m.mapcfg = c.oid \n"
3514                                           "GROUP BY m.mapcfg, m.maptokentype, c.cfgparser \n"
3515                                           "ORDER BY 1",
3516                                           gettext_noop("Token"),
3517                                           gettext_noop("Dictionaries"),
3518                                           oid);
3519
3520         res = PSQLexec(buf.data, false);
3521         termPQExpBuffer(&buf);
3522         if (!res)
3523                 return false;
3524
3525         initPQExpBuffer(&title);
3526
3527         if (nspname)
3528                 appendPQExpBuffer(&title, _("Text search configuration \"%s.%s\""),
3529                                                   nspname, cfgname);
3530         else
3531                 appendPQExpBuffer(&title, _("Text search configuration \"%s\""),
3532                                                   cfgname);
3533
3534         if (pnspname)
3535                 appendPQExpBuffer(&title, _("\nParser: \"%s.%s\""),
3536                                                   pnspname, prsname);
3537         else
3538                 appendPQExpBuffer(&title, _("\nParser: \"%s\""),
3539                                                   prsname);
3540
3541         myopt.nullPrint = NULL;
3542         myopt.title = title.data;
3543         myopt.footers = NULL;
3544         myopt.default_footer = false;
3545         myopt.translate_header = true;
3546
3547         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3548
3549         termPQExpBuffer(&title);
3550
3551         PQclear(res);
3552         return true;
3553 }
3554
3555
3556 /*
3557  * \dew
3558  *
3559  * Describes foreign-data wrappers
3560  */
3561 bool
3562 listForeignDataWrappers(const char *pattern, bool verbose)
3563 {
3564         PQExpBufferData buf;
3565         PGresult   *res;
3566         printQueryOpt myopt = pset.popt;
3567
3568         if (pset.sversion < 80400)
3569         {
3570                 fprintf(stderr, _("The server (version %d.%d) does not support foreign-data wrappers.\n"),
3571                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3572                 return true;
3573         }
3574
3575         initPQExpBuffer(&buf);
3576         printfPQExpBuffer(&buf,
3577                                           "SELECT fdwname AS \"%s\",\n"
3578                                           "  pg_catalog.pg_get_userbyid(fdwowner) AS \"%s\",\n",
3579                                           gettext_noop("Name"),
3580                                           gettext_noop("Owner"));
3581         if (pset.sversion >= 90100)
3582                 appendPQExpBuffer(&buf,
3583                                                   "  fdwhandler::pg_catalog.regproc AS \"%s\",\n",
3584                                                   gettext_noop("Handler"));
3585         appendPQExpBuffer(&buf,
3586                                           "  fdwvalidator::pg_catalog.regproc AS \"%s\"",
3587                                           gettext_noop("Validator"));
3588
3589         if (verbose)
3590         {
3591                 appendPQExpBuffer(&buf, ",\n  ");
3592                 printACLColumn(&buf, "fdwacl");
3593                 appendPQExpBuffer(&buf,
3594                                                   ",\n  fdwoptions AS \"%s\"",
3595                                                   gettext_noop("Options"));
3596         }
3597
3598         appendPQExpBuffer(&buf, "\nFROM pg_catalog.pg_foreign_data_wrapper\n");
3599
3600         processSQLNamePattern(pset.db, &buf, pattern, false, false,
3601                                                   NULL, "fdwname", NULL, NULL);
3602
3603         appendPQExpBuffer(&buf, "ORDER BY 1;");
3604
3605         res = PSQLexec(buf.data, false);
3606         termPQExpBuffer(&buf);
3607         if (!res)
3608                 return false;
3609
3610         myopt.nullPrint = NULL;
3611         myopt.title = _("List of foreign-data wrappers");
3612         myopt.translate_header = true;
3613
3614         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3615
3616         PQclear(res);
3617         return true;
3618 }
3619
3620 /*
3621  * \des
3622  *
3623  * Describes foreign servers.
3624  */
3625 bool
3626 listForeignServers(const char *pattern, bool verbose)
3627 {
3628         PQExpBufferData buf;
3629         PGresult   *res;
3630         printQueryOpt myopt = pset.popt;
3631
3632         if (pset.sversion < 80400)
3633         {
3634                 fprintf(stderr, _("The server (version %d.%d) does not support foreign servers.\n"),
3635                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3636                 return true;
3637         }
3638
3639         initPQExpBuffer(&buf);
3640         printfPQExpBuffer(&buf,
3641                                           "SELECT s.srvname AS \"%s\",\n"
3642                                           "  pg_catalog.pg_get_userbyid(s.srvowner) AS \"%s\",\n"
3643                                           "  f.fdwname AS \"%s\"",
3644                                           gettext_noop("Name"),
3645                                           gettext_noop("Owner"),
3646                                           gettext_noop("Foreign-data wrapper"));
3647
3648         if (verbose)
3649         {
3650                 appendPQExpBuffer(&buf, ",\n  ");
3651                 printACLColumn(&buf, "s.srvacl");
3652                 appendPQExpBuffer(&buf,
3653                                                   ",\n"
3654                                                   "  s.srvtype AS \"%s\",\n"
3655                                                   "  s.srvversion AS \"%s\",\n"
3656                                                   "  s.srvoptions AS \"%s\"",
3657                                                   gettext_noop("Type"),
3658                                                   gettext_noop("Version"),
3659                                                   gettext_noop("Options"));
3660         }
3661
3662         appendPQExpBuffer(&buf,
3663                                           "\nFROM pg_catalog.pg_foreign_server s\n"
3664            "     JOIN pg_catalog.pg_foreign_data_wrapper f ON f.oid=s.srvfdw\n");
3665
3666         processSQLNamePattern(pset.db, &buf, pattern, false, false,
3667                                                   NULL, "s.srvname", NULL, NULL);
3668
3669         appendPQExpBuffer(&buf, "ORDER BY 1;");
3670
3671         res = PSQLexec(buf.data, false);
3672         termPQExpBuffer(&buf);
3673         if (!res)
3674                 return false;
3675
3676         myopt.nullPrint = NULL;
3677         myopt.title = _("List of foreign servers");
3678         myopt.translate_header = true;
3679
3680         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3681
3682         PQclear(res);
3683         return true;
3684 }
3685
3686 /*
3687  * \deu
3688  *
3689  * Describes user mappings.
3690  */
3691 bool
3692 listUserMappings(const char *pattern, bool verbose)
3693 {
3694         PQExpBufferData buf;
3695         PGresult   *res;
3696         printQueryOpt myopt = pset.popt;
3697
3698         if (pset.sversion < 80400)
3699         {
3700                 fprintf(stderr, _("The server (version %d.%d) does not support user mappings.\n"),
3701                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3702                 return true;
3703         }
3704
3705         initPQExpBuffer(&buf);
3706         printfPQExpBuffer(&buf,
3707                                           "SELECT um.srvname AS \"%s\",\n"
3708                                           "  um.usename AS \"%s\"",
3709                                           gettext_noop("Server"),
3710                                           gettext_noop("User name"));
3711
3712         if (verbose)
3713                 appendPQExpBuffer(&buf,
3714                                                   ",\n  um.umoptions AS \"%s\"",
3715                                                   gettext_noop("Options"));
3716
3717         appendPQExpBuffer(&buf, "\nFROM pg_catalog.pg_user_mappings um\n");
3718
3719         processSQLNamePattern(pset.db, &buf, pattern, false, false,
3720                                                   NULL, "um.srvname", "um.usename", NULL);
3721
3722         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
3723
3724         res = PSQLexec(buf.data, false);
3725         termPQExpBuffer(&buf);
3726         if (!res)
3727                 return false;
3728
3729         myopt.nullPrint = NULL;
3730         myopt.title = _("List of user mappings");
3731         myopt.translate_header = true;
3732
3733         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3734
3735         PQclear(res);
3736         return true;
3737 }
3738
3739 /*
3740  * \det
3741  *
3742  * Describes foreign tables.
3743  */
3744 bool
3745 listForeignTables(const char *pattern, bool verbose)
3746 {
3747         PQExpBufferData buf;
3748         PGresult   *res;
3749         printQueryOpt myopt = pset.popt;
3750
3751         if (pset.sversion < 90100)
3752         {
3753                 fprintf(stderr, _("The server (version %d.%d) does not support foreign tables.\n"),
3754                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3755                 return true;
3756         }
3757
3758         initPQExpBuffer(&buf);
3759         printfPQExpBuffer(&buf,
3760                                           "SELECT n.nspname AS \"%s\",\n"
3761                                           "  c.relname AS \"%s\",\n"
3762                                           "  s.srvname AS \"%s\"",
3763                                           gettext_noop("Schema"),
3764                                           gettext_noop("Table"),
3765                                           gettext_noop("Server"));
3766
3767         if (verbose)
3768                 appendPQExpBuffer(&buf,
3769                                                   ",\n  ft.ftoptions AS \"%s\"",
3770                                                   gettext_noop("Options"));
3771
3772         appendPQExpBuffer(&buf, "\nFROM pg_catalog.pg_foreign_table ft,");
3773         appendPQExpBuffer(&buf, "\n pg_catalog.pg_class c,");
3774         appendPQExpBuffer(&buf, "\n pg_catalog.pg_namespace n,");
3775         appendPQExpBuffer(&buf, "\n pg_catalog.pg_foreign_server s\n");
3776         appendPQExpBuffer(&buf, "\nWHERE c.oid = ft.ftrelid");
3777         appendPQExpBuffer(&buf, "\nAND s.oid = ft.ftserver\n");
3778         appendPQExpBuffer(&buf, "\nAND n.oid = c.relnamespace\n");
3779
3780         processSQLNamePattern(pset.db, &buf, pattern, true, false,
3781                                                   NULL, "n.nspname", "c.relname", NULL);
3782
3783         appendPQExpBuffer(&buf, "ORDER BY 1, 2;");
3784
3785         res = PSQLexec(buf.data, false);
3786         termPQExpBuffer(&buf);
3787         if (!res)
3788                 return false;
3789
3790         myopt.nullPrint = NULL;
3791         myopt.title = _("List of foreign tables");
3792         myopt.translate_header = true;
3793
3794         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3795
3796         PQclear(res);
3797         return true;
3798 }
3799
3800 /*
3801  * \dx
3802  *
3803  * Briefly describes installed extensions.
3804  */
3805 bool
3806 listExtensions(const char *pattern)
3807 {
3808         PQExpBufferData buf;
3809         PGresult   *res;
3810         printQueryOpt myopt = pset.popt;
3811
3812         if (pset.sversion < 90100)
3813         {
3814                 fprintf(stderr, _("The server (version %d.%d) does not support extensions.\n"),
3815                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3816                 return true;
3817         }
3818
3819         initPQExpBuffer(&buf);
3820         printfPQExpBuffer(&buf,
3821                                           "SELECT e.extname AS \"%s\", "
3822                                           "e.extversion AS \"%s\", n.nspname AS \"%s\", c.description AS \"%s\"\n"
3823                                           "FROM pg_catalog.pg_extension e "
3824                                           "LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace "
3825                                           "LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid "
3826                                           "AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass\n",
3827                                           gettext_noop("Name"),
3828                                           gettext_noop("Version"),
3829                                           gettext_noop("Schema"),
3830                                           gettext_noop("Description"));
3831
3832         processSQLNamePattern(pset.db, &buf, pattern,
3833                                                   false, false,
3834                                                   NULL, "e.extname", NULL,
3835                                                   NULL);
3836
3837         appendPQExpBuffer(&buf, "ORDER BY 1;");
3838
3839         res = PSQLexec(buf.data, false);
3840         termPQExpBuffer(&buf);
3841         if (!res)
3842                 return false;
3843
3844         myopt.nullPrint = NULL;
3845         myopt.title = _("List of installed extensions");
3846         myopt.translate_header = true;
3847
3848         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3849
3850         PQclear(res);
3851         return true;
3852 }
3853
3854 /*
3855  * \dx+
3856  *
3857  * List contents of installed extensions.
3858  */
3859 bool
3860 listExtensionContents(const char *pattern)
3861 {
3862         PQExpBufferData buf;
3863         PGresult   *res;
3864         int                     i;
3865
3866         if (pset.sversion < 90100)
3867         {
3868                 fprintf(stderr, _("The server (version %d.%d) does not support extensions.\n"),
3869                                 pset.sversion / 10000, (pset.sversion / 100) % 100);
3870                 return true;
3871         }
3872
3873         initPQExpBuffer(&buf);
3874         printfPQExpBuffer(&buf,
3875                                           "SELECT e.extname, e.oid\n"
3876                                           "FROM pg_catalog.pg_extension e\n");
3877
3878         processSQLNamePattern(pset.db, &buf, pattern,
3879                                                   false, false,
3880                                                   NULL, "e.extname", NULL,
3881                                                   NULL);
3882
3883         appendPQExpBuffer(&buf, "ORDER BY 1;");
3884
3885         res = PSQLexec(buf.data, false);
3886         termPQExpBuffer(&buf);
3887         if (!res)
3888                 return false;
3889
3890         if (PQntuples(res) == 0)
3891         {
3892                 if (!pset.quiet)
3893                 {
3894                         if (pattern)
3895                                 fprintf(stderr, _("Did not find any extension named \"%s\".\n"),
3896                                                 pattern);
3897                         else
3898                                 fprintf(stderr, _("Did not find any extensions.\n"));
3899                 }
3900                 PQclear(res);
3901                 return false;
3902         }
3903
3904         for (i = 0; i < PQntuples(res); i++)
3905         {
3906                 const char *extname;
3907                 const char *oid;
3908
3909                 extname = PQgetvalue(res, i, 0);
3910                 oid = PQgetvalue(res, i, 1);
3911
3912                 if (!listOneExtensionContents(extname, oid))
3913                 {
3914                         PQclear(res);
3915                         return false;
3916                 }
3917                 if (cancel_pressed)
3918                 {
3919                         PQclear(res);
3920                         return false;
3921                 }
3922         }
3923
3924         PQclear(res);
3925         return true;
3926 }
3927
3928 static bool
3929 listOneExtensionContents(const char *extname, const char *oid)
3930 {
3931         PQExpBufferData buf;
3932         PGresult   *res;
3933         char            title[1024];
3934         printQueryOpt myopt = pset.popt;
3935
3936         initPQExpBuffer(&buf);
3937         printfPQExpBuffer(&buf,
3938                                           "SELECT pg_catalog.pg_describe_object(classid, objid, 0) AS \"%s\"\n"
3939                                           "FROM pg_catalog.pg_depend\n"
3940                                           "WHERE refclassid = 'pg_catalog.pg_extension'::pg_catalog.regclass AND refobjid = '%s' AND deptype = 'e'\n"
3941                                           "ORDER BY 1;",
3942                                           gettext_noop("Object Description"),
3943                                           oid);
3944
3945         res = PSQLexec(buf.data, false);
3946         termPQExpBuffer(&buf);
3947         if (!res)
3948                 return false;
3949
3950         myopt.nullPrint = NULL;
3951         snprintf(title, sizeof(title), _("Objects in extension \"%s\""), extname);
3952         myopt.title = title;
3953         myopt.translate_header = true;
3954
3955         printQuery(res, &myopt, pset.queryFout, pset.logfile);
3956
3957         PQclear(res);
3958         return true;
3959 }
3960
3961 /*
3962  * printACLColumn
3963  *
3964  * Helper function for consistently formatting ACL (privilege) columns.
3965  * The proper targetlist entry is appended to buf.      Note lack of any
3966  * whitespace or comma decoration.
3967  */
3968 static void
3969 printACLColumn(PQExpBuffer buf, const char *colname)
3970 {
3971         if (pset.sversion >= 80100)
3972                 appendPQExpBuffer(buf,
3973                                                   "pg_catalog.array_to_string(%s, E'\\n') AS \"%s\"",
3974                                                   colname, gettext_noop("Access privileges"));
3975         else
3976                 appendPQExpBuffer(buf,
3977                                                   "pg_catalog.array_to_string(%s, '\\n') AS \"%s\"",
3978                                                   colname, gettext_noop("Access privileges"));
3979 }