microsoft / go

The Microsoft build of the Go toolset
BSD 3-Clause "New" or "Revised" License
258 stars 22 forks source link

[BEST PRACTICE] To use with unique identifier #1143

Open brutalzinn opened 5 months ago

brutalzinn commented 5 months ago

Hello, guys. Thanks for this project be public. I have a question about best case to uses with mssql.uniqueidentifier.
This is a small example of my struct and crud operations. I use bun to connect to database


type SomeStruct struct {
    ID         int                    `bun:"id"`
    ExternalId mssql.UniqueIdentifier `bun:"externalid"`
    IdPost     int                    `bun:"id_post"`
    IdAvatar   int                    `bun:"id_avatar"`
}

func (someStruct *SomeStruct) MarshalJSON() ([]byte, error) {
    type Alias SomeStruct
    return json.Marshal(&struct {
        ID string `json:"id"`
        *Alias
    }{
        ID:    someStruct.ExternalId.String(),
        Alias: (*Alias)(someStruct),
    })
}

I need use externalId as string everywhere at my project. And i need to cast mssql uniqueidentifier to string like i do at MarshalJson func. Is there a best practice to handle this without uses conversion everytime? I am thinking about change the unique identifier column to string. But i will lost much funcionalities of unique identifier be managed by sql server.

dagood commented 5 months ago

Hi @brutalzinn, happy to share our work. 🙂

For info about an established best practice with the go-mssqldb module, it might be better to ask at https://github.com/microsoft/go-mssqldb, or maybe even https://groups.google.com/g/golang-nuts or another broad resource listed at https://go.dev/help. The microsoft/go repository in particular is a fork of the Go compiler itself, so we might not know if there's a best practice already agreed upon by the community.

That said, I noticed that https://pkg.go.dev/github.com/microsoft/go-mssqldb@v1.6.0#UniqueIdentifier implements json.Marshaler and json.Unmarshaler, so the module probably expects you to use those rather than converting it to a string yourself: https://go.dev/play/p/49AXUtn0BZb