Orm library bun creates for select a bun.SelectQuery struct which is just specific to select. For update it creates a similar one. Is it possible to create a general query struct pg.Query and define the operation (select, update) later like in go-pg. It seems to me there's no general struct but perhaps there's a workaround to not re-write general query twice.
Simple select written in bun: (https://bun.uptrace.dev/guide/query-select.html#api)
book := new(Book)
err := db.NewSelect().Model(book).Where("id = ?", 123).Scan(ctx)
How to re-write this working example from go-pg to bun without writing general sql logic twice:
package main
import (
"fmt"
"github.com/go-pg/pg/v10"
)
type User struct {
ID int64
Name string
}
func herr(e error) { // handle error func
if e != nil {
panic(e)
}
}
func main() {
db := pg.Connect(&pg.Options{
User: "postgres",
Database: "play",
})
var err error
var name string
query := db.Model(&User{}).
Where("TRUE = TRUE") // some general sql logic
caseLogic := false // comes from some business logic
if caseLogic { // two different sql logics using same base query
err = query.Column("name").Where("id = 1").Select(&name)
herr(err)
fmt.Println("name 1:", name)
} else {
_, err = query.Set("name = 'newname'").Where("id = 2").Returning("name").Update(&name)
herr(err)
fmt.Println("name 2:", name)
}
}
P.S Apparently I didn't find the bun tag for the library on Stackoverflow.
Try: