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