PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
oid2name.c
Go to the documentation of this file.
1 /*
2  * oid2name, a PostgreSQL app to map OIDs on the filesystem
3  * to table and database names.
4  *
5  * Originally by
6  * B. Palmer, bpalmer@crimelabs.net 1-17-2001
7  *
8  * contrib/oid2name/oid2name.c
9  */
10 #include "postgres_fe.h"
11 
12 #include "catalog/pg_class.h"
13 
14 #include "libpq-fe.h"
15 #include "pg_getopt.h"
16 
17 /* an extensible array to keep track of elements to show */
18 typedef struct
19 {
20  char **array;
21  int num;
22  int alloc;
23 } eary;
24 
25 /* these are the opts structures for command line params */
26 struct options
27 {
31 
32  bool quiet;
33  bool systables;
34  bool indexes;
35  bool nodb;
36  bool extended;
38 
39  char *dbname;
40  char *hostname;
41  char *port;
42  char *username;
43  const char *progname;
44 };
45 
46 /* function prototypes */
47 static void help(const char *progname);
48 void get_opts(int, char **, struct options *);
49 void add_one_elt(char *eltname, eary *eary);
50 char *get_comma_elts(eary *eary);
51 PGconn *sql_conn(struct options *);
52 int sql_exec(PGconn *, const char *sql, bool quiet);
53 void sql_exec_dumpalldbs(PGconn *, struct options *);
54 void sql_exec_dumpalltables(PGconn *, struct options *);
55 void sql_exec_searchtables(PGconn *, struct options *);
56 void sql_exec_dumpalltbspc(PGconn *, struct options *);
57 
58 /* function to parse command line options and check for some usage errors. */
59 void
60 get_opts(int argc, char **argv, struct options *my_opts)
61 {
62  int c;
63  const char *progname;
64 
65  progname = get_progname(argv[0]);
66 
67  /* set the defaults */
68  my_opts->quiet = false;
69  my_opts->systables = false;
70  my_opts->indexes = false;
71  my_opts->nodb = false;
72  my_opts->extended = false;
73  my_opts->tablespaces = false;
74  my_opts->dbname = NULL;
75  my_opts->hostname = NULL;
76  my_opts->port = NULL;
77  my_opts->username = NULL;
78  my_opts->progname = progname;
79 
80  if (argc > 1)
81  {
82  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
83  {
84  help(progname);
85  exit(0);
86  }
87  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
88  {
89  puts("oid2name (PostgreSQL) " PG_VERSION);
90  exit(0);
91  }
92  }
93 
94  /* get opts */
95  while ((c = getopt(argc, argv, "H:p:U:d:t:o:f:qSxish")) != -1)
96  {
97  switch (c)
98  {
99  /* specify the database */
100  case 'd':
101  my_opts->dbname = pg_strdup(optarg);
102  break;
103 
104  /* specify one tablename to show */
105  case 't':
106  add_one_elt(optarg, my_opts->tables);
107  break;
108 
109  /* specify one Oid to show */
110  case 'o':
111  add_one_elt(optarg, my_opts->oids);
112  break;
113 
114  /* specify one filenode to show */
115  case 'f':
116  add_one_elt(optarg, my_opts->filenodes);
117  break;
118 
119  /* don't show headers */
120  case 'q':
121  my_opts->quiet = true;
122  break;
123 
124  /* host to connect to */
125  case 'H':
126  my_opts->hostname = pg_strdup(optarg);
127  break;
128 
129  /* port to connect to on remote host */
130  case 'p':
131  my_opts->port = pg_strdup(optarg);
132  break;
133 
134  /* username */
135  case 'U':
136  my_opts->username = pg_strdup(optarg);
137  break;
138 
139  /* display system tables */
140  case 'S':
141  my_opts->systables = true;
142  break;
143 
144  /* also display indexes */
145  case 'i':
146  my_opts->indexes = true;
147  break;
148 
149  /* display extra columns */
150  case 'x':
151  my_opts->extended = true;
152  break;
153 
154  /* dump tablespaces only */
155  case 's':
156  my_opts->tablespaces = true;
157  break;
158 
159  case 'h':
160  help(progname);
161  exit(0);
162  break;
163 
164  default:
165  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
166  exit(1);
167  }
168  }
169 }
170 
171 static void
172 help(const char *progname)
173 {
174  printf("%s helps examining the file structure used by PostgreSQL.\n\n"
175  "Usage:\n"
176  " %s [OPTION]...\n"
177  "\nOptions:\n"
178  " -d DBNAME database to connect to\n"
179  " -f FILENODE show info for table with given file node\n"
180  " -H HOSTNAME database server host or socket directory\n"
181  " -i show indexes and sequences too\n"
182  " -o OID show info for table with given OID\n"
183  " -p PORT database server port number\n"
184  " -q quiet (don't show headers)\n"
185  " -s show all tablespaces\n"
186  " -S show system objects too\n"
187  " -t TABLE show info for named table\n"
188  " -U NAME connect as specified database user\n"
189  " -V, --version output version information, then exit\n"
190  " -x extended (show additional columns)\n"
191  " -?, --help show this help, then exit\n"
192  "\nThe default action is to show all database OIDs.\n\n"
193  "Report bugs to <pgsql-bugs@postgresql.org>.\n",
194  progname, progname);
195 }
196 
197 /*
198  * add_one_elt
199  *
200  * Add one element to a (possibly empty) eary struct.
201  */
202 void
203 add_one_elt(char *eltname, eary *eary)
204 {
205  if (eary->alloc == 0)
206  {
207  eary ->alloc = 8;
208  eary ->array = (char **) pg_malloc(8 * sizeof(char *));
209  }
210  else if (eary->num >= eary->alloc)
211  {
212  eary ->alloc *= 2;
213  eary ->array = (char **) pg_realloc(eary->array,
214  eary->alloc * sizeof(char *));
215  }
216 
217  eary ->array[eary->num] = pg_strdup(eltname);
218  eary ->num++;
219 }
220 
221 /*
222  * get_comma_elts
223  *
224  * Return the elements of an eary as a (freshly allocated) single string, in
225  * single quotes, separated by commas and properly escaped for insertion in an
226  * SQL statement.
227  */
228 char *
230 {
231  char *ret,
232  *ptr;
233  int i,
234  length = 0;
235 
236  if (eary->num == 0)
237  return pg_strdup("");
238 
239  /*
240  * PQescapeString wants 2 * length + 1 bytes of breath space. Add two
241  * chars per element for the single quotes and one for the comma.
242  */
243  for (i = 0; i < eary->num; i++)
244  length += strlen(eary->array[i]);
245 
246  ret = (char *) pg_malloc(length * 2 + 4 * eary->num);
247  ptr = ret;
248 
249  for (i = 0; i < eary->num; i++)
250  {
251  if (i != 0)
252  sprintf(ptr++, ",");
253  sprintf(ptr++, "'");
254  ptr += PQescapeString(ptr, eary->array[i], strlen(eary->array[i]));
255  sprintf(ptr++, "'");
256  }
257 
258  return ret;
259 }
260 
261 /* establish connection with database. */
262 PGconn *
263 sql_conn(struct options *my_opts)
264 {
265  PGconn *conn;
266  bool have_password = false;
267  char password[100];
268  bool new_pass;
269 
270  /*
271  * Start the connection. Loop until we have a password if requested by
272  * backend.
273  */
274  do
275  {
276 #define PARAMS_ARRAY_SIZE 7
277 
278  const char *keywords[PARAMS_ARRAY_SIZE];
279  const char *values[PARAMS_ARRAY_SIZE];
280 
281  keywords[0] = "host";
282  values[0] = my_opts->hostname;
283  keywords[1] = "port";
284  values[1] = my_opts->port;
285  keywords[2] = "user";
286  values[2] = my_opts->username;
287  keywords[3] = "password";
288  values[3] = have_password ? password : NULL;
289  keywords[4] = "dbname";
290  values[4] = my_opts->dbname;
291  keywords[5] = "fallback_application_name";
292  values[5] = my_opts->progname;
293  keywords[6] = NULL;
294  values[6] = NULL;
295 
296  new_pass = false;
297  conn = PQconnectdbParams(keywords, values, true);
298 
299  if (!conn)
300  {
301  fprintf(stderr, "%s: could not connect to database %s\n",
302  "oid2name", my_opts->dbname);
303  exit(1);
304  }
305 
306  if (PQstatus(conn) == CONNECTION_BAD &&
308  !have_password)
309  {
310  PQfinish(conn);
311  simple_prompt("Password: ", password, sizeof(password), false);
312  have_password = true;
313  new_pass = true;
314  }
315  } while (new_pass);
316 
317  /* check to see that the backend connection was successfully made */
318  if (PQstatus(conn) == CONNECTION_BAD)
319  {
320  fprintf(stderr, "%s: could not connect to database %s: %s",
321  "oid2name", my_opts->dbname, PQerrorMessage(conn));
322  PQfinish(conn);
323  exit(1);
324  }
325 
326  /* return the conn if good */
327  return conn;
328 }
329 
330 /*
331  * Actual code to make call to the database and print the output data.
332  */
333 int
334 sql_exec(PGconn *conn, const char *todo, bool quiet)
335 {
336  PGresult *res;
337 
338  int nfields;
339  int nrows;
340  int i,
341  j,
342  l;
343  int *length;
344  char *pad;
345 
346  /* make the call */
347  res = PQexec(conn, todo);
348 
349  /* check and deal with errors */
350  if (!res || PQresultStatus(res) > 2)
351  {
352  fprintf(stderr, "oid2name: query failed: %s\n", PQerrorMessage(conn));
353  fprintf(stderr, "oid2name: query was: %s\n", todo);
354 
355  PQclear(res);
356  PQfinish(conn);
357  exit(-1);
358  }
359 
360  /* get the number of fields */
361  nrows = PQntuples(res);
362  nfields = PQnfields(res);
363 
364  /* for each field, get the needed width */
365  length = (int *) pg_malloc(sizeof(int) * nfields);
366  for (j = 0; j < nfields; j++)
367  length[j] = strlen(PQfname(res, j));
368 
369  for (i = 0; i < nrows; i++)
370  {
371  for (j = 0; j < nfields; j++)
372  {
373  l = strlen(PQgetvalue(res, i, j));
374  if (l > length[j])
375  length[j] = strlen(PQgetvalue(res, i, j));
376  }
377  }
378 
379  /* print a header */
380  if (!quiet)
381  {
382  for (j = 0, l = 0; j < nfields; j++)
383  {
384  fprintf(stdout, "%*s", length[j] + 2, PQfname(res, j));
385  l += length[j] + 2;
386  }
387  fprintf(stdout, "\n");
388  pad = (char *) pg_malloc(l + 1);
389  MemSet(pad, '-', l);
390  pad[l] = '\0';
391  fprintf(stdout, "%s\n", pad);
392  free(pad);
393  }
394 
395  /* for each row, dump the information */
396  for (i = 0; i < nrows; i++)
397  {
398  for (j = 0; j < nfields; j++)
399  fprintf(stdout, "%*s", length[j] + 2, PQgetvalue(res, i, j));
400  fprintf(stdout, "\n");
401  }
402 
403  /* cleanup */
404  PQclear(res);
405  free(length);
406 
407  return 0;
408 }
409 
410 /*
411  * Dump all databases. There are no system objects to worry about.
412  */
413 void
415 {
416  char todo[1024];
417 
418  /* get the oid and database name from the system pg_database table */
419  snprintf(todo, sizeof(todo),
420  "SELECT d.oid AS \"Oid\", datname AS \"Database Name\", "
421  "spcname AS \"Tablespace\" FROM pg_catalog.pg_database d JOIN pg_catalog.pg_tablespace t ON "
422  "(dattablespace = t.oid) ORDER BY 2");
423 
424  sql_exec(conn, todo, opts->quiet);
425 }
426 
427 /*
428  * Dump all tables, indexes and sequences in the current database.
429  */
430 void
432 {
433  char todo[1024];
434  char *addfields = ",c.oid AS \"Oid\", nspname AS \"Schema\", spcname as \"Tablespace\" ";
435 
436  snprintf(todo, sizeof(todo),
437  "SELECT pg_catalog.pg_relation_filenode(c.oid) as \"Filenode\", relname as \"Table Name\" %s "
438  "FROM pg_catalog.pg_class c "
439  " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace "
440  " LEFT JOIN pg_catalog.pg_database d ON d.datname = pg_catalog.current_database(),"
441  " pg_catalog.pg_tablespace t "
442  "WHERE relkind IN (" CppAsString2(RELKIND_RELATION) ","
443  CppAsString2(RELKIND_MATVIEW) "%s%s) AND "
444  " %s"
445  " t.oid = CASE"
446  " WHEN reltablespace <> 0 THEN reltablespace"
447  " ELSE dattablespace"
448  " END "
449  "ORDER BY relname",
450  opts->extended ? addfields : "",
452  opts->systables ? "," CppAsString2(RELKIND_TOASTVALUE) : "",
453  opts->systables ? "" : "n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname !~ '^pg_toast' AND");
454 
455  sql_exec(conn, todo, opts->quiet);
456 }
457 
458 /*
459  * Show oid, filenode, name, schema and tablespace for each of the
460  * given objects in the current database.
461  */
462 void
464 {
465  char *todo;
466  char *qualifiers,
467  *ptr;
468  char *comma_oids,
469  *comma_filenodes,
470  *comma_tables;
471  bool written = false;
472  char *addfields = ",c.oid AS \"Oid\", nspname AS \"Schema\", spcname as \"Tablespace\" ";
473 
474  /* get tables qualifiers, whether names, filenodes, or OIDs */
475  comma_oids = get_comma_elts(opts->oids);
476  comma_tables = get_comma_elts(opts->tables);
477  comma_filenodes = get_comma_elts(opts->filenodes);
478 
479  /* 80 extra chars for SQL expression */
480  qualifiers = (char *) pg_malloc(strlen(comma_oids) + strlen(comma_tables) +
481  strlen(comma_filenodes) + 80);
482  ptr = qualifiers;
483 
484  if (opts->oids->num > 0)
485  {
486  ptr += sprintf(ptr, "c.oid IN (%s)", comma_oids);
487  written = true;
488  }
489  if (opts->filenodes->num > 0)
490  {
491  if (written)
492  ptr += sprintf(ptr, " OR ");
493  ptr += sprintf(ptr, "pg_catalog.pg_relation_filenode(c.oid) IN (%s)", comma_filenodes);
494  written = true;
495  }
496  if (opts->tables->num > 0)
497  {
498  if (written)
499  ptr += sprintf(ptr, " OR ");
500  sprintf(ptr, "c.relname ~~ ANY (ARRAY[%s])", comma_tables);
501  }
502  free(comma_oids);
503  free(comma_tables);
504  free(comma_filenodes);
505 
506  /* now build the query */
507  todo = psprintf(
508  "SELECT pg_catalog.pg_relation_filenode(c.oid) as \"Filenode\", relname as \"Table Name\" %s\n"
509  "FROM pg_catalog.pg_class c\n"
510  " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"
511  " LEFT JOIN pg_catalog.pg_database d ON d.datname = pg_catalog.current_database(),\n"
512  " pg_catalog.pg_tablespace t\n"
513  "WHERE relkind IN (" CppAsString2(RELKIND_RELATION) ","
518  " t.oid = CASE\n"
519  " WHEN reltablespace <> 0 THEN reltablespace\n"
520  " ELSE dattablespace\n"
521  " END AND\n"
522  " (%s)\n"
523  "ORDER BY relname\n",
524  opts->extended ? addfields : "",
525  qualifiers);
526 
527  free(qualifiers);
528 
529  sql_exec(conn, todo, opts->quiet);
530 }
531 
532 void
534 {
535  char todo[1024];
536 
537  snprintf(todo, sizeof(todo),
538  "SELECT oid AS \"Oid\", spcname as \"Tablespace Name\"\n"
539  "FROM pg_catalog.pg_tablespace");
540 
541  sql_exec(conn, todo, opts->quiet);
542 }
543 
544 int
545 main(int argc, char **argv)
546 {
547  struct options *my_opts;
548  PGconn *pgconn;
549 
550  my_opts = (struct options *) pg_malloc(sizeof(struct options));
551 
552  my_opts->oids = (eary *) pg_malloc(sizeof(eary));
553  my_opts->tables = (eary *) pg_malloc(sizeof(eary));
554  my_opts->filenodes = (eary *) pg_malloc(sizeof(eary));
555 
556  my_opts->oids->num = my_opts->oids->alloc = 0;
557  my_opts->tables->num = my_opts->tables->alloc = 0;
558  my_opts->filenodes->num = my_opts->filenodes->alloc = 0;
559 
560  /* parse the opts */
561  get_opts(argc, argv, my_opts);
562 
563  if (my_opts->dbname == NULL)
564  {
565  my_opts->dbname = "postgres";
566  my_opts->nodb = true;
567  }
568  pgconn = sql_conn(my_opts);
569 
570  /* display only tablespaces */
571  if (my_opts->tablespaces)
572  {
573  if (!my_opts->quiet)
574  printf("All tablespaces:\n");
575  sql_exec_dumpalltbspc(pgconn, my_opts);
576 
577  PQfinish(pgconn);
578  exit(0);
579  }
580 
581  /* display the given elements in the database */
582  if (my_opts->oids->num > 0 ||
583  my_opts->tables->num > 0 ||
584  my_opts->filenodes->num > 0)
585  {
586  if (!my_opts->quiet)
587  printf("From database \"%s\":\n", my_opts->dbname);
588  sql_exec_searchtables(pgconn, my_opts);
589 
590  PQfinish(pgconn);
591  exit(0);
592  }
593 
594  /* no elements given; dump the given database */
595  if (my_opts->dbname && !my_opts->nodb)
596  {
597  if (!my_opts->quiet)
598  printf("From database \"%s\":\n", my_opts->dbname);
599  sql_exec_dumpalltables(pgconn, my_opts);
600 
601  PQfinish(pgconn);
602  exit(0);
603  }
604 
605  /* no database either; dump all databases */
606  if (!my_opts->quiet)
607  printf("All databases:\n");
608  sql_exec_dumpalldbs(pgconn, my_opts);
609 
610  PQfinish(pgconn);
611  return 0;
612 }
int sql_exec(PGconn *, const char *sql, bool quiet)
Definition: oid2name.c:334
static char password[100]
Definition: streamutil.c:45
int length(const List *list)
Definition: list.c:1271
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2732
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6097
Definition: oid2name.c:18
void sql_exec_dumpalltbspc(PGconn *, struct options *)
Definition: oid2name.c:533
size_t PQescapeString(char *to, const char *from, size_t length)
Definition: fe-exec.c:3383
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3118
char * PQfname(const PGresult *res, int field_num)
Definition: fe-exec.c:2810
void * pg_malloc(size_t size)
Definition: fe_memutils.c:47
const char * get_progname(const char *argv0)
Definition: path.c:453
PGconn * sql_conn(struct options *)
Definition: oid2name.c:263
void get_opts(int, char **, struct options *)
Definition: oid2name.c:60
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define RELKIND_MATVIEW
Definition: pg_class.h:165
#define PARAMS_ARRAY_SIZE
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3630
#define MemSet(start, val, len)
Definition: c.h:863
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
char * hostname
Definition: oid2name.c:40
bool nodb
Definition: oid2name.c:35
const char * progname
Definition: pg_standby.c:37
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2724
char * username
Definition: oid2name.c:42
int getopt(int nargc, char *const *nargv, const char *ostr)
Definition: getopt.c:72
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
int main(int argc, char **argv)
Definition: oid2name.c:545
PGconn * PQconnectdbParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:529
bool tablespaces
Definition: oid2name.c:37
char ** array
Definition: oid2name.c:20
static void help(const char *progname)
Definition: oid2name.c:172
void sql_exec_dumpalldbs(PGconn *, struct options *)
Definition: oid2name.c:414
eary * oids
Definition: oid2name.c:29
PGconn * conn
Definition: streamutil.c:46
bool indexes
Definition: oid2name.c:34
char * c
bool systables
Definition: oid2name.c:33
void simple_prompt(const char *prompt, char *destination, size_t destlen, bool echo)
Definition: sprompt.c:37
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void * pg_realloc(void *ptr, size_t size)
Definition: fe_memutils.c:65
eary * tables
Definition: oid2name.c:28
#define CppAsString2(x)
Definition: c.h:162
void add_one_elt(char *eltname, eary *eary)
Definition: oid2name.c:203
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
const char * progname
Definition: oid2name.c:43
char * dbname
Definition: oid2name.c:39
void PQclear(PGresult *res)
Definition: fe-exec.c:671
#define free(a)
Definition: header.h:65
bool quiet
Definition: oid2name.c:32
static bool have_password
Definition: streamutil.c:44
bool extended
Definition: oid2name.c:36
char * get_comma_elts(eary *eary)
Definition: oid2name.c:229
static Datum values[MAXATTR]
Definition: bootstrap.c:164
int alloc
Definition: oid2name.c:22
int PQconnectionNeedsPassword(const PGconn *conn)
Definition: fe-connect.c:6131
void sql_exec_searchtables(PGconn *, struct options *)
Definition: oid2name.c:463
char * optarg
Definition: getopt.c:53
char * port
Definition: oid2name.c:41
int i
#define RELKIND_INDEX
Definition: pg_class.h:161
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1897
eary * filenodes
Definition: oid2name.c:30
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6044
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
#define _(x)
Definition: elog.c:84
int num
Definition: oid2name.c:21
void sql_exec_dumpalltables(PGconn *, struct options *)
Definition: oid2name.c:431