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