javapostgresqlormlite

Get PostgreSql table size on disk (byte) in ORMlite


I use ORMLite in a Java application, in order to deal with a PostgreSql DataBase. I want to get the space on the disc used by a table of DataBase. It seems that OrmLite doesn't have a specific method to get it, so I tried without success:

final String TABLE_NAME = "a_table_name_of_db";

//1)
String SQL = "SELECT pg_relation_size('" + TABLE_NAME + "');"  ;
int result = OGGETTO_DAO.executeRaw(SQL); 

//2)
String SQL = "SELECT pg_table_size('" + TABLE_NAME + "');"  ;
int result = OGGETTO_DAO.executeRaw(SQL); 

//3 - it was just a try...)
SQL = "SELECT pg_table_size('" + TABLE_NAME + "');"  ;
GenericRawResults<String> ARRAY = OGGETTO_DAO.queryRaw(SQL);
String result= ARRAY.getFirstResult();

With 1) and 2) I get always -1, with 3) I get a cast exception;

I I use the command 'pg_relation_size' or 'pg_table_size' by command line (linux - by psql prompt), it works properly.

What am I wrong? Thank you

UPDATE - WORKING SOLUTION:

Now it works! Solution, as per accepted answer below, is:

final String TABLE_NAME = "a_table_name_of_db";
String SQL = "SELECT pg_table_size('" + TABLE_NAME  + "');"  
final long RESULT = OGGETTO_DAO.queryRawValue(SQL); //in bytes

Solution

  • int result = OGGETTO_DAO.executeRaw(SQL);

    Yeah that's not right. Looking at the javadocs for executeRaw(...) they say that it returns the number of rows affected not the result.

    SQL = "SELECT pg_table_size('" + TABLE_NAME + "');" ; GenericRawResults ARRAY = OGGETTO_DAO.queryRaw(SQL); String result= ARRAY.getFirstResult();

    Looking at the javadocs for queryRaw(...), the problem here is it returns a GenericRawResults<String[]> and not <String>. It returns a collection of raw results, each row being represented by a string array. I'm really surprised that your code even compiles.

    It should be:

    GenericRawResults<String[]> ARRAY = OGGETTO_DAO.queryRaw(SQL);
    String result= ARRAY.getFirstResult()[0];
    

    Probably the best way to do this is to use queryRawValue(...) which performs a raw query and returns a single value.

    // throws an exception if there are no results or if the first one isn't a number
    long size = OGGETTO_DAO.queryRawValue(SQL);