Skip to content

Commit 350be30

Browse files
committed
feat(db): formatting args for sql queries
1 parent 6afca91 commit 350be30

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

db/sql/SqlDb.go

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"regexp"
1010
"strconv"
1111
"strings"
12+
"time"
1213

1314
"github.com/Masterminds/squirrel"
1415
"github.com/go-gorp/gorp/v3"
@@ -134,24 +135,38 @@ func (d *SqlDbConnection) PrepareQuery(query string) string {
134135
return d.prepareQueryWithDialect(query, d.sql.Dialect)
135136
}
136137

138+
func formatArgs(args []any) (formattedArgs []any) {
139+
for _, arg := range args {
140+
switch typedArg := arg.(type) {
141+
case time.Time:
142+
formattedArgs = append(formattedArgs, typedArg.Format("2006-01-02 15:04:05.0000000"))
143+
default:
144+
formattedArgs = append(formattedArgs, arg)
145+
}
146+
}
147+
return
148+
}
149+
137150
func (d *SqlDbConnection) Insert(primaryKeyColumnName string, query string, args ...any) (int, error) {
138151
var insertId int64
139152

153+
formattedArgs := formatArgs(args)
154+
140155
switch d.sql.Dialect.(type) {
141156
case gorp.PostgresDialect:
142157
var err error
143158
if primaryKeyColumnName != "" {
144159
query += " returning " + primaryKeyColumnName
145-
err = d.sql.QueryRow(d.PrepareQuery(query), args...).Scan(&insertId)
160+
err = d.sql.QueryRow(d.PrepareQuery(query), formattedArgs...).Scan(&insertId)
146161
} else {
147-
_, err = d.sql.Exec(d.PrepareQuery(query), args...)
162+
_, err = d.sql.Exec(d.PrepareQuery(query), formattedArgs...)
148163
}
149164

150165
if err != nil {
151166
return 0, err
152167
}
153168
default:
154-
res, err := d.sql.Exec(d.PrepareQuery(query), args...)
169+
res, err := d.sql.Exec(d.PrepareQuery(query), formattedArgs...)
155170
if err != nil {
156171
return 0, err
157172
}
@@ -364,8 +379,7 @@ func (d *SqlDb) insert(primaryKeyColumnName string, query string, args ...any) (
364379
}
365380

366381
func (d *SqlDb) exec(query string, args ...any) (sql.Result, error) {
367-
q := d.PrepareQuery(query)
368-
return d.Sql().Exec(q, args...)
382+
return d.connection.Exec(query, args...)
369383
}
370384

371385
func (d *SqlDb) execTx(tx *gorp.Transaction, query string, args ...any) (sql.Result, error) {
@@ -384,8 +398,7 @@ func (d *SqlDb) selectOne(holder any, query string, args ...any) error {
384398
}
385399

386400
func (d *SqlDb) selectAll(i any, query string, args ...any) ([]any, error) {
387-
q := d.PrepareQuery(query)
388-
return d.Sql().Select(i, q, args...)
401+
return d.connection.SelectAll(i, query, args...)
389402
}
390403

391404
func connect() (*sql.DB, error) {

0 commit comments

Comments
 (0)