Changeset 679 for trunk


Ignore:
Timestamp:
Dec 30, 2015, 4:31:47 PM (4 years ago)
Author:
cito
Message:

Use simpler and more standard type names in pgdb

We already renamed the types provided by the classic module to be more simple
and intuitive. We now do the same for the types provided by the DB-API 2 module.

Location:
trunk
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • trunk/docs/changelog.rst

    r674 r679  
    77- The supported versions are Python 2.6, 2.7, 3.3, 3.4 and 3.5.
    88- The supported PostgreSQL versions are 9.0, 9.1, 9.2, 9.3 and 9.4.
    9 
     9- The names of the various types supported by the classic and DB-API 2
     10  modules have been renamed to become simpler, more intuitive and in
     11  line with the names used in the DB-API 2 documentation.
     12  Since the API provides objects of these types only by the use of
     13  constructor functions, this should not cause any incompatibilities.
    1014
    1115Version 4.2
     
    6468- New method use_regtypes() that can be called to let getattnames()
    6569  return regular type names instead of the simplified classic types (#44).
    66 
    6770
    6871Version 4.0 (2009-01-01)
     
    113116  and returns whether the row existed or not.
    114117
    115 
    116118Version 3.8.1 (2006-06-05)
    117119--------------------------
  • trunk/docs/pg.rst

    r676 r679  
    1010Introduction
    1111============
     12
    1213You may either choose to use the "classic" PyGreSQL interface
    1314provided by the :mod:`pg` module or else the
  • trunk/docs/pgdb.rst

    r677 r679  
    1010Introduction
    1111============
     12
    1213You may either choose to use the "classic" PyGreSQL interface
    1314provided by the :mod:`pg` module or else the
     
    4849    :param database: the name of the database
    4950    :returns: a connection object
    50     :rtype: :class:`pgdbCnx`
     51    :rtype: :class:`Connection`
    5152    :raises pgdb.OperationalError: error connecting to the database
    5253
    5354This function takes parameters specifying how to connect to a PostgreSQL
    54 database and returns a :class:`pgdbCnx` object using these parameters.
     55database and returns a :class:`Connection` object using these parameters.
    5556If specified, the *dsn* parameter must be a string with the format
    5657``'host:base:user:passwd:opt:tty'``. All of the parts specified in the *dsn*
     
    139140
    140141
    141 pgdbCnx -- The connection object
    142 ================================
    143 
    144 .. class:: pgdbCnx
     142Connection -- The connection object
     143===================================
     144
     145.. class:: Connection
    145146
    146147These connection objects respond to the following methods.
    147148
    148 Note that ``pgdb.pgdbCnx`` objects also implement the context manager protocol,
     149Note that ``pgdb.Connection`` objects also implement the context manager protocol,
    149150i.e. you can use them in a ``with`` statement.
    150151
     
    152153-----------------------------
    153154
    154 .. method:: pgdbCnx.close()
     155.. method:: Connection.close()
    155156
    156157    Close the connection now (rather than whenever it is deleted)
     
    167168-------------------------------
    168169
    169 .. method:: pgdbCnx.commit()
     170.. method:: Connection.commit()
    170171
    171172    Commit any pending transaction to the database
     
    178179------------------------------------
    179180
    180 .. method:: pgdbCnx.rollback()
     181.. method:: Connection.rollback()
    181182
    182183    Roll back any pending transaction to the database
     
    191192------------------------------------
    192193
    193 .. method:: pgdbCnx.cusor()
     194.. method:: Connection.cusor()
    194195
    195196    Return a new cursor object using the connection
    196197
    197198    :returns: a connection object
    198     :rtype: :class:`pgdbCursor`
    199 
    200 This method returns a new :class:`pgdbCursor` object that can be used to
     199    :rtype: :class:`Cursor`
     200
     201This method returns a new :class:`Cursor` object that can be used to
    201202operate on the database in the way described in the next section.
    202203
    203204
    204 pgdbCursor -- The cursor object
    205 ===============================
    206 
    207 .. class:: pgdbCursor
     205Cursor -- The cursor object
     206===========================
     207
     208.. class:: Cursor
    208209
    209210These objects represent a database cursor, which is used to manage the context
     
    216217Cursor objects respond to the following methods and attributes.
    217218
    218 Note that ``pgdbCursor`` objects also implement both the iterator and the
     219Note that ``Cursor`` objects also implement both the iterator and the
    219220context manager protocol, i.e. you can iterate over them and you can use them
    220221in a ``with`` statement.
     
    223224---------------------------------------------------
    224225
    225 .. attribute:: pgdbCursor.description
     226.. attribute:: Cursor.description
    226227
    227228    This read-only attribute is a sequence of 7-item sequences.
     
    241242    This attribute will be ``None`` for operations that do not return rows
    242243    or if the cursor has not had an operation invoked via the
    243     :meth:`pgdbCursor.execute` or :meth:`pgdbCursor.executemany` method yet.
     244    :meth:`Cursor.execute` or :meth:`Cursor.executemany` method yet.
    244245
    245246rowcount -- number of rows of the result
    246247----------------------------------------
    247248
    248 .. attribute:: pgdbCursor.rowcount
     249.. attribute:: Cursor.rowcount
    249250
    250251    This read-only attribute specifies the number of rows that the last
    251     :meth:`pgdbCursor.execute` or :meth:`pgdbCursor.executemany` call produced
     252    :meth:`Cursor.execute` or :meth:`Cursor.executemany` call produced
    252253    (for DQL statements like SELECT) or affected (for DML statements like
    253254    UPDATE or INSERT ). The attribute is -1 in case no such method call has
     
    258259-------------------------
    259260
    260 .. method:: pgdbCursor.close()
     261.. method:: Cursor.close()
    261262
    262263    Close the cursor now (rather than whenever it is deleted)
     
    271272---------------------------------------
    272273
    273 .. method:: pgdbCursor.execute(operation, [parameters])
     274.. method:: Cursor.execute(operation, [parameters])
    274275
    275276    Prepare and execute a database operation (query or command)
     
    290291The parameters may also be specified as list of tuples to e.g. insert multiple
    291292rows in a single operation, but this kind of usage is deprecated:
    292 :meth:`pgdbCursor.executemany` should be used instead.
     293:meth:`Cursor.executemany` should be used instead.
    293294
    294295executemany -- execute many similar database operations
    295296-------------------------------------------------------
    296297
    297 .. method:: pgdbCursor.executemany(operation, [seq_of_parameters])
     298.. method:: Cursor.executemany(operation, [seq_of_parameters])
    298299
    299300    Prepare and execute many similar database operations (queries or commands)
     
    312313----------------------------------------------
    313314
    314 .. method:: pgdbCursor.fetchone()
     315.. method:: Cursor.fetchone()
    315316
    316317    Fetch the next row of a query result set
     
    323324
    324325An :exc:`Error` (or subclass) exception is raised if the previous call to
    325 :meth:`pgdbCursor.execute` or :meth:`pgdbCursor.executemany` did not produce
     326:meth:`Cursor.execute` or :meth:`Cursor.executemany` did not produce
    326327any result set or no call was issued yet.
    327328
     
    329330-------------------------------------------------------
    330331
    331 .. method:: pgdbCursor.fetchmany([size=None], [keep=False])
     332.. method:: Cursor.fetchmany([size=None], [keep=False])
    332333
    333334    Fetch the next set of rows of a query result
     
    353354
    354355An :exc:`Error` (or subclass) exception is raised if the previous call to
    355 :meth:`pgdbCursor.execute` or :meth:`pgdbCursor.executemany` did not produce
     356:meth:`Cursor.execute` or :meth:`Cursor.executemany` did not produce
    356357any result set or no call was issued yet.
    357358
     
    359360For optimal performance, it is usually best to use the :attr:`arraysize`
    360361attribute. If the *size* parameter is used, then it is best for it to retain
    361 the same value from one :meth:`pgdbCursor.fetchmany` call to the next.
     362the same value from one :meth:`Cursor.fetchmany` call to the next.
    362363
    363364fetchall -- fetch all rows of the query result
    364365----------------------------------------------
    365366
    366 .. method:: pgdbCursor.fetchall()
     367.. method:: Cursor.fetchall()
    367368
    368369    Fetch all (remaining) rows of a query result
     
    378379------------------------------------------------
    379380
    380 .. method:: pgdbCursor.row_factory(row)
     381.. method:: Cursor.row_factory(row)
    381382
    382383    Process rows before they are returned
     
    390391if you want to return rows as dicts instead of tuples::
    391392
    392     class DictCursor(pgdb.pgdbCursor):
     393    class DictCursor(pgdb.Cursor):
    393394
    394395        def row_factory(self, row):
     
    401402-------------------------------------------------
    402403
    403 .. attribute:: pgdbCursor.arraysize
     404.. attribute:: Cursor.arraysize
    404405
    405406    The number of rows to fetch at a time
    406407
    407408This read/write attribute specifies the number of rows to fetch at a time with
    408 :meth:`pgdbCursor.fetchmany`. It defaults to 1 meaning to fetch a single row
     409:meth:`Cursor.fetchmany`. It defaults to 1 meaning to fetch a single row
    409410at a time.
    410411
    411412
    412 pgdbType -- Type objects and constructors
    413 =========================================
    414 
    415 .. class:: pgdbType
    416 
    417 The :attr:`pgdbCursor.description` attribute returns information about each
     413Type -- Type objects and constructors
     414=====================================
     415
     416.. class:: Type
     417
     418The :attr:`Cursor.description` attribute returns information about each
    418419of the result columns of a query. The *type_code* must compare equal to one
    419 of the :class:`pgdbType` objects defined below. Type objects can be equal to
     420of the :class:`Type` objects defined below. Type objects can be equal to
    420421more than one type code (e.g. :class:`DATETIME` is equal to the type codes
    421422for date, time and timestamp columns).
  • trunk/module/pgdb.py

    r678 r679  
    165165
    166166
    167 class pgdbTypeCache(dict):
     167class TypeCache(dict):
    168168    """Cache for database types."""
    169169
    170170    def __init__(self, cnx):
    171171        """Initialize type cache for connection."""
    172         super(pgdbTypeCache, self).__init__()
     172        super(TypeCache, self).__init__()
    173173        self._src = cnx.source()
    174174
     
    216216### Cursor Object
    217217
    218 class pgdbCursor(object):
     218class Cursor(object):
    219219    """Cursor object."""
    220220
     
    294294        e.g. a dict factory:
    295295
    296             class DictCursor(pgdb.pgdbCursor):
     296            class DictCursor(pgdb.Cursor):
    297297
    298298                def row_factory(self, row):
     
    442442### Connection Objects
    443443
    444 class pgdbCnx(object):
     444class Connection(object):
    445445    """Connection object."""
    446446
     
    461461        self._cnx = cnx  # connection
    462462        self._tnx = False  # transaction state
    463         self._type_cache = pgdbTypeCache(cnx)
     463        self._type_cache = TypeCache(cnx)
    464464        try:
    465465            self._cnx.source()
     
    531531        if self._cnx:
    532532            try:
    533                 return pgdbCursor(self)
     533                return Cursor(self)
    534534            except Exception:
    535535                raise _op_error("invalid connection")
     
    603603    cnx = _connect_(dbbase, dbhost, dbport, dbopt,
    604604        dbtty, dbuser, dbpasswd)
    605     return pgdbCnx(cnx)
     605    return Connection(cnx)
    606606
    607607
    608608### Types Handling
    609609
    610 class pgdbType(frozenset):
     610class Type(frozenset):
    611611    """Type class for a couple of PostgreSQL data types.
    612612
     
    619619        if isinstance(values, basestring):
    620620            values = values.split()
    621         return super(pgdbType, cls).__new__(cls, values)
     621        return super(Type, cls).__new__(cls, values)
    622622
    623623    def __eq__(self, other):
     
    625625            return other in self
    626626        else:
    627             return super(pgdbType, self).__eq__(other)
     627            return super(Type, self).__eq__(other)
    628628
    629629    def __ne__(self, other):
     
    631631            return other not in self
    632632        else:
    633             return super(pgdbType, self).__ne__(other)
     633            return super(Type, self).__ne__(other)
    634634
    635635
    636636# Mandatory type objects defined by DB-API 2 specs:
    637637
    638 STRING = pgdbType('char bpchar name text varchar')
    639 BINARY = pgdbType('bytea')
    640 NUMBER = pgdbType('int2 int4 serial int8 float4 float8 numeric money')
    641 DATETIME = pgdbType('date time timetz timestamp timestamptz datetime abstime'
     638STRING = Type('char bpchar name text varchar')
     639BINARY = Type('bytea')
     640NUMBER = Type('int2 int4 serial int8 float4 float8 numeric money')
     641DATETIME = Type('date time timetz timestamp timestamptz datetime abstime'
    642642    ' interval tinterval timespan reltime')
    643 ROWID = pgdbType('oid oid8')
     643ROWID = Type('oid oid8')
    644644
    645645
    646646# Additional type objects (more specific):
    647647
    648 BOOL = pgdbType('bool')
    649 SMALLINT = pgdbType('int2')
    650 INTEGER = pgdbType('int2 int4 int8 serial')
    651 LONG = pgdbType('int8')
    652 FLOAT = pgdbType('float4 float8')
    653 NUMERIC = pgdbType('numeric')
    654 MONEY = pgdbType('money')
    655 DATE = pgdbType('date')
    656 TIME = pgdbType('time timetz')
    657 TIMESTAMP = pgdbType('timestamp timestamptz datetime abstime')
    658 INTERVAL = pgdbType('interval tinterval timespan reltime')
     648BOOL = Type('bool')
     649SMALLINT = Type('int2')
     650INTEGER = Type('int2 int4 int8 serial')
     651LONG = Type('int8')
     652FLOAT = Type('float4 float8')
     653NUMERIC = Type('numeric')
     654MONEY = Type('money')
     655DATE = Type('date')
     656TIME = Type('time timetz')
     657TIMESTAMP = Type('timestamp timestamptz datetime abstime')
     658INTERVAL = Type('interval tinterval timespan reltime')
    659659
    660660
  • trunk/module/tests/test_dbapi20.py

    r667 r679  
    5151            con.close()
    5252        except pgdb.Error:  # try to create a missing database
    53             warning.
    5453            import pg
    5554            try:  # first try to log in as superuser
     
    6463
    6564    def test_row_factory(self):
    66         class myCursor(pgdb.pgdbCursor):
     65
     66        class DictCursor(pgdb.Cursor):
     67
    6768            def row_factory(self, row):
    68                 d = {}
    69                 for idx, col in enumerate(self.description):
    70                     d[col[0]] = row[idx]
    71                 return d
    72 
    73         con = self._connect()
    74         cur = myCursor(con)
     69                return {desc[0]:value
     70                    for desc, value in zip(self.description, row)}
     71
     72        con = self._connect()
     73        cur = DictCursor(con)
    7574        ret = cur.execute("select 1 as a, 2 as b")
    7675        self.assertTrue(ret is cur, 'execute() should return cursor')
Note: See TracChangeset for help on using the changeset viewer.