1

I am using psycopg2 to get a PostgreSQL database size in Python3.

dbname = 'my_pg_database'
q = 'select pg_total_relation_size(%s);'
conn.cursor.execute(q, (dbname, ))
row = conn.cursor.fetchone()
print(str(row[0]))

I have also tried with the same code but switching second line:

q = 'select pg_total_relation_size((%s));'

And changing second and third lines:

dbname = 'my_pg_database'
q = 'select pg_total_relation_size({dbname});'.format(dbname=dbname)
conn.cursor.execute(q)
row = conn.cursor.fetchone()
print(str(row[0]))

I always get the same syntax error, I had a lot this problem before with other queries, but I managed to deal with this using format or the other way, but not in this case. Anyone knows why?

EDIT

The errors I am getting are:

With the first code:

psycopg2.ProgrammingError: relation "my_pg_database" does not exist LINE 1: select pg_total_relation_size('my_pg_database');

By the way, here there is a kind of arrow pointing to the first quote of the second line.

With the third code:

psycopg2.ProgrammingError: column "my_pg_database" does not exist LINE 1: select pg_total_relation_size(my_pg_database);

And here there is a kind of arrow pointing to the m of my_pg_database of the second line.

Note that the first error is talking about relation and the second one about column.

6
  • print is a function in Python 3 - print(things, you, want, to print) not print things you want to print (note the parenthesis) Commented May 22, 2014 at 14:59
  • OK in fact I am not using print (logger instead), but the problem is in the query, sure. But I am going to change that here! Commented May 22, 2014 at 15:01
  • Can you provide the error that you are getting? Commented May 22, 2014 at 15:06
  • I edited the post with the errors. Commented May 22, 2014 at 15:13
  • 2
    You're using the wrong function, you need pg_database_size() to get the size of your database. pg_total_relation_size() is for a single table and it's indexes. Commented May 22, 2014 at 15:17

1 Answer 1

1

You're using the wrong function, you need pg_database_size() to get the size of your database. pg_total_relation_size() is for a single table and it's indexes.

Check the manual for more details.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.