Find out the schema with psycopg?

Ben Hutchings ben-public-nospam at decadentplace.org.uk
Fri Dec 23 22:38:22 EST 2005


Steve Holden <steve at holdenweb.com> wrote:
> survivalist at gmail.com wrote:
>> I am trying to discover the schema of a PostgreSQL database
>> programatically at runtime.
>> 
>> I'm using psycopg (I assume that's still the best library).  Is there a
>> way to query the schema other than opening a system pipe like "psql -d
>> '\d'", "psql -d '\d tablename'", etc.?
>> 
>> DBIAPI 2.0 shows that the Cursor object has a .description method that
>> describes rows, and there's the Type object.  But neither of these
>> appear to give you table names.
>> 
>> Is there something else I should look at?
>
> Yes, but as with so many of these things you'll have to accept it's a 
> platform-specific (i.e. non-portable) solution, and it requires that you 
> are running PostgreSQL 7.4 or higher. Under those circumstances you can 
> query the metadata through the information schema.
<snip>

It's not *that* non-portable - information_schema is a standard part
of ANSI SQL and is supported by several RDBMSes.

-- 
Ben Hutchings
It is easier to write an incorrect program than to understand a correct one.



More information about the Python-list mailing list