Skip to content

Commit

Permalink
fix(dialect): 正确处理字符串包含单引号的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed May 4, 2024
1 parent c805e35 commit b8d1018
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 3 deletions.
6 changes: 6 additions & 0 deletions dialect/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,16 @@ package dialect

import (
"os/exec"
"strings"

"github.com/issue9/sliceutil"
)

var (
quoteApostrophe = strings.NewReplacer("'", "''") // 标准 SQL 用法
escapeApostrophe = strings.NewReplacer("'", "\\'") // mysql 用法
)

type base struct {
driverName string
name string
Expand Down
2 changes: 1 addition & 1 deletion dialect/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ func (m *mysql) formatSQL(col *core.Column) (f string, err error) {
}
return "0", nil
case string:
return "'" + vv + "'", nil
return "'" + escapeApostrophe.Replace(vv) + "'", nil
case time.Time: // datetime
return formatTime(col, vv)
case sql.NullTime: // datetime
Expand Down
2 changes: 1 addition & 1 deletion dialect/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ func (p *postgres) formatSQL(col *core.Column) (f string, err error) {

switch vv := v.(type) {
case string:
return "'" + vv + "'", nil
return "'" + quoteApostrophe.Replace(vv) + "'", nil
case time.Time: // timestamp
return formatTime(col, vv)
case sql.NullTime: // timestamp
Expand Down
2 changes: 1 addition & 1 deletion dialect/sqlite3.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ func (s *sqlite3) formatSQL(v any) (f string, err error) {

switch vv := v.(type) {
case string:
return "'" + vv + "'", nil
return "'" + quoteApostrophe.Replace(vv) + "'", nil
case time.Time: // timestamp
return "'" + vv.In(time.UTC).Format(datetimeLayouts[0]) + "'", nil
case sql.NullTime: // timestamp
Expand Down

0 comments on commit b8d1018

Please sign in to comment.