Code Monkey home page Code Monkey logo

Comments (8)

vmihailenco avatar vmihailenco commented on July 22, 2024

Do you mean that you tried something like

type MyObject struct {
    Id bson.ObjectId
}

and it does not work? If so what error do you receive?

from pg.

xy02 avatar xy02 commented on July 22, 2024
package main

import (
    "fmt"

    "gopkg.in/mgo.v2/bson"
    "gopkg.in/pg.v4"
)

type User struct {
    Id     bson.ObjectId `sql:",pk"`
    Name   string
    Emails []string
}

func (u User) String() string {
    return fmt.Sprintf("User<%d %s %v>", u.Id.Hex(), u.Name, u.Emails)
}

func createSchema(db *pg.DB) error {
    queries := []string{
        `CREATE TABLE users (id bit(96), name text, emails jsonb)`,
    }
    for _, q := range queries {
        _, err := db.Exec(q)
        if err != nil {
            return err
        }
    }
    return nil
}

func main() {
    db := pg.Connect(&pg.Options{
        User:     "postgres",
        Password: "xxx",
    })

    err := createSchema(db)
    if err != nil {
        panic(err)
    }

    var id = bson.NewObjectId()
    fmt.Println(id, id.Hex())

    user1 := &User{
        Id:     id,
        Name:   "admin",
        Emails: []string{"admin1@admin", "admin2@admin"},
    }
    err = db.Create(user1)
    if err != nil {
        panic(err)
    }
}

I got panic: ERROR #22021 invalid byte sequence for encoding "UTF8": 0xf9:

from pg.

vmihailenco avatar vmihailenco commented on July 22, 2024

Indeed... I need some time to fix it.

BTW why do you use bit(96)? What value do you expect?

from pg.

xy02 avatar xy02 commented on July 22, 2024

ObjectId is 12bytes == 96bits. Using bit(or byte) is better than character because it need character(24) to save 12 bytes hex.
BTW does your pg support UUID? And I saw that sql.Scanner and sql/driver.Valuer interfaces in the Supports. What's it mean? I am just learning Go and Postgresql.

from pg.

vmihailenco avatar vmihailenco commented on July 22, 2024

Yes, UUID is supported:

package main

import (
    "fmt"

    "github.com/m4rw3r/uuid"
    "gopkg.in/pg.v4"
)

type User struct {
    Id     uuid.UUID
    Name   string
    Emails []string
}

func (u User) String() string {
    return fmt.Sprintf("User<%s %s %v>", u.Id, u.Name, u.Emails)
}

func createSchema(db *pg.DB) error {
    queries := []string{
        `CREATE EXTENSION IF NOT EXISTS "uuid-ossp"`,
        `DROP TABLE users`,
        `CREATE TABLE users (id uuid, name text, emails jsonb)`,
    }
    for _, q := range queries {
        _, err := db.Exec(q)
        if err != nil {
            return err
        }
    }
    return nil
}

func main() {
    db := pg.Connect(&pg.Options{
        User:     "postgres",
        Password: "",
    })

    err := createSchema(db)
    if err != nil {
        panic(err)
    }

    id, err := uuid.V4()
    if err != nil {
        panic(err)
    }

    user1 := &User{
        Id:     id,
        Name:   "admin",
        Emails: []string{"admin1@admin", "admin2@admin"},
    }
    err = db.Create(user1)
    if err != nil {
        panic(err)
    }
    fmt.Println(user1)
}

And I saw that sql.Scanner and sql/driver.Valuer interfaces in the Supports. What's it mean?

There are special interfaces in database/sql that allow you to write custom types: https://golang.org/pkg/database/sql/#Scanner and https://golang.org/pkg/database/sql/driver/#Valuer. And types UUID implements those interfaces https://github.com/m4rw3r/uuid/blob/master/sql.go#L22-L39

from pg.

xy02 avatar xy02 commented on July 22, 2024

Thank you. So if I declare a custom type like this:

type MyObjectId struct {
    V bson.ObjectId
}

func (id MyObjectId) String() string {
    return id.V.Hex()
}

func (id *MyObjectId) Scan(val interface{}) error {
    if b, ok := val.([]byte); ok {
        id.V = bson.ObjectId(b)
        return nil
    }
    return errors.New("MyObjectId Scan(): invalid data")
}

func (id MyObjectId) Value() (driver.Value, error) {
    b := []byte(id.V)
    return b, nil
}

and

type User struct {
    Id     MyObjectId
    Name   string
    Emails []string
}

Can this work?
I tried it and found out the value of id can not be wrote into db.

from pg.

vmihailenco avatar vmihailenco commented on July 22, 2024

Yes, it should work, but b := []byte(id.V) in Value() returns bytes representation, but you need Hex representation (if you use char(24)) or write some some function that converts bson.ObjectId to bits 01010 etc.

from pg.

xy02 avatar xy02 commented on July 22, 2024

Thanks

from pg.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.