Changeset 788 for trunk/pgdb.py


Ignore:
Timestamp:
Jan 26, 2016, 4:13:55 PM (3 years ago)
Author:
cito
Message:

Add method columns() to type cache

The method returns the columns of composite types.
This makes the type cache even more useful.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/pgdb.py

    r787 r788  
    160160    ['oid', 'name', 'len', 'type', 'category', 'delim', 'relid'])
    161161
     162ColumnInfo = namedtuple('ColumnInfo', ['name', 'type'])
     163
    162164
    163165class TypeCache(dict):
     
    175177
    176178    def __missing__(self, key):
    177         q = ("SELECT oid, typname,"
     179        """Get the type info from the database if it is not cached."""
     180        if isinstance(key, int):
     181            oid = key
     182        else:
     183            if not '.' in key and not '"' in key:
     184                key = '"%s"' % key
     185            oid = "'%s'::regtype" % self._escape_string(key)
     186        self._src.execute("SELECT oid, typname,"
    178187             " typlen, typtype, typcategory, typdelim, typrelid"
    179             " FROM pg_type WHERE ")
    180         if isinstance(key, int):
    181             q += "oid = %d" % key
    182         else:
    183             q += "typname = '%s'" % self._escape_string(key)
    184         self._src.execute(q)
     188            " FROM pg_type WHERE oid=%s" % oid)
    185189        res = self._src.fetch(1)
    186190        if not res:
     
    193197        self[res.oid] = self[res.name] = res
    194198        return res
     199
     200    def columns(self, key):
     201        """Get the names and types of the columns of composite types."""
     202        typ = self[key]
     203        if typ.type != 'c' or not typ.relid:
     204            return []  # this type is not composite
     205        self._src.execute("SELECT attname, atttypid"
     206            " FROM pg_attribute WHERE attrelid=%s AND attnum>0"
     207            " AND NOT attisdropped ORDER BY attnum" % typ.relid)
     208        return [ColumnInfo(name, int(oid))
     209            for name, oid in self._src.fetch(-1)]
    195210
    196211    @staticmethod
Note: See TracChangeset for help on using the changeset viewer.