Skip to content

Commit 2707ca3

Browse files
committed
Fix handling of CIDR input to "inet" data type
PostgreSQL actually allows network addresses in "inet", so handle this. Fixes: #37
1 parent 5ca0b07 commit 2707ca3

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

asyncpg/protocol/codecs/network.pyx

+9-3
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ cdef net_decode(ConnectionSettings settings, FastReadBuffer buf):
6262

6363
addr = cpython.PyBytes_FromStringAndSize(buf.read(addrlen), addrlen)
6464

65-
if is_cidr:
65+
if is_cidr or bits > 0:
6666
return _ipnet(addr).supernet(new_prefix=cpython.PyLong_FromLong(bits))
6767
else:
6868
return _ipaddr(addr)
@@ -81,8 +81,14 @@ cdef inet_encode(ConnectionSettings settings, WriteBuffer buf, obj):
8181
cdef:
8282
object ipaddr
8383

84-
ipaddr = _ipaddr(obj)
85-
_net_encode(buf, ipaddr.version, 0, 0, ipaddr.packed)
84+
try:
85+
ipaddr = _ipaddr(obj)
86+
except ValueError:
87+
# PostgreSQL accepts *both* CIDR and host values
88+
# for the host datatype.
89+
cidr_encode(settings, buf, obj)
90+
else:
91+
_net_encode(buf, ipaddr.version, 0, 0, ipaddr.packed)
8692

8793

8894
cdef init_network_codecs():

tests/test_codecs.py

+6
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,12 @@ def _timezone(offset):
287287
ipaddress.IPv6Address('ffff' + ':ffff' * 7),
288288
ipaddress.IPv6Address('::1'),
289289
ipaddress.IPv6Address('::'),
290+
dict(
291+
input='127.0.0.0/8',
292+
output=ipaddress.IPv4Network('127.0.0.0/8')),
293+
dict(
294+
input='127.0.0.1/32',
295+
output=ipaddress.IPv4Network('127.0.0.1/32')),
290296
]),
291297
('macaddr', 'macaddr', [
292298
'00:00:00:00:00:00',

0 commit comments

Comments
 (0)