Reputation: 10189
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.
Upvotes: 1
Views: 3229
Reputation: 127096
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.
Upvotes: 1