Skip to content

Commit af1b822

Browse files
committed
Fix QuoteTo
1 parent 397ec6f commit af1b822

File tree

1 file changed

+42
-11
lines changed

1 file changed

+42
-11
lines changed

sqlite.go

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"context"
55
"database/sql"
66
"strconv"
7-
"strings"
87

98
"gorm.io/gorm/callbacks"
109

@@ -143,19 +142,51 @@ func (dialector Dialector) BindVarTo(writer clause.Writer, stmt *gorm.Statement,
143142
}
144143

145144
func (dialector Dialector) QuoteTo(writer clause.Writer, str string) {
146-
writer.WriteByte('`')
147-
if strings.Contains(str, ".") {
148-
for idx, str := range strings.Split(str, ".") {
149-
if idx > 0 {
150-
writer.WriteString(".`")
145+
var (
146+
underQuoted, selfQuoted bool
147+
continuousBacktick int8
148+
shiftDelimiter int8
149+
)
150+
151+
for _, v := range []byte(str) {
152+
switch v {
153+
case '`':
154+
continuousBacktick++
155+
if continuousBacktick == 2 {
156+
writer.WriteString("``")
157+
continuousBacktick = 0
158+
}
159+
case '.':
160+
if continuousBacktick > 0 || !selfQuoted {
161+
shiftDelimiter = 0
162+
underQuoted = false
163+
continuousBacktick = 0
164+
writer.WriteString("`")
165+
}
166+
writer.WriteByte(v)
167+
continue
168+
default:
169+
if shiftDelimiter-continuousBacktick <= 0 && !underQuoted {
170+
writer.WriteString("`")
171+
underQuoted = true
172+
if selfQuoted = continuousBacktick > 0; selfQuoted {
173+
continuousBacktick -= 1
174+
}
175+
}
176+
177+
for ; continuousBacktick > 0; continuousBacktick -= 1 {
178+
writer.WriteString("``")
151179
}
152-
writer.WriteString(str)
153-
writer.WriteByte('`')
180+
181+
writer.WriteByte(v)
154182
}
155-
} else {
156-
writer.WriteString(str)
157-
writer.WriteByte('`')
183+
shiftDelimiter++
184+
}
185+
186+
if continuousBacktick > 0 && !selfQuoted {
187+
writer.WriteString("``")
158188
}
189+
writer.WriteString("`")
159190
}
160191

161192
func (dialector Dialector) Explain(sql string, vars ...interface{}) string {

0 commit comments

Comments
 (0)