From 575b2b5f7724ef349e7d7e76a430d124f474fee0 Mon Sep 17 00:00:00 2001 From: Daniele Varrazzo Date: Sat, 25 Sep 2010 23:55:55 +0100 Subject: [PATCH] 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. --- lib/extras.py | 5 ++++- tests/types_extras.py | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/extras.py b/lib/extras.py index 88f85a74..b75eef98 100644 --- a/lib/extras.py +++ b/lib/extras.py @@ -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 diff --git a/tests/types_extras.py b/tests/types_extras.py index dc406fd8..b7fd015e 100644 --- a/tests/types_extras.py +++ b/tests/types_extras.py @@ -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,