The Inet type knows how to adapt itself.

Implemented __conform__ as the Adaptation PEP suggests. It is not
required for the type to be registered as adapter.
This commit is contained in:
Daniele Varrazzo 2010-09-25 23:55:55 +01:00
parent 75a6f783c5
commit 575b2b5f77
2 changed files with 17 additions and 1 deletions

View File

@ -423,6 +423,10 @@ class Inet(object):
obj.prepare(self._conn)
return obj.getquoted()+"::inet"
def __conform__(self, foo):
if foo is _ext.ISQLQuote:
return self
def __str__(self):
return str(self.addr)
@ -432,7 +436,6 @@ def register_inet(oid=None, conn_or_curs=None):
_ext.INET = _ext.new_type((oid, ), "INET",
lambda data, cursor: data and Inet(data) or None)
_ext.register_type(_ext.INET, conn_or_curs)
_ext.register_adapter(Inet, lambda x: x)
return _ext.INET

View File

@ -79,6 +79,19 @@ class TypesExtrasTests(unittest.TestCase):
s = self.execute("SELECT NULL::inet AS foo")
self.failUnless(s is None)
def test_inet_conform(self):
from psycopg2.extras import Inet
i = Inet("192.168.1.0/24")
a = psycopg2.extensions.adapt(i)
a.prepare(self.conn)
self.assertEqual("E'192.168.1.0/24'::inet", a.getquoted())
# adapts ok with unicode too
i = Inet(u"192.168.1.0/24")
a = psycopg2.extensions.adapt(i)
a.prepare(self.conn)
self.assertEqual("E'192.168.1.0/24'::inet", a.getquoted())
def test_adapt_fail(self):
class Foo(object): pass
self.assertRaises(psycopg2.ProgrammingError,