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