Encode from net.IP to inet and cidr

pull/92/head
Jack Christensen 2015-09-09 18:49:20 -05:00
parent ee7d621528
commit 8b296b9d58
4 changed files with 53 additions and 0 deletions

View File

@ -1,5 +1,6 @@
# Master
* Encode from net.IP to inet and cidr
* Generalize encoding pointer to string to any PostgreSQL type
* Add UUID encoding from pointer to string (Joseph Glanville)
* Add null mapping to pointer to pointer (Jonathan Rudenberg)

6
doc.go
View File

@ -150,6 +150,12 @@ JSON and JSONB Mapping
pgx includes built-in support to marshal and unmarshal between Go types and
the PostgreSQL JSON and JSONB.
Inet and Cidr Mapping
pgx encodes from net.IPNet to and from inet and cidr PostgreSQL types. In
addition, as a convenience pgx will encode from a net.IP; it will assume a /32
netmask for IPv4 and a /128 for IPv6.
Custom Type Support
pgx includes support for the common data types like integers, floats, strings,

View File

@ -1196,6 +1196,10 @@ func encodeInet(w *WriteBuf, value interface{}) error {
switch value := value.(type) {
case net.IPNet:
ipnet = value
case net.IP:
ipnet.IP = value
bitCount := len(value) * 8
ipnet.Mask = net.CIDRMask(bitCount, bitCount)
default:
return fmt.Errorf("Expected net.IPNet, received %T %v", value, value)
}

View File

@ -274,6 +274,48 @@ func TestInetCidrTranscode(t *testing.T) {
}
}
func TestInetCidrTranscodeWithJustIP(t *testing.T) {
t.Parallel()
conn := mustConnect(t, *defaultConnConfig)
defer closeConn(t, conn)
tests := []struct {
sql string
value string
}{
{"select $1::inet", "0.0.0.0/32"},
{"select $1::inet", "127.0.0.1/32"},
{"select $1::inet", "12.34.56.0/32"},
{"select $1::inet", "255.255.255.255/32"},
{"select $1::inet", "::/128"},
{"select $1::inet", "2607:f8b0:4009:80b::200e/128"},
{"select $1::cidr", "0.0.0.0/32"},
{"select $1::cidr", "127.0.0.1/32"},
{"select $1::cidr", "12.34.56.0/32"},
{"select $1::cidr", "255.255.255.255/32"},
{"select $1::cidr", "::/128"},
{"select $1::cidr", "2607:f8b0:4009:80b::200e/128"},
}
for i, tt := range tests {
expected := mustParseCIDR(t, tt.value)
var actual net.IPNet
err := conn.QueryRow(tt.sql, expected.IP).Scan(&actual)
if err != nil {
t.Errorf("%d. Unexpected failure: %v (sql -> %v, value -> %v)", i, err, tt.sql, tt.value)
continue
}
if actual.String() != expected.String() {
t.Errorf("%d. Expected %v, got %v (sql -> %v)", i, tt.value, actual, tt.sql)
}
ensureConnValid(t, conn)
}
}
func TestNullX(t *testing.T) {
t.Parallel()