11#include "postgres.h"
2- #include "fmgr.h"
3-
4- #include "access/heapam.h"
5- #include "catalog/catalog.h"
6- #include "catalog/catname.h"
7- #include "catalog/pg_database.h"
8- #include "utils/fmgroids.h"
92
10- #include <stdlib.h>
113#include <sys/types.h>
124#include <dirent.h>
135#include <sys/stat.h>
146#include <unistd.h>
157#include <errno.h>
168
9+ #include "access/heapam.h"
10+ #include "catalog/catalog.h"
11+ #include "catalog/catname.h"
12+ #include "catalog/namespace.h"
13+ #include "catalog/pg_database.h"
14+ #include "fmgr.h"
15+ #include "utils/builtins.h"
16+ #include "utils/fmgroids.h"
17+
1718
1819static char *
1920psnprintf (size_t len ,const char * fmt ,...)
@@ -38,6 +39,8 @@ psnprintf(size_t len, const char *fmt,...)
3839
3940PG_FUNCTION_INFO_V1 (database_size );
4041
42+ Datum database_size (PG_FUNCTION_ARGS );
43+
4144Datum
4245database_size (PG_FUNCTION_ARGS )
4346{
@@ -107,39 +110,29 @@ database_size(PG_FUNCTION_ARGS)
107110
108111
109112/*
110- * SQL function: relation_size(name ) returns bigint
113+ * SQL function: relation_size(text ) returns bigint
111114 */
112115
113116PG_FUNCTION_INFO_V1 (relation_size );
114117
118+ Datum relation_size (PG_FUNCTION_ARGS );
119+
115120Datum
116121relation_size (PG_FUNCTION_ARGS )
117122{
118- Name relname = PG_GETARG_NAME (0 );
123+ text * relname = PG_GETARG_TEXT_P (0 );
119124
120- HeapTuple tuple ;
125+ RangeVar * relrv ;
121126Relation relation ;
122- ScanKeyData scanKey ;
123- HeapScanDesc scan ;
124127Oid relnode ;
125128int64 totalsize ;
126129unsignedint segcount ;
127130
128- relation = heap_openr (RelationRelationName ,AccessShareLock );
129- ScanKeyEntryInitialize (& scanKey ,0 ,Anum_pg_class_relname ,
130- F_NAMEEQ ,NameGetDatum (relname ));
131- scan = heap_beginscan (relation ,0 ,SnapshotNow ,1 ,& scanKey );
132- tuple = heap_getnext (scan ,0 );
131+ relrv = makeRangeVarFromNameList (textToQualifiedNameList (relname ,
132+ "relation_size" ));
133+ relation = relation_openrv (relrv ,AccessShareLock );
133134
134- if (!HeapTupleIsValid (tuple ))
135- elog (ERROR ,"relation %s does not exist" ,NameStr (* relname ));
136-
137- relnode = ((Form_pg_class )GETSTRUCT (tuple ))-> relfilenode ;
138- if (relnode == InvalidOid )
139- elog (ERROR ,"invalid relation node id" );
140-
141- heap_endscan (scan );
142- heap_close (relation ,NoLock );
135+ relnode = relation -> rd_rel -> relfilenode ;
143136
144137totalsize = 0 ;
145138segcount = 0 ;
@@ -158,12 +151,14 @@ relation_size(PG_FUNCTION_ARGS)
158151if (errno == ENOENT )
159152break ;
160153else
161- elog (ERROR ,"could not stat %s: %s " ,fullname , strerror ( errno ) );
154+ elog (ERROR ,"could not stat %s: %m " ,fullname );
162155}
163156totalsize += statbuf .st_size ;
164157pfree (fullname );
165158segcount ++ ;
166159}
167160
161+ relation_close (relation ,AccessShareLock );
162+
168163PG_RETURN_INT64 (totalsize );
169164}