Author: cito
Date: Wed Dec 30 16:31:47 2015
New Revision: 679

Log:
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.

Modified:
   branches/4.x/docs/changelog.rst
   branches/4.x/docs/pg.rst
   branches/4.x/docs/pgdb.rst
   branches/4.x/module/pgdb.py
   trunk/docs/changelog.rst
   trunk/docs/pg.rst
   trunk/docs/pgdb.rst
   trunk/module/pgdb.py
   trunk/module/tests/test_dbapi20.py

Modified: branches/4.x/docs/changelog.rst
==============================================================================
--- branches/4.x/docs/changelog.rst     Wed Dec 30 16:01:53 2015        (r678)
+++ branches/4.x/docs/changelog.rst     Wed Dec 30 16:31:47 2015        (r679)
@@ -57,7 +57,6 @@
 - New method use_regtypes() that can be called to let getattnames()
   return regular type names instead of the simplified classic types (#44).
 
-
 Version 4.0 (2009-01-01)
 ------------------------
 - Dropped support for Python below 2.3 and PostgreSQL below 7.4.
@@ -105,7 +104,6 @@
 - delete() now also works based on the primary key if no oid available
   and returns whether the row existed or not.
 
-
 Version 3.8.1 (2006-06-05)
 --------------------------
 - Use string methods instead of deprecated string functions.

Modified: branches/4.x/docs/pg.rst
==============================================================================
--- branches/4.x/docs/pg.rst    Wed Dec 30 16:01:53 2015        (r678)
+++ branches/4.x/docs/pg.rst    Wed Dec 30 16:31:47 2015        (r679)
@@ -9,6 +9,7 @@
 
 Introduction
 ============
+
 You may either choose to use the "classic" PyGreSQL interface
 provided by the :mod:`pg` module or else the
 DB-API 2.0 compliant interface provided by the :mod:`pgdb` module.

Modified: branches/4.x/docs/pgdb.rst
==============================================================================
--- branches/4.x/docs/pgdb.rst  Wed Dec 30 16:01:53 2015        (r678)
+++ branches/4.x/docs/pgdb.rst  Wed Dec 30 16:31:47 2015        (r679)
@@ -9,6 +9,7 @@
 
 Introduction
 ============
+
 You may either choose to use the "classic" PyGreSQL interface
 provided by the :mod:`pg` module or else the
 DB-API 2.0 compliant interface provided by the :mod:`pgdb` module.

Modified: branches/4.x/module/pgdb.py
==============================================================================
--- branches/4.x/module/pgdb.py Wed Dec 30 16:01:53 2015        (r678)
+++ branches/4.x/module/pgdb.py Wed Dec 30 16:31:47 2015        (r679)
@@ -101,7 +101,7 @@
 
 # shortcut methods are not supported by default
 # since they have been excluded from DB API 2
-# and are not recommended by the DB SIG;
+# and are not recommended by the DB SIG.
 
 shortcutmethods = 0
 
@@ -290,12 +290,14 @@
         You can overwrite this with a custom row factory,
         e.g. a dict factory:
 
-        class myCursor(pgdb.pgdbCursor):
-            def cursor.row_factory(self, row):
-                d = {}
-                for idx, col in enumerate(self.description):
-                    d[col[0]] = row[idx]
-                return d
+            class myCursor(pgdb.pgdbCursor):
+
+                def row_factory(self, row):
+                    d = {}
+                    for idx, col in enumerate(self.description):
+                        d[col[0]] = row[idx]
+                    return d
+
         cursor = myCursor(cnx)
 
         """

Modified: trunk/docs/changelog.rst
==============================================================================
--- trunk/docs/changelog.rst    Wed Dec 30 16:01:53 2015        (r678)
+++ trunk/docs/changelog.rst    Wed Dec 30 16:31:47 2015        (r679)
@@ -6,7 +6,11 @@
 - This version runs on both Python 2 and Python 3.
 - The supported versions are Python 2.6, 2.7, 3.3, 3.4 and 3.5.
 - The supported PostgreSQL versions are 9.0, 9.1, 9.2, 9.3 and 9.4.
-
+- The names of the various types supported by the classic and DB-API 2
+  modules have been renamed to become simpler, more intuitive and in
+  line with the names used in the DB-API 2 documentation.
+  Since the API provides objects of these types only by the use of
+  constructor functions, this should not cause any incompatibilities.
 
 Version 4.2
 -----------
@@ -64,7 +68,6 @@
 - New method use_regtypes() that can be called to let getattnames()
   return regular type names instead of the simplified classic types (#44).
 
-
 Version 4.0 (2009-01-01)
 ------------------------
 - Dropped support for Python below 2.3 and PostgreSQL below 7.4.
@@ -112,7 +115,6 @@
 - delete() now also works based on the primary key if no oid available
   and returns whether the row existed or not.
 
-
 Version 3.8.1 (2006-06-05)
 --------------------------
 - Use string methods instead of deprecated string functions.

Modified: trunk/docs/pg.rst
==============================================================================
--- trunk/docs/pg.rst   Wed Dec 30 16:01:53 2015        (r678)
+++ trunk/docs/pg.rst   Wed Dec 30 16:31:47 2015        (r679)
@@ -9,6 +9,7 @@
 
 Introduction
 ============
+
 You may either choose to use the "classic" PyGreSQL interface
 provided by the :mod:`pg` module or else the
 DB-API 2.0 compliant interface provided by the :mod:`pgdb` module.

Modified: trunk/docs/pgdb.rst
==============================================================================
--- trunk/docs/pgdb.rst Wed Dec 30 16:01:53 2015        (r678)
+++ trunk/docs/pgdb.rst Wed Dec 30 16:31:47 2015        (r679)
@@ -9,6 +9,7 @@
 
 Introduction
 ============
+
 You may either choose to use the "classic" PyGreSQL interface
 provided by the :mod:`pg` module or else the
 DB-API 2.0 compliant interface provided by the :mod:`pgdb` module.
@@ -47,11 +48,11 @@
     :param str host: the hostname of the database
     :param database: the name of the database
     :returns: a connection object
-    :rtype: :class:`pgdbCnx`
+    :rtype: :class:`Connection`
     :raises pgdb.OperationalError: error connecting to the database
 
 This function takes parameters specifying how to connect to a PostgreSQL
-database and returns a :class:`pgdbCnx` object using these parameters.
+database and returns a :class:`Connection` object using these parameters.
 If specified, the *dsn* parameter must be a string with the format
 ``'host:base:user:passwd:opt:tty'``. All of the parts specified in the *dsn*
 are optional. You can also specify the parameters individually using keyword
@@ -138,20 +139,20 @@
     supported by the database.
 
 
-pgdbCnx -- The connection object
-================================
+Connection -- The connection object
+===================================
 
-.. class:: pgdbCnx
+.. class:: Connection
 
 These connection objects respond to the following methods.
 
-Note that ``pgdb.pgdbCnx`` objects also implement the context manager protocol,
+Note that ``pgdb.Connection`` objects also implement the context manager 
protocol,
 i.e. you can use them in a ``with`` statement.
 
 close -- close the connection
 -----------------------------
 
-.. method:: pgdbCnx.close()
+.. method:: Connection.close()
 
     Close the connection now (rather than whenever it is deleted)
 
@@ -166,7 +167,7 @@
 commit -- commit the connection
 -------------------------------
 
-.. method:: pgdbCnx.commit()
+.. method:: Connection.commit()
 
     Commit any pending transaction to the database
 
@@ -177,7 +178,7 @@
 rollback -- roll back the connection
 ------------------------------------
 
-.. method:: pgdbCnx.rollback()
+.. method:: Connection.rollback()
 
     Roll back any pending transaction to the database
 
@@ -190,21 +191,21 @@
 cursor -- return a new cursor object
 ------------------------------------
 
-.. method:: pgdbCnx.cusor()
+.. method:: Connection.cusor()
 
     Return a new cursor object using the connection
 
     :returns: a connection object
-    :rtype: :class:`pgdbCursor`
+    :rtype: :class:`Cursor`
 
-This method returns a new :class:`pgdbCursor` object that can be used to
+This method returns a new :class:`Cursor` object that can be used to
 operate on the database in the way described in the next section.
 
 
-pgdbCursor -- The cursor object
-===============================
+Cursor -- The cursor object
+===========================
 
-.. class:: pgdbCursor
+.. class:: Cursor
 
 These objects represent a database cursor, which is used to manage the context
 of a fetch operation. Cursors created from the same connection are not
@@ -215,14 +216,14 @@
 
 Cursor objects respond to the following methods and attributes.
 
-Note that ``pgdbCursor`` objects also implement both the iterator and the
+Note that ``Cursor`` objects also implement both the iterator and the
 context manager protocol, i.e. you can iterate over them and you can use them
 in a ``with`` statement.
 
 description -- details regarding the result columns
 ---------------------------------------------------
 
-.. attribute:: pgdbCursor.description
+.. attribute:: Cursor.description
 
     This read-only attribute is a sequence of 7-item sequences.
 
@@ -240,15 +241,15 @@
 
     This attribute will be ``None`` for operations that do not return rows
     or if the cursor has not had an operation invoked via the
-    :meth:`pgdbCursor.execute` or :meth:`pgdbCursor.executemany` method yet.
+    :meth:`Cursor.execute` or :meth:`Cursor.executemany` method yet.
 
 rowcount -- number of rows of the result
 ----------------------------------------
 
-.. attribute:: pgdbCursor.rowcount
+.. attribute:: Cursor.rowcount
 
     This read-only attribute specifies the number of rows that the last
-    :meth:`pgdbCursor.execute` or :meth:`pgdbCursor.executemany` call produced
+    :meth:`Cursor.execute` or :meth:`Cursor.executemany` call produced
     (for DQL statements like SELECT) or affected (for DML statements like
     UPDATE or INSERT ). The attribute is -1 in case no such method call has
     been performed on the cursor or the rowcount of the last operation
@@ -257,7 +258,7 @@
 close -- close the cursor
 -------------------------
 
-.. method:: pgdbCursor.close()
+.. method:: Cursor.close()
 
     Close the cursor now (rather than whenever it is deleted)
 
@@ -270,7 +271,7 @@
 execute -- execute a database operation
 ---------------------------------------
 
-.. method:: pgdbCursor.execute(operation, [parameters])
+.. method:: Cursor.execute(operation, [parameters])
 
     Prepare and execute a database operation (query or command)
 
@@ -289,12 +290,12 @@
 
 The parameters may also be specified as list of tuples to e.g. insert multiple
 rows in a single operation, but this kind of usage is deprecated:
-:meth:`pgdbCursor.executemany` should be used instead.
+:meth:`Cursor.executemany` should be used instead.
 
 executemany -- execute many similar database operations
 -------------------------------------------------------
 
-.. method:: pgdbCursor.executemany(operation, [seq_of_parameters])
+.. method:: Cursor.executemany(operation, [seq_of_parameters])
 
     Prepare and execute many similar database operations (queries or commands)
 
@@ -311,7 +312,7 @@
 fetchone -- fetch next row of the query result
 ----------------------------------------------
 
-.. method:: pgdbCursor.fetchone()
+.. method:: Cursor.fetchone()
 
     Fetch the next row of a query result set
 
@@ -322,13 +323,13 @@
 or ``None`` when no more data is available.
 
 An :exc:`Error` (or subclass) exception is raised if the previous call to
-:meth:`pgdbCursor.execute` or :meth:`pgdbCursor.executemany` did not produce
+:meth:`Cursor.execute` or :meth:`Cursor.executemany` did not produce
 any result set or no call was issued yet.
 
 fetchmany -- fetch next set of rows of the query result
 -------------------------------------------------------
 
-.. method:: pgdbCursor.fetchmany([size=None], [keep=False])
+.. method:: Cursor.fetchmany([size=None], [keep=False])
 
     Fetch the next set of rows of a query result
 
@@ -352,18 +353,18 @@
 available, fewer rows may be returned.
 
 An :exc:`Error` (or subclass) exception is raised if the previous call to
-:meth:`pgdbCursor.execute` or :meth:`pgdbCursor.executemany` did not produce
+:meth:`Cursor.execute` or :meth:`Cursor.executemany` did not produce
 any result set or no call was issued yet.
 
 Note there are performance considerations involved with the *size* parameter.
 For optimal performance, it is usually best to use the :attr:`arraysize`
 attribute. If the *size* parameter is used, then it is best for it to retain
-the same value from one :meth:`pgdbCursor.fetchmany` call to the next.
+the same value from one :meth:`Cursor.fetchmany` call to the next.
 
 fetchall -- fetch all rows of the query result
 ----------------------------------------------
 
-.. method:: pgdbCursor.fetchall()
+.. method:: Cursor.fetchall()
 
     Fetch all (remaining) rows of a query result
 
@@ -377,7 +378,7 @@
 row_factory -- process a row of the query result
 ------------------------------------------------
 
-.. method:: pgdbCursor.row_factory(row)
+.. method:: Cursor.row_factory(row)
 
     Process rows before they are returned
 
@@ -389,7 +390,7 @@
 You can overwrite this method with a custom row factory, e.g.
 if you want to return rows as dicts instead of tuples::
 
-    class DictCursor(pgdb.pgdbCursor):
+    class DictCursor(pgdb.Cursor):
 
         def row_factory(self, row):
             return {desc[0]:value
@@ -400,23 +401,23 @@
 arraysize - the number of rows to fetch at a time
 -------------------------------------------------
 
-.. attribute:: pgdbCursor.arraysize
+.. attribute:: Cursor.arraysize
 
     The number of rows to fetch at a time
 
 This read/write attribute specifies the number of rows to fetch at a time with
-:meth:`pgdbCursor.fetchmany`. It defaults to 1 meaning to fetch a single row
+:meth:`Cursor.fetchmany`. It defaults to 1 meaning to fetch a single row
 at a time.
 
 
-pgdbType -- Type objects and constructors
-=========================================
+Type -- Type objects and constructors
+=====================================
 
-.. class:: pgdbType
+.. class:: Type
 
-The :attr:`pgdbCursor.description` attribute returns information about each
+The :attr:`Cursor.description` attribute returns information about each
 of the result columns of a query. The *type_code* must compare equal to one
-of the :class:`pgdbType` objects defined below. Type objects can be equal to
+of the :class:`Type` objects defined below. Type objects can be equal to
 more than one type code (e.g. :class:`DATETIME` is equal to the type codes
 for date, time and timestamp columns).
 

Modified: trunk/module/pgdb.py
==============================================================================
--- trunk/module/pgdb.py        Wed Dec 30 16:01:53 2015        (r678)
+++ trunk/module/pgdb.py        Wed Dec 30 16:31:47 2015        (r679)
@@ -164,12 +164,12 @@
     return _db_error(msg, OperationalError)
 
 
-class pgdbTypeCache(dict):
+class TypeCache(dict):
     """Cache for database types."""
 
     def __init__(self, cnx):
         """Initialize type cache for connection."""
-        super(pgdbTypeCache, self).__init__()
+        super(TypeCache, self).__init__()
         self._src = cnx.source()
 
     @staticmethod
@@ -215,7 +215,7 @@
 
 ### Cursor Object
 
-class pgdbCursor(object):
+class Cursor(object):
     """Cursor object."""
 
     def __init__(self, dbcnx):
@@ -293,7 +293,7 @@
         You can overwrite this with a custom row factory,
         e.g. a dict factory:
 
-            class DictCursor(pgdb.pgdbCursor):
+            class DictCursor(pgdb.Cursor):
 
                 def row_factory(self, row):
                     return {desc[0]:value
@@ -441,7 +441,7 @@
 
 ### Connection Objects
 
-class pgdbCnx(object):
+class Connection(object):
     """Connection object."""
 
     # expose the exceptions as attributes on the connection object
@@ -460,7 +460,7 @@
         """Create a database connection object."""
         self._cnx = cnx  # connection
         self._tnx = False  # transaction state
-        self._type_cache = pgdbTypeCache(cnx)
+        self._type_cache = TypeCache(cnx)
         try:
             self._cnx.source()
         except Exception:
@@ -530,7 +530,7 @@
         """Return a new cursor object using the connection."""
         if self._cnx:
             try:
-                return pgdbCursor(self)
+                return Cursor(self)
             except Exception:
                 raise _op_error("invalid connection")
         else:
@@ -602,12 +602,12 @@
     # open the connection
     cnx = _connect_(dbbase, dbhost, dbport, dbopt,
         dbtty, dbuser, dbpasswd)
-    return pgdbCnx(cnx)
+    return Connection(cnx)
 
 
 ### Types Handling
 
-class pgdbType(frozenset):
+class Type(frozenset):
     """Type class for a couple of PostgreSQL data types.
 
     PostgreSQL is object-oriented: types are dynamic.
@@ -618,44 +618,44 @@
     def __new__(cls, values):
         if isinstance(values, basestring):
             values = values.split()
-        return super(pgdbType, cls).__new__(cls, values)
+        return super(Type, cls).__new__(cls, values)
 
     def __eq__(self, other):
         if isinstance(other, basestring):
             return other in self
         else:
-            return super(pgdbType, self).__eq__(other)
+            return super(Type, self).__eq__(other)
 
     def __ne__(self, other):
         if isinstance(other, basestring):
             return other not in self
         else:
-            return super(pgdbType, self).__ne__(other)
+            return super(Type, self).__ne__(other)
 
 
 # Mandatory type objects defined by DB-API 2 specs:
 
-STRING = pgdbType('char bpchar name text varchar')
-BINARY = pgdbType('bytea')
-NUMBER = pgdbType('int2 int4 serial int8 float4 float8 numeric money')
-DATETIME = pgdbType('date time timetz timestamp timestamptz datetime abstime'
+STRING = Type('char bpchar name text varchar')
+BINARY = Type('bytea')
+NUMBER = Type('int2 int4 serial int8 float4 float8 numeric money')
+DATETIME = Type('date time timetz timestamp timestamptz datetime abstime'
     ' interval tinterval timespan reltime')
-ROWID = pgdbType('oid oid8')
+ROWID = Type('oid oid8')
 
 
 # Additional type objects (more specific):
 
-BOOL = pgdbType('bool')
-SMALLINT = pgdbType('int2')
-INTEGER = pgdbType('int2 int4 int8 serial')
-LONG = pgdbType('int8')
-FLOAT = pgdbType('float4 float8')
-NUMERIC = pgdbType('numeric')
-MONEY = pgdbType('money')
-DATE = pgdbType('date')
-TIME = pgdbType('time timetz')
-TIMESTAMP = pgdbType('timestamp timestamptz datetime abstime')
-INTERVAL = pgdbType('interval tinterval timespan reltime')
+BOOL = Type('bool')
+SMALLINT = Type('int2')
+INTEGER = Type('int2 int4 int8 serial')
+LONG = Type('int8')
+FLOAT = Type('float4 float8')
+NUMERIC = Type('numeric')
+MONEY = Type('money')
+DATE = Type('date')
+TIME = Type('time timetz')
+TIMESTAMP = Type('timestamp timestamptz datetime abstime')
+INTERVAL = Type('interval tinterval timespan reltime')
 
 
 # Mandatory type helpers defined by DB-API 2 specs:

Modified: trunk/module/tests/test_dbapi20.py
==============================================================================
--- trunk/module/tests/test_dbapi20.py  Wed Dec 30 16:01:53 2015        (r678)
+++ trunk/module/tests/test_dbapi20.py  Wed Dec 30 16:31:47 2015        (r679)
@@ -50,7 +50,6 @@
             con = self._connect()
             con.close()
         except pgdb.Error:  # try to create a missing database
-            warning.
             import pg
             try:  # first try to log in as superuser
                 db = pg.DB('postgres', dbhost or None, dbport or -1,
@@ -63,15 +62,15 @@
         dbapi20.DatabaseAPI20Test.tearDown(self)
 
     def test_row_factory(self):
-        class myCursor(pgdb.pgdbCursor):
+
+        class DictCursor(pgdb.Cursor):
+
             def row_factory(self, row):
-                d = {}
-                for idx, col in enumerate(self.description):
-                    d[col[0]] = row[idx]
-                return d
+                return {desc[0]:value
+                    for desc, value in zip(self.description, row)}
 
         con = self._connect()
-        cur = myCursor(con)
+        cur = DictCursor(con)
         ret = cur.execute("select 1 as a, 2 as b")
         self.assertTrue(ret is cur, 'execute() should return cursor')
         self.assertEqual(cur.fetchone(), {'a': 1, 'b': 2})
_______________________________________________
PyGreSQL mailing list
[email protected]
https://mail.vex.net/mailman/listinfo.cgi/pygresql

Reply via email to