Last active
April 21, 2024 16:15
-
-
Save abdivasiyev/c94cfeb370907f2877d25aabbbd72ca4 to your computer and use it in GitHub Desktop.
Repository for dynamic insertion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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