pgtype icon indicating copy to clipboard operation
pgtype copied to clipboard

cannot use net.ParseIP(c.IP()) (type net.IP) as type pgtype.Inet in field value

Open encryptblockr opened this issue 3 years ago • 5 comments
trafficstars

here is my model

import (
    "github.com/jackc/pgtype"
)

...
ClientIp     pgtype.Inet `json:"client_ip" gorm:"type:inet;not null"`
...

I am trying to parse the ip address which is in string format to type pgtype.Inet in postgresql database like this when inserting into the database

import (
    "net"
)

...
ClientIp:     net.ParseIP(c.IP()),
...

we are told to parse the ip using net package but this is error from that

cannot use net.ParseIP(c.IP()) (type net.IP) as type pgtype.Inet in field value

I have also tried using net package for the model

import (
    "net"
)

...
ClientIp     net.IP `json:"client_ip" gorm:"type:inet;not null"`
...

but kept getting this error

sql: Scan error on column index 16, name "client_ip": unsupported Scan, storing driver.Value type string into type *net.IP

so how do we store inet values inside postgresql using GORM?

encryptblockr avatar Aug 05 '22 09:08 encryptblockr

I'm not sure how gorm works. But the following reads an pgtype.Inet with database/sql:

package main

import (
	"database/sql"
	"fmt"
	"log"

	"github.com/jackc/pgtype"
	_ "github.com/jackc/pgx/v4/stdlib"
)

func main() {
	db, err := sql.Open("pgx", "")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	var ip pgtype.Inet

	err = db.QueryRow("select '127.0.0.1'::inet").Scan(&ip)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(ip)
}

jackc avatar Aug 06 '22 09:08 jackc

yeah trying to do this with GORM It is able to insert the values in the database but getting the scan error when running query on it

sql: Scan error on column index 16, name "client_ip": unsupported Scan, storing driver.Value type string into type *net.IP

encryptblockr avatar Aug 11 '22 19:08 encryptblockr

I don't know anything about GORM, but it looks like your trying to scan into *net.IP. That's not going to work unless GORM is doing some magic. database/sql doesn't support scanning into non-primitive types unless they implement sql.Scanner.

jackc avatar Aug 12 '22 02:08 jackc

so what do i do? do i not use GORM to insert and get records that has IP address? It is 2022, i can not believe GORM can not do this I mean this is a widely used thing storing IP addresses am amazed at this limitation

here is GORM doc https://gorm.io/docs/index.html

what do i do please? will appreciate your advice thanks

encryptblockr avatar Aug 12 '22 18:08 encryptblockr

I don't know. Like I said I don't use GORM or any other Go ORM for that matter. I typically write my own SQL and mapping code more or less by hand.

jackc avatar Aug 13 '22 14:08 jackc