Skip to content

Instantly share code, notes, and snippets.

@abdivasiyev
Last active April 21, 2024 16:15
Show Gist options
  • Save abdivasiyev/c94cfeb370907f2877d25aabbbd72ca4 to your computer and use it in GitHub Desktop.
Save abdivasiyev/c94cfeb370907f2877d25aabbbd72ca4 to your computer and use it in GitHub Desktop.
Repository for dynamic insertion
package repository
import (
"fmt"
"strings"
)
type Row interface {
SetPos(pos int)
Values() []any
Insert() string
}
type Rows interface {
Insert() string
Values() []any
}
type offer struct {
pos int
ID int64
DownPayment string
Term string
}
func (o *offer) SetPos(pos int) {
o.pos = pos
}
func (o *offer) Insert() string {
return fmt.Sprintf(`(
(select id from loans where guid = $%d),
$%d,
$%d
)`,
o.pos+1,
o.pos+2,
o.pos+3,
)
}
func (o *offer) Values() []any {
return []any{
o.ID,
o.DownPayment,
o.Term,
}
}
type offers []offer
func (o offers) Insert() string {
pos := 0
values := make([]string, len(o))
for i, item := range o {
item.SetPos(pos)
values[i] = item.Insert()
pos += len(item.Values())
}
return fmt.Sprintf("insert into loan_offers values %s", strings.Join(values, ","))
}
func (o offers) Values() []any {
values := make([]any, 0)
for _, item := range o {
values = append(values, item.Values()...)
}
return values
}
func (r *repository) DoSomething(offers Rows) error {
return r.db.Exec(offers.Insert(), offers.Values()...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment