Skip to content

Instantly share code, notes, and snippets.

@seanhagen
Created February 5, 2022 01:59
Show Gist options
  • Save seanhagen/075dc14356e3e683fe413a4d1351c17b to your computer and use it in GitHub Desktop.
Save seanhagen/075dc14356e3e683fe413a4d1351c17b to your computer and use it in GitHub Desktop.
An example of how you can have both squirrel-crafted queries & hand-crafted queries in the same codebase
type result struct {
ID string `db:"id"`
Name string `db:"name"`
Title sql.NullString `db:"title"`
}
func queryWithSqurrel(ctx context.Context, id string) (*Result, error) {
q := sq.Select("t.id,t.name,t.title").
From("the_table t").
Column("b.other as phone").
LeftJoin("big_table as b on b.player_id=t.id").
OrderBy("ord_col desc").
Where("t.filter_id = ?", id )
var r *result
err := db.Get(ctx, r, q)
return r, err
}
type qs struct {
argID string
query string
}
// ToSql ...
func (qs ) ToSql() (string, []interface{}, error ) {
return qs.query, []interface{}{ qs.argID }, nil
}
func queryWithHandCrafted(ctx context.Context, id string) (*Result, error){
q := qs{
argID: id,
query: `select t.id, t.name, t.title, b.other as phone
from the_table t
left join big_table as b on b.player_id=t.id
where t.filter_id = ?
order by ord_col desc`,
}
var r *result
err := db.Get(ctx, r, q)
return r, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment