9 #include "access/heapam.h"
10 #include "catalog/catalog.h"
11 #include "catalog/namespace.h"
12 #include "commands/dbcommands.h"
14 #include "utils/builtins.h"
18 psnprintf(size_t len, const char *fmt,...)
26 vsnprintf(buf, len, fmt, ap);
35 * SQL function: database_size(name) returns bigint
38 PG_FUNCTION_INFO_V1(database_size);
40 Datum database_size(PG_FUNCTION_ARGS);
43 database_size(PG_FUNCTION_ARGS)
45 Name dbname = PG_GETARG_NAME(0);
50 struct dirent *direntry;
53 dbid = get_database_oid(NameStr(*dbname));
54 if (!OidIsValid(dbid))
55 elog(ERROR, "database %s does not exist", NameStr(*dbname));
57 dbpath = GetDatabasePath(dbid);
59 dirdesc = opendir(dbpath);
61 elog(ERROR, "could not open directory %s: %s", dbpath, strerror(errno));
70 direntry = readdir(dirdesc);
74 elog(ERROR, "error reading directory: %s", strerror(errno));
79 fullname = psnprintf(strlen(dbpath) + 1 + strlen(direntry->d_name) + 1,
80 "%s/%s", dbpath, direntry->d_name);
81 if (stat(fullname, &statbuf) == -1)
82 elog(ERROR, "could not stat %s: %s", fullname, strerror(errno));
83 totalsize += statbuf.st_size;
89 PG_RETURN_INT64(totalsize);
95 * SQL function: relation_size(text) returns bigint
98 PG_FUNCTION_INFO_V1(relation_size);
100 Datum relation_size(PG_FUNCTION_ARGS);
103 relation_size(PG_FUNCTION_ARGS)
105 text *relname = PG_GETARG_TEXT_P(0);
111 unsigned int segcount;
113 relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname,
115 relation = relation_openrv(relrv, AccessShareLock);
117 relnode = relation->rd_rel->relfilenode;
127 fullname = psnprintf(25, "%u", (unsigned) relnode);
129 fullname = psnprintf(50, "%u.%u", (unsigned) relnode, segcount);
131 if (stat(fullname, &statbuf) == -1)
136 elog(ERROR, "could not stat %s: %m", fullname);
138 totalsize += statbuf.st_size;
143 relation_close(relation, AccessShareLock);
145 PG_RETURN_INT64(totalsize);