[Zope] How to access NAMES of database fields? (ZSQL)

Doug Hellmann hellmann@GNNcast.net
Wed, 06 Oct 1999 15:57:28 +0000


Martin Dougiamas wrote:
> 
> How can I print all the NAMES of the fields in a record
> that is returned by a ZSQL query method (not the CONTENTS
> of the fields).

I think I worked out what you need, but since I'm still figuring out how
to learn these sorts of things myself, so I'll share my thought
process.  Maybe someone can point out a shortcut of this logic which
would arrive at the same place.

The first thing I needed to know is what is the type of the thing
returned by a call to a ZSQL method?  Given that, I would be able to
decide if there was an interesting method or attribute that I could use
to get the names.  The way I got the type was to make a DTML method
containing:

<dtml-var getrecord>

That returned a page with:

<Shared.DC.ZRDB.Results.Results instance at 9a9310>

This is the default way for Python to provide the representation of an
object.  In this case, the object is an instance of the Results class
from the Shared.DC.ZRDB.Results module.  

The Python modules for Zope are all in the $ZOPE_ROOT/lib/python
directory.  Each part of the name (separated by .) is a directory name,
up to the 2nd to last part which is the basename for the file containing
the class and the last part which is the class name.  Deciphering that
lead me to look at the file
$ZOPE_ROOT/lib/python/Shared/DC/ZRDB/Results.py for the class Results.  

The Results class has a method called "names" which returns a list of
the names of the things returned by running the query (essentially the
column names returned, but depending on the SQL it might be some weird
sort of thing like "MAX(column_name)" or whatever).

Since Results.names returns a list, you can iterate over it with
dtml-in:

<ul>
<dtml-in "getrecord.names()">
<li><dtml-var sequence-item>
</dtml-in>
</ul>

The data_dictionary() method also looks interesting, but I haven't tried
printing its output.

Hope that helps,
Doug