PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
dbsize.c
Go to the documentation of this file.
1 /*
2  * dbsize.c
3  * Database object size functions, and related inquiries
4  *
5  * Copyright (c) 2002-2017, PostgreSQL Global Development Group
6  *
7  * IDENTIFICATION
8  * src/backend/utils/adt/dbsize.c
9  *
10  */
11 
12 #include "postgres.h"
13 
14 #include <sys/stat.h>
15 
16 #include "access/heapam.h"
17 #include "access/htup_details.h"
18 #include "catalog/catalog.h"
19 #include "catalog/namespace.h"
20 #include "catalog/pg_authid.h"
21 #include "catalog/pg_tablespace.h"
22 #include "commands/dbcommands.h"
23 #include "commands/tablespace.h"
24 #include "miscadmin.h"
25 #include "storage/fd.h"
26 #include "utils/acl.h"
27 #include "utils/builtins.h"
28 #include "utils/numeric.h"
29 #include "utils/rel.h"
30 #include "utils/relfilenodemap.h"
31 #include "utils/relmapper.h"
32 #include "utils/syscache.h"
33 
34 /* Divide by two and round towards positive infinity. */
35 #define half_rounded(x) (((x) + ((x) < 0 ? 0 : 1)) / 2)
36 
37 /* Return physical size of directory contents, or 0 if dir doesn't exist */
38 static int64
39 db_dir_size(const char *path)
40 {
41  int64 dirsize = 0;
42  struct dirent *direntry;
43  DIR *dirdesc;
44  char filename[MAXPGPATH * 2];
45 
46  dirdesc = AllocateDir(path);
47 
48  if (!dirdesc)
49  return 0;
50 
51  while ((direntry = ReadDir(dirdesc, path)) != NULL)
52  {
53  struct stat fst;
54 
56 
57  if (strcmp(direntry->d_name, ".") == 0 ||
58  strcmp(direntry->d_name, "..") == 0)
59  continue;
60 
61  snprintf(filename, sizeof(filename), "%s/%s", path, direntry->d_name);
62 
63  if (stat(filename, &fst) < 0)
64  {
65  if (errno == ENOENT)
66  continue;
67  else
68  ereport(ERROR,
70  errmsg("could not stat file \"%s\": %m", filename)));
71  }
72  dirsize += fst.st_size;
73  }
74 
75  FreeDir(dirdesc);
76  return dirsize;
77 }
78 
79 /*
80  * calculate size of database in all tablespaces
81  */
82 static int64
84 {
85  int64 totalsize;
86  DIR *dirdesc;
87  struct dirent *direntry;
88  char dirpath[MAXPGPATH];
89  char pathname[MAXPGPATH + 12 + sizeof(TABLESPACE_VERSION_DIRECTORY)];
90  AclResult aclresult;
91 
92  /*
93  * User must have connect privilege for target database or be a member of
94  * pg_read_all_stats
95  */
96  aclresult = pg_database_aclcheck(dbOid, GetUserId(), ACL_CONNECT);
97  if (aclresult != ACLCHECK_OK &&
99  {
101  get_database_name(dbOid));
102  }
103 
104  /* Shared storage in pg_global is not counted */
105 
106  /* Include pg_default storage */
107  snprintf(pathname, sizeof(pathname), "base/%u", dbOid);
108  totalsize = db_dir_size(pathname);
109 
110  /* Scan the non-default tablespaces */
111  snprintf(dirpath, MAXPGPATH, "pg_tblspc");
112  dirdesc = AllocateDir(dirpath);
113  if (!dirdesc)
114  ereport(ERROR,
116  errmsg("could not open tablespace directory \"%s\": %m",
117  dirpath)));
118 
119  while ((direntry = ReadDir(dirdesc, dirpath)) != NULL)
120  {
122 
123  if (strcmp(direntry->d_name, ".") == 0 ||
124  strcmp(direntry->d_name, "..") == 0)
125  continue;
126 
127  snprintf(pathname, sizeof(pathname), "pg_tblspc/%s/%s/%u",
128  direntry->d_name, TABLESPACE_VERSION_DIRECTORY, dbOid);
129  totalsize += db_dir_size(pathname);
130  }
131 
132  FreeDir(dirdesc);
133 
134  return totalsize;
135 }
136 
137 Datum
139 {
140  Oid dbOid = PG_GETARG_OID(0);
141  int64 size;
142 
143  size = calculate_database_size(dbOid);
144 
145  if (size == 0)
146  PG_RETURN_NULL();
147 
148  PG_RETURN_INT64(size);
149 }
150 
151 Datum
153 {
155  Oid dbOid = get_database_oid(NameStr(*dbName), false);
156  int64 size;
157 
158  size = calculate_database_size(dbOid);
159 
160  if (size == 0)
161  PG_RETURN_NULL();
162 
163  PG_RETURN_INT64(size);
164 }
165 
166 
167 /*
168  * Calculate total size of tablespace. Returns -1 if the tablespace directory
169  * cannot be found.
170  */
171 static int64
173 {
174  char tblspcPath[MAXPGPATH];
175  char pathname[MAXPGPATH * 2];
176  int64 totalsize = 0;
177  DIR *dirdesc;
178  struct dirent *direntry;
179  AclResult aclresult;
180 
181  /*
182  * User must be a member of pg_read_all_stats or have CREATE privilege for
183  * target tablespace, either explicitly granted or implicitly because it
184  * is default for current database.
185  */
186  if (tblspcOid != MyDatabaseTableSpace &&
188  {
189  aclresult = pg_tablespace_aclcheck(tblspcOid, GetUserId(), ACL_CREATE);
190  if (aclresult != ACLCHECK_OK)
192  get_tablespace_name(tblspcOid));
193  }
194 
195  if (tblspcOid == DEFAULTTABLESPACE_OID)
196  snprintf(tblspcPath, MAXPGPATH, "base");
197  else if (tblspcOid == GLOBALTABLESPACE_OID)
198  snprintf(tblspcPath, MAXPGPATH, "global");
199  else
200  snprintf(tblspcPath, MAXPGPATH, "pg_tblspc/%u/%s", tblspcOid,
202 
203  dirdesc = AllocateDir(tblspcPath);
204 
205  if (!dirdesc)
206  return -1;
207 
208  while ((direntry = ReadDir(dirdesc, tblspcPath)) != NULL)
209  {
210  struct stat fst;
211 
213 
214  if (strcmp(direntry->d_name, ".") == 0 ||
215  strcmp(direntry->d_name, "..") == 0)
216  continue;
217 
218  snprintf(pathname, sizeof(pathname), "%s/%s", tblspcPath, direntry->d_name);
219 
220  if (stat(pathname, &fst) < 0)
221  {
222  if (errno == ENOENT)
223  continue;
224  else
225  ereport(ERROR,
227  errmsg("could not stat file \"%s\": %m", pathname)));
228  }
229 
230  if (S_ISDIR(fst.st_mode))
231  totalsize += db_dir_size(pathname);
232 
233  totalsize += fst.st_size;
234  }
235 
236  FreeDir(dirdesc);
237 
238  return totalsize;
239 }
240 
241 Datum
243 {
244  Oid tblspcOid = PG_GETARG_OID(0);
245  int64 size;
246 
247  size = calculate_tablespace_size(tblspcOid);
248 
249  if (size < 0)
250  PG_RETURN_NULL();
251 
252  PG_RETURN_INT64(size);
253 }
254 
255 Datum
257 {
258  Name tblspcName = PG_GETARG_NAME(0);
259  Oid tblspcOid = get_tablespace_oid(NameStr(*tblspcName), false);
260  int64 size;
261 
262  size = calculate_tablespace_size(tblspcOid);
263 
264  if (size < 0)
265  PG_RETURN_NULL();
266 
267  PG_RETURN_INT64(size);
268 }
269 
270 
271 /*
272  * calculate size of (one fork of) a relation
273  *
274  * Note: we can safely apply this to temp tables of other sessions, so there
275  * is no check here or at the call sites for that.
276  */
277 static int64
279 {
280  int64 totalsize = 0;
281  char *relationpath;
282  char pathname[MAXPGPATH];
283  unsigned int segcount = 0;
284 
285  relationpath = relpathbackend(*rfn, backend, forknum);
286 
287  for (segcount = 0;; segcount++)
288  {
289  struct stat fst;
290 
292 
293  if (segcount == 0)
294  snprintf(pathname, MAXPGPATH, "%s",
295  relationpath);
296  else
297  snprintf(pathname, MAXPGPATH, "%s.%u",
298  relationpath, segcount);
299 
300  if (stat(pathname, &fst) < 0)
301  {
302  if (errno == ENOENT)
303  break;
304  else
305  ereport(ERROR,
307  errmsg("could not stat file \"%s\": %m", pathname)));
308  }
309  totalsize += fst.st_size;
310  }
311 
312  return totalsize;
313 }
314 
315 Datum
317 {
318  Oid relOid = PG_GETARG_OID(0);
319  text *forkName = PG_GETARG_TEXT_PP(1);
320  Relation rel;
321  int64 size;
322 
323  rel = try_relation_open(relOid, AccessShareLock);
324 
325  /*
326  * Before 9.2, we used to throw an error if the relation didn't exist, but
327  * that makes queries like "SELECT pg_relation_size(oid) FROM pg_class"
328  * less robust, because while we scan pg_class with an MVCC snapshot,
329  * someone else might drop the table. It's better to return NULL for
330  * already-dropped tables than throw an error and abort the whole query.
331  */
332  if (rel == NULL)
333  PG_RETURN_NULL();
334 
335  size = calculate_relation_size(&(rel->rd_node), rel->rd_backend,
337 
339 
340  PG_RETURN_INT64(size);
341 }
342 
343 /*
344  * Calculate total on-disk size of a TOAST relation, including its indexes.
345  * Must not be applied to non-TOAST relations.
346  */
347 static int64
349 {
350  int64 size = 0;
351  Relation toastRel;
352  ForkNumber forkNum;
353  ListCell *lc;
354  List *indexlist;
355 
356  toastRel = relation_open(toastrelid, AccessShareLock);
357 
358  /* toast heap size, including FSM and VM size */
359  for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
360  size += calculate_relation_size(&(toastRel->rd_node),
361  toastRel->rd_backend, forkNum);
362 
363  /* toast index size, including FSM and VM size */
364  indexlist = RelationGetIndexList(toastRel);
365 
366  /* Size is calculated using all the indexes available */
367  foreach(lc, indexlist)
368  {
369  Relation toastIdxRel;
370 
371  toastIdxRel = relation_open(lfirst_oid(lc),
373  for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
374  size += calculate_relation_size(&(toastIdxRel->rd_node),
375  toastIdxRel->rd_backend, forkNum);
376 
377  relation_close(toastIdxRel, AccessShareLock);
378  }
379  list_free(indexlist);
380  relation_close(toastRel, AccessShareLock);
381 
382  return size;
383 }
384 
385 /*
386  * Calculate total on-disk size of a given table,
387  * including FSM and VM, plus TOAST table if any.
388  * Indexes other than the TOAST table's index are not included.
389  *
390  * Note that this also behaves sanely if applied to an index or toast table;
391  * those won't have attached toast tables, but they can have multiple forks.
392  */
393 static int64
395 {
396  int64 size = 0;
397  ForkNumber forkNum;
398 
399  /*
400  * heap size, including FSM and VM
401  */
402  for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
403  size += calculate_relation_size(&(rel->rd_node), rel->rd_backend,
404  forkNum);
405 
406  /*
407  * Size of toast relation
408  */
409  if (OidIsValid(rel->rd_rel->reltoastrelid))
410  size += calculate_toast_table_size(rel->rd_rel->reltoastrelid);
411 
412  return size;
413 }
414 
415 /*
416  * Calculate total on-disk size of all indexes attached to the given table.
417  *
418  * Can be applied safely to an index, but you'll just get zero.
419  */
420 static int64
422 {
423  int64 size = 0;
424 
425  /*
426  * Aggregate all indexes on the given relation
427  */
428  if (rel->rd_rel->relhasindex)
429  {
430  List *index_oids = RelationGetIndexList(rel);
431  ListCell *cell;
432 
433  foreach(cell, index_oids)
434  {
435  Oid idxOid = lfirst_oid(cell);
436  Relation idxRel;
437  ForkNumber forkNum;
438 
439  idxRel = relation_open(idxOid, AccessShareLock);
440 
441  for (forkNum = 0; forkNum <= MAX_FORKNUM; forkNum++)
442  size += calculate_relation_size(&(idxRel->rd_node),
443  idxRel->rd_backend,
444  forkNum);
445 
447  }
448 
449  list_free(index_oids);
450  }
451 
452  return size;
453 }
454 
455 Datum
457 {
458  Oid relOid = PG_GETARG_OID(0);
459  Relation rel;
460  int64 size;
461 
462  rel = try_relation_open(relOid, AccessShareLock);
463 
464  if (rel == NULL)
465  PG_RETURN_NULL();
466 
467  size = calculate_table_size(rel);
468 
470 
471  PG_RETURN_INT64(size);
472 }
473 
474 Datum
476 {
477  Oid relOid = PG_GETARG_OID(0);
478  Relation rel;
479  int64 size;
480 
481  rel = try_relation_open(relOid, AccessShareLock);
482 
483  if (rel == NULL)
484  PG_RETURN_NULL();
485 
486  size = calculate_indexes_size(rel);
487 
489 
490  PG_RETURN_INT64(size);
491 }
492 
493 /*
494  * Compute the on-disk size of all files for the relation,
495  * including heap data, index data, toast data, FSM, VM.
496  */
497 static int64
499 {
500  int64 size;
501 
502  /*
503  * Aggregate the table size, this includes size of the heap, toast and
504  * toast index with free space and visibility map
505  */
506  size = calculate_table_size(rel);
507 
508  /*
509  * Add size of all attached indexes as well
510  */
511  size += calculate_indexes_size(rel);
512 
513  return size;
514 }
515 
516 Datum
518 {
519  Oid relOid = PG_GETARG_OID(0);
520  Relation rel;
521  int64 size;
522 
523  rel = try_relation_open(relOid, AccessShareLock);
524 
525  if (rel == NULL)
526  PG_RETURN_NULL();
527 
528  size = calculate_total_relation_size(rel);
529 
531 
532  PG_RETURN_INT64(size);
533 }
534 
535 /*
536  * formatting with size units
537  */
538 Datum
540 {
541  int64 size = PG_GETARG_INT64(0);
542  char buf[64];
543  int64 limit = 10 * 1024;
544  int64 limit2 = limit * 2 - 1;
545 
546  if (Abs(size) < limit)
547  snprintf(buf, sizeof(buf), INT64_FORMAT " bytes", size);
548  else
549  {
550  size >>= 9; /* keep one extra bit for rounding */
551  if (Abs(size) < limit2)
552  snprintf(buf, sizeof(buf), INT64_FORMAT " kB",
553  half_rounded(size));
554  else
555  {
556  size >>= 10;
557  if (Abs(size) < limit2)
558  snprintf(buf, sizeof(buf), INT64_FORMAT " MB",
559  half_rounded(size));
560  else
561  {
562  size >>= 10;
563  if (Abs(size) < limit2)
564  snprintf(buf, sizeof(buf), INT64_FORMAT " GB",
565  half_rounded(size));
566  else
567  {
568  size >>= 10;
569  snprintf(buf, sizeof(buf), INT64_FORMAT " TB",
570  half_rounded(size));
571  }
572  }
573  }
574  }
575 
577 }
578 
579 static char *
581 {
582  Datum d = NumericGetDatum(n);
583 
585 }
586 
587 static Numeric
589 {
590  Datum d = Int64GetDatum(v);
591 
593 }
594 
595 static bool
597 {
598  Datum da = NumericGetDatum(a);
599  Datum db = NumericGetDatum(b);
600 
602 }
603 
604 static Numeric
606 {
607  Datum d = NumericGetDatum(n);
608  Datum result;
609 
610  result = DirectFunctionCall1(numeric_abs, d);
611  return DatumGetNumeric(result);
612 }
613 
614 static Numeric
616 {
617  Datum d = NumericGetDatum(n);
618  Datum zero;
619  Datum one;
620  Datum two;
621  Datum result;
622 
626 
628  d = DirectFunctionCall2(numeric_add, d, one);
629  else
630  d = DirectFunctionCall2(numeric_sub, d, one);
631 
632  result = DirectFunctionCall2(numeric_div_trunc, d, two);
633  return DatumGetNumeric(result);
634 }
635 
636 static Numeric
637 numeric_shift_right(Numeric n, unsigned count)
638 {
639  Datum d = NumericGetDatum(n);
640  Datum divisor_int64;
641  Datum divisor_numeric;
642  Datum result;
643 
644  divisor_int64 = Int64GetDatum((int64) (1 << count));
645  divisor_numeric = DirectFunctionCall1(int8_numeric, divisor_int64);
646  result = DirectFunctionCall2(numeric_div_trunc, d, divisor_numeric);
647  return DatumGetNumeric(result);
648 }
649 
650 Datum
652 {
653  Numeric size = PG_GETARG_NUMERIC(0);
654  Numeric limit,
655  limit2;
656  char *result;
657 
658  limit = int64_to_numeric(10 * 1024);
659  limit2 = int64_to_numeric(10 * 1024 * 2 - 1);
660 
661  if (numeric_is_less(numeric_absolute(size), limit))
662  {
663  result = psprintf("%s bytes", numeric_to_cstring(size));
664  }
665  else
666  {
667  /* keep one extra bit for rounding */
668  /* size >>= 9 */
669  size = numeric_shift_right(size, 9);
670 
671  if (numeric_is_less(numeric_absolute(size), limit2))
672  {
673  size = numeric_half_rounded(size);
674  result = psprintf("%s kB", numeric_to_cstring(size));
675  }
676  else
677  {
678  /* size >>= 10 */
679  size = numeric_shift_right(size, 10);
680  if (numeric_is_less(numeric_absolute(size), limit2))
681  {
682  size = numeric_half_rounded(size);
683  result = psprintf("%s MB", numeric_to_cstring(size));
684  }
685  else
686  {
687  /* size >>= 10 */
688  size = numeric_shift_right(size, 10);
689 
690  if (numeric_is_less(numeric_absolute(size), limit2))
691  {
692  size = numeric_half_rounded(size);
693  result = psprintf("%s GB", numeric_to_cstring(size));
694  }
695  else
696  {
697  /* size >>= 10 */
698  size = numeric_shift_right(size, 10);
699  size = numeric_half_rounded(size);
700  result = psprintf("%s TB", numeric_to_cstring(size));
701  }
702  }
703  }
704  }
705 
707 }
708 
709 /*
710  * Convert a human-readable size to a size in bytes
711  */
712 Datum
714 {
715  text *arg = PG_GETARG_TEXT_PP(0);
716  char *str,
717  *strptr,
718  *endptr;
719  char saved_char;
720  Numeric num;
721  int64 result;
722  bool have_digits = false;
723 
724  str = text_to_cstring(arg);
725 
726  /* Skip leading whitespace */
727  strptr = str;
728  while (isspace((unsigned char) *strptr))
729  strptr++;
730 
731  /* Check that we have a valid number and determine where it ends */
732  endptr = strptr;
733 
734  /* Part (1): sign */
735  if (*endptr == '-' || *endptr == '+')
736  endptr++;
737 
738  /* Part (2): main digit string */
739  if (isdigit((unsigned char) *endptr))
740  {
741  have_digits = true;
742  do
743  endptr++;
744  while (isdigit((unsigned char) *endptr));
745  }
746 
747  /* Part (3): optional decimal point and fractional digits */
748  if (*endptr == '.')
749  {
750  endptr++;
751  if (isdigit((unsigned char) *endptr))
752  {
753  have_digits = true;
754  do
755  endptr++;
756  while (isdigit((unsigned char) *endptr));
757  }
758  }
759 
760  /* Complain if we don't have a valid number at this point */
761  if (!have_digits)
762  ereport(ERROR,
763  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
764  errmsg("invalid size: \"%s\"", str)));
765 
766  /* Part (4): optional exponent */
767  if (*endptr == 'e' || *endptr == 'E')
768  {
769  long exponent;
770  char *cp;
771 
772  /*
773  * Note we might one day support EB units, so if what follows 'E'
774  * isn't a number, just treat it all as a unit to be parsed.
775  */
776  exponent = strtol(endptr + 1, &cp, 10);
777  (void) exponent; /* Silence -Wunused-result warnings */
778  if (cp > endptr + 1)
779  endptr = cp;
780  }
781 
782  /*
783  * Parse the number, saving the next character, which may be the first
784  * character of the unit string.
785  */
786  saved_char = *endptr;
787  *endptr = '\0';
788 
790  CStringGetDatum(strptr),
792  Int32GetDatum(-1)));
793 
794  *endptr = saved_char;
795 
796  /* Skip whitespace between number and unit */
797  strptr = endptr;
798  while (isspace((unsigned char) *strptr))
799  strptr++;
800 
801  /* Handle possible unit */
802  if (*strptr != '\0')
803  {
804  int64 multiplier = 0;
805 
806  /* Trim any trailing whitespace */
807  endptr = str + VARSIZE_ANY_EXHDR(arg) - 1;
808 
809  while (isspace((unsigned char) *endptr))
810  endptr--;
811 
812  endptr++;
813  *endptr = '\0';
814 
815  /* Parse the unit case-insensitively */
816  if (pg_strcasecmp(strptr, "bytes") == 0)
817  multiplier = (int64) 1;
818  else if (pg_strcasecmp(strptr, "kb") == 0)
819  multiplier = (int64) 1024;
820  else if (pg_strcasecmp(strptr, "mb") == 0)
821  multiplier = ((int64) 1024) * 1024;
822 
823  else if (pg_strcasecmp(strptr, "gb") == 0)
824  multiplier = ((int64) 1024) * 1024 * 1024;
825 
826  else if (pg_strcasecmp(strptr, "tb") == 0)
827  multiplier = ((int64) 1024) * 1024 * 1024 * 1024;
828 
829  else
830  ereport(ERROR,
831  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
832  errmsg("invalid size: \"%s\"", text_to_cstring(arg)),
833  errdetail("Invalid size unit: \"%s\".", strptr),
834  errhint("Valid units are \"bytes\", \"kB\", \"MB\", \"GB\", and \"TB\".")));
835 
836  if (multiplier > 1)
837  {
838  Numeric mul_num;
839 
841  Int64GetDatum(multiplier)));
842 
844  NumericGetDatum(mul_num),
845  NumericGetDatum(num)));
846  }
847  }
848 
850  NumericGetDatum(num)));
851 
852  PG_RETURN_INT64(result);
853 }
854 
855 /*
856  * Get the filenode of a relation
857  *
858  * This is expected to be used in queries like
859  * SELECT pg_relation_filenode(oid) FROM pg_class;
860  * That leads to a couple of choices. We work from the pg_class row alone
861  * rather than actually opening each relation, for efficiency. We don't
862  * fail if we can't find the relation --- some rows might be visible in
863  * the query's MVCC snapshot even though the relations have been dropped.
864  * (Note: we could avoid using the catcache, but there's little point
865  * because the relation mapper also works "in the now".) We also don't
866  * fail if the relation doesn't have storage. In all these cases it
867  * seems better to quietly return NULL.
868  */
869 Datum
871 {
872  Oid relid = PG_GETARG_OID(0);
873  Oid result;
874  HeapTuple tuple;
875  Form_pg_class relform;
876 
877  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
878  if (!HeapTupleIsValid(tuple))
879  PG_RETURN_NULL();
880  relform = (Form_pg_class) GETSTRUCT(tuple);
881 
882  switch (relform->relkind)
883  {
884  case RELKIND_RELATION:
885  case RELKIND_MATVIEW:
886  case RELKIND_INDEX:
887  case RELKIND_SEQUENCE:
888  case RELKIND_TOASTVALUE:
889  /* okay, these have storage */
890  if (relform->relfilenode)
891  result = relform->relfilenode;
892  else /* Consult the relation mapper */
893  result = RelationMapOidToFilenode(relid,
894  relform->relisshared);
895  break;
896 
897  default:
898  /* no storage, return NULL */
899  result = InvalidOid;
900  break;
901  }
902 
903  ReleaseSysCache(tuple);
904 
905  if (!OidIsValid(result))
906  PG_RETURN_NULL();
907 
908  PG_RETURN_OID(result);
909 }
910 
911 /*
912  * Get the relation via (reltablespace, relfilenode)
913  *
914  * This is expected to be used when somebody wants to match an individual file
915  * on the filesystem back to its table. That's not trivially possible via
916  * pg_class, because that doesn't contain the relfilenodes of shared and nailed
917  * tables.
918  *
919  * We don't fail but return NULL if we cannot find a mapping.
920  *
921  * InvalidOid can be passed instead of the current database's default
922  * tablespace.
923  */
924 Datum
926 {
927  Oid reltablespace = PG_GETARG_OID(0);
928  Oid relfilenode = PG_GETARG_OID(1);
929  Oid heaprel = InvalidOid;
930 
931  heaprel = RelidByRelfilenode(reltablespace, relfilenode);
932 
933  if (!OidIsValid(heaprel))
934  PG_RETURN_NULL();
935  else
936  PG_RETURN_OID(heaprel);
937 }
938 
939 /*
940  * Get the pathname (relative to $PGDATA) of a relation
941  *
942  * See comments for pg_relation_filenode.
943  */
944 Datum
946 {
947  Oid relid = PG_GETARG_OID(0);
948  HeapTuple tuple;
949  Form_pg_class relform;
950  RelFileNode rnode;
951  BackendId backend;
952  char *path;
953 
954  tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
955  if (!HeapTupleIsValid(tuple))
956  PG_RETURN_NULL();
957  relform = (Form_pg_class) GETSTRUCT(tuple);
958 
959  switch (relform->relkind)
960  {
961  case RELKIND_RELATION:
962  case RELKIND_MATVIEW:
963  case RELKIND_INDEX:
964  case RELKIND_SEQUENCE:
965  case RELKIND_TOASTVALUE:
966  /* okay, these have storage */
967 
968  /* This logic should match RelationInitPhysicalAddr */
969  if (relform->reltablespace)
970  rnode.spcNode = relform->reltablespace;
971  else
973  if (rnode.spcNode == GLOBALTABLESPACE_OID)
974  rnode.dbNode = InvalidOid;
975  else
976  rnode.dbNode = MyDatabaseId;
977  if (relform->relfilenode)
978  rnode.relNode = relform->relfilenode;
979  else /* Consult the relation mapper */
980  rnode.relNode = RelationMapOidToFilenode(relid,
981  relform->relisshared);
982  break;
983 
984  default:
985  /* no storage, return NULL */
986  rnode.relNode = InvalidOid;
987  /* some compilers generate warnings without these next two lines */
988  rnode.dbNode = InvalidOid;
989  rnode.spcNode = InvalidOid;
990  break;
991  }
992 
993  if (!OidIsValid(rnode.relNode))
994  {
995  ReleaseSysCache(tuple);
996  PG_RETURN_NULL();
997  }
998 
999  /* Determine owning backend. */
1000  switch (relform->relpersistence)
1001  {
1004  backend = InvalidBackendId;
1005  break;
1006  case RELPERSISTENCE_TEMP:
1007  if (isTempOrTempToastNamespace(relform->relnamespace))
1008  backend = BackendIdForTempRelations();
1009  else
1010  {
1011  /* Do it the hard way. */
1012  backend = GetTempNamespaceBackendId(relform->relnamespace);
1013  Assert(backend != InvalidBackendId);
1014  }
1015  break;
1016  default:
1017  elog(ERROR, "invalid relpersistence: %c", relform->relpersistence);
1018  backend = InvalidBackendId; /* placate compiler */
1019  break;
1020  }
1021 
1022  ReleaseSysCache(tuple);
1023 
1024  path = relpathbackend(rnode, backend, MAIN_FORKNUM);
1025 
1027 }
Datum pg_filenode_relation(PG_FUNCTION_ARGS)
Definition: dbsize.c:925
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
Definition: tablespace.c:1380
AclResult pg_tablespace_aclcheck(Oid spc_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4496
int errhint(const char *fmt,...)
Definition: elog.c:987
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
static int64 calculate_total_relation_size(Relation rel)
Definition: dbsize.c:498
#define RELPERSISTENCE_UNLOGGED
Definition: pg_class.h:171
Datum pg_relation_filepath(PG_FUNCTION_ARGS)
Definition: dbsize.c:945
static int64 calculate_relation_size(RelFileNode *rfn, BackendId backend, ForkNumber forknum)
Definition: dbsize.c:278
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1153
Oid GetUserId(void)
Definition: miscinit.c:284
#define PG_RETURN_INT64(x)
Definition: fmgr.h:327
bool isTempOrTempToastNamespace(Oid namespaceId)
Definition: namespace.c:3142
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
#define NumericGetDatum(X)
Definition: numeric.h:51
Oid RelidByRelfilenode(Oid reltablespace, Oid relfilenode)
Datum numeric_out(PG_FUNCTION_ARGS)
Definition: numeric.c:641
#define RELKIND_MATVIEW
Definition: pg_class.h:165
#define AccessShareLock
Definition: lockdefs.h:36
#define GLOBALTABLESPACE_OID
Definition: pg_tablespace.h:64
Datum numeric_int8(PG_FUNCTION_ARGS)
Definition: numeric.c:2987
int errcode(int sqlerrcode)
Definition: elog.c:575
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: heapam.c:1266
return result
Definition: formatting.c:1633
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
int GetTempNamespaceBackendId(Oid namespaceId)
Definition: namespace.c:3195
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:584
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
static Numeric numeric_shift_right(Numeric n, unsigned count)
Definition: dbsize.c:637
Definition: dirent.h:9
Datum int8_numeric(PG_FUNCTION_ARGS)
Definition: numeric.c:2968
#define OidIsValid(objectId)
Definition: c.h:538
Datum numeric_div_trunc(PG_FUNCTION_ARGS)
Definition: numeric.c:2414
Datum pg_total_relation_size(PG_FUNCTION_ARGS)
Definition: dbsize.c:517
ForkNumber forkname_to_number(const char *forkName)
Definition: relpath.c:48
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:156
Oid MyDatabaseTableSpace
Definition: globals.c:79
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:273
#define Abs(x)
Definition: c.h:813
#define RELPERSISTENCE_PERMANENT
Definition: pg_class.h:170
Datum pg_relation_filenode(PG_FUNCTION_ARGS)
Definition: dbsize.c:870
static char * numeric_to_cstring(Numeric n)
Definition: dbsize.c:580
static Numeric numeric_absolute(Numeric n)
Definition: dbsize.c:605
Definition: dirent.c:25
Datum numeric_abs(PG_FUNCTION_ARGS)
Definition: numeric.c:1079
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define ACL_CREATE
Definition: parsenodes.h:82
#define DatumGetCString(X)
Definition: postgres.h:572
#define MAXPGPATH
#define DatumGetInt64(X)
Definition: postgres.h:613
#define half_rounded(x)
Definition: dbsize.c:35
char * get_database_name(Oid dbid)
Definition: dbcommands.c:2056
Definition: c.h:493
#define BackendIdForTempRelations()
Definition: backendid.h:34
static Numeric int64_to_numeric(int64 v)
Definition: dbsize.c:588
static char * buf
Definition: pg_test_fsync.c:66
#define PG_GETARG_OID(n)
Definition: fmgr.h:240
void aclcheck_error(AclResult aclerr, AclObjectKind objectkind, const char *objectname)
Definition: aclchk.c:3399
static Numeric numeric_half_rounded(Numeric n)
Definition: dbsize.c:615
#define DEFAULTTABLESPACE_OID
Definition: pg_tablespace.h:63
int errdetail(const char *fmt,...)
Definition: elog.c:873
int errcode_for_file_access(void)
Definition: elog.c:598
#define CStringGetDatum(X)
Definition: postgres.h:584
#define DatumGetBool(X)
Definition: postgres.h:399
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2335
Datum numeric_in(PG_FUNCTION_ARGS)
Definition: numeric.c:559
static uint64 totalsize
static bool numeric_is_less(Numeric a, Numeric b)
Definition: dbsize.c:596
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1791
Datum pg_table_size(PG_FUNCTION_ARGS)
Definition: dbsize.c:456
Datum pg_size_bytes(PG_FUNCTION_ARGS)
Definition: dbsize.c:713
#define ereport(elevel, rest)
Definition: elog.h:122
static int64 calculate_table_size(Relation rel)
Definition: dbsize.c:394
#define ACL_CONNECT
Definition: parsenodes.h:84
ForkNumber
Definition: relpath.h:24
#define DirectFunctionCall3(func, arg1, arg2, arg3)
Definition: fmgr.h:588
Datum numeric_mul(PG_FUNCTION_ARGS)
Definition: numeric.c:2324
Datum pg_database_size_name(PG_FUNCTION_ARGS)
Definition: dbsize.c:152
#define InvalidBackendId
Definition: backendid.h:23
#define RELKIND_TOASTVALUE
Definition: pg_class.h:163
AclResult
Definition: acl.h:170
Oid RelationMapOidToFilenode(Oid relationId, bool shared)
Definition: relmapper.c:146
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Datum numeric_sub(PG_FUNCTION_ARGS)
Definition: numeric.c:2286
int BackendId
Definition: backendid.h:21
Oid MyDatabaseId
Definition: globals.c:77
#define DEFAULT_ROLE_READ_ALL_STATS
Definition: pg_authid.h:108
Datum numeric_lt(PG_FUNCTION_ARGS)
Definition: numeric.c:2096
#define InvalidOid
Definition: postgres_ext.h:36
Oid get_database_oid(const char *dbname, bool missing_ok)
Definition: dbcommands.c:2009
Datum pg_size_pretty_numeric(PG_FUNCTION_ARGS)
Definition: dbsize.c:651
bool is_member_of_role(Oid member, Oid role)
Definition: acl.c:4837
#define PG_RETURN_TEXT_P(x)
Definition: fmgr.h:330
static int64 calculate_toast_table_size(Oid toastrelid)
Definition: dbsize.c:348
static int64 calculate_database_size(Oid dbOid)
Definition: dbsize.c:83
RelFileNode rd_node
Definition: rel.h:85
text * cstring_to_text(const char *s)
Definition: varlena.c:149
#define PG_GETARG_NUMERIC(n)
Definition: numeric.h:52
#define DatumGetNumeric(X)
Definition: numeric.h:49
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
AclResult pg_database_aclcheck(Oid db_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:4434
#define NULL
Definition: c.h:229
BackendId rd_backend
Definition: rel.h:89
#define Assert(condition)
Definition: c.h:676
Datum pg_tablespace_size_name(PG_FUNCTION_ARGS)
Definition: dbsize.c:256
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2401
Datum pg_size_pretty(PG_FUNCTION_ARGS)
Definition: dbsize.c:539
Datum pg_indexes_size(PG_FUNCTION_ARGS)
Definition: dbsize.c:475
#define MAX_FORKNUM
Definition: relpath.h:39
#define TABLESPACE_VERSION_DIRECTORY
Definition: catalog.h:26
List * RelationGetIndexList(Relation relation)
Definition: relcache.c:4357
#define INT64_FORMAT
Definition: c.h:315
FormData_pg_class * Form_pg_class
Definition: pg_class.h:95
char * text_to_cstring(const text *t)
Definition: varlena.c:182
Datum pg_tablespace_size_oid(PG_FUNCTION_ARGS)
Definition: dbsize.c:242
#define Int32GetDatum(X)
Definition: postgres.h:485
static char * filename
Definition: pg_dumpall.c:90
Datum pg_database_size_oid(PG_FUNCTION_ARGS)
Definition: dbsize.c:138
#define VARSIZE_ANY_EXHDR(PTR)
Definition: postgres.h:340
char * dbName
Definition: pgbench.c:183
int errmsg(const char *fmt,...)
Definition: elog.c:797
static int64 calculate_tablespace_size(Oid tblspcOid)
Definition: dbsize.c:172
char * get_tablespace_name(Oid spc_oid)
Definition: tablespace.c:1426
void list_free(List *list)
Definition: list.c:1133
#define NameStr(name)
Definition: c.h:499
#define RELKIND_INDEX
Definition: pg_class.h:161
void * arg
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1120
Definition: c.h:439
#define PG_FUNCTION_ARGS
Definition: fmgr.h:158
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
char d_name[MAX_PATH]
Definition: dirent.h:14
#define elog
Definition: elog.h:219
#define RELPERSISTENCE_TEMP
Definition: pg_class.h:172
Datum numeric_ge(PG_FUNCTION_ARGS)
Definition: numeric.c:2081
#define RELKIND_RELATION
Definition: pg_class.h:160
#define PG_GETARG_INT64(n)
Definition: fmgr.h:247
#define relpathbackend(rnode, backend, forknum)
Definition: relpath.h:62
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
Definition: pg_list.h:45
#define PG_RETURN_OID(x)
Definition: fmgr.h:320
Datum pg_relation_size(PG_FUNCTION_ARGS)
Definition: dbsize.c:316
Datum numeric_add(PG_FUNCTION_ARGS)
Definition: numeric.c:2248
#define DirectFunctionCall2(func, arg1, arg2)
Definition: fmgr.h:586
#define PG_RETURN_NULL()
Definition: fmgr.h:305
int FreeDir(DIR *dir)
Definition: fd.c:2444
static int64 db_dir_size(const char *path)
Definition: dbsize.c:39
#define PG_GETARG_NAME(n)
Definition: fmgr.h:243
static int64 calculate_indexes_size(Relation rel)
Definition: dbsize.c:421
#define lfirst_oid(lc)
Definition: pg_list.h:108