jackc / pgtype

MIT License
318 stars 112 forks source link

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

Open encryptblockr opened 2 years ago

encryptblockr commented 2 years ago

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?

jackc commented 2 years ago

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)
}
encryptblockr commented 2 years ago

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
jackc commented 2 years ago

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.

encryptblockr commented 2 years ago

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

jackc commented 2 years ago

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.