Skip to content
This repository was archived by the owner on Sep 7, 2021. It is now read-only.
This repository is currently being migrated. It's locked while the migration is in progress.

Commit 18b3248

Browse files
BetaCat0lunny
authored andcommitted
remove QuoteStr() usage (#1360)
1 parent 674c908 commit 18b3248

File tree

8 files changed

+105
-63
lines changed

8 files changed

+105
-63
lines changed

engine.go

Lines changed: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ func (engine *Engine) SupportInsertMany() bool {
177177

178178
// QuoteStr Engine's database use which character as quote.
179179
// mysql, sqlite use ` and postgres use "
180+
// Deprecated, use Quote() instead
180181
func (engine *Engine) QuoteStr() string {
181182
return engine.dialect.QuoteStr()
182183
}
@@ -196,13 +197,10 @@ func (engine *Engine) Quote(value string) string {
196197
return value
197198
}
198199

199-
if string(value[0]) == engine.dialect.QuoteStr() || value[0] == '`' {
200-
return value
201-
}
202-
203-
value = strings.Replace(value, ".", engine.dialect.QuoteStr()+"."+engine.dialect.QuoteStr(), -1)
200+
buf := builder.StringBuilder{}
201+
engine.QuoteTo(&buf, value)
204202

205-
return engine.dialect.QuoteStr() + value + engine.dialect.QuoteStr()
203+
return buf.String()
206204
}
207205

208206
// QuoteTo quotes string and writes into the buffer
@@ -216,20 +214,30 @@ func (engine *Engine) QuoteTo(buf *builder.StringBuilder, value string) {
216214
return
217215
}
218216

219-
if string(value[0]) == engine.dialect.QuoteStr() || value[0] == '`' {
220-
buf.WriteString(value)
217+
quotePair := engine.dialect.Quote("")
218+
219+
if value[0] == '`' || len(quotePair) < 2 || value[0] == quotePair[0] { // no quote
220+
_, _ = buf.WriteString(value)
221221
return
222+
} else {
223+
prefix, suffix := quotePair[0], quotePair[1]
224+
225+
_ = buf.WriteByte(prefix)
226+
for i := 0; i < len(value); i++ {
227+
if value[i] == '.' {
228+
_ = buf.WriteByte(suffix)
229+
_ = buf.WriteByte('.')
230+
_ = buf.WriteByte(prefix)
231+
} else {
232+
_ = buf.WriteByte(value[i])
233+
}
234+
}
235+
_ = buf.WriteByte(suffix)
222236
}
223-
224-
value = strings.Replace(value, ".", engine.dialect.QuoteStr()+"."+engine.dialect.QuoteStr(), -1)
225-
226-
buf.WriteString(engine.dialect.QuoteStr())
227-
buf.WriteString(value)
228-
buf.WriteString(engine.dialect.QuoteStr())
229237
}
230238

231239
func (engine *Engine) quote(sql string) string {
232-
return engine.dialect.QuoteStr() + sql + engine.dialect.QuoteStr()
240+
return engine.dialect.Quote(sql)
233241
}
234242

235243
// SqlType will be deprecated, please use SQLType instead
@@ -1581,7 +1589,7 @@ func (engine *Engine) formatColTime(col *core.Column, t time.Time) (v interface{
15811589
func (engine *Engine) formatTime(sqlTypeName string, t time.Time) (v interface{}) {
15821590
switch sqlTypeName {
15831591
case core.Time:
1584-
s := t.Format("2006-01-02 15:04:05") //time.RFC3339
1592+
s := t.Format("2006-01-02 15:04:05") // time.RFC3339
15851593
v = s[11:19]
15861594
case core.Date:
15871595
v = t.Format("2006-01-02")

helpers.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ func rValue(bean interface{}) reflect.Value {
281281

282282
func rType(bean interface{}) reflect.Type {
283283
sliceValue := reflect.Indirect(reflect.ValueOf(bean))
284-
//return reflect.TypeOf(sliceValue.Interface())
284+
// return reflect.TypeOf(sliceValue.Interface())
285285
return sliceValue.Type()
286286
}
287287

@@ -309,3 +309,24 @@ func sliceEq(left, right []string) bool {
309309
func indexName(tableName, idxName string) string {
310310
return fmt.Sprintf("IDX_%v_%v", tableName, idxName)
311311
}
312+
313+
func eraseAny(value string, strToErase ...string) string {
314+
if len(strToErase) == 0 {
315+
return value
316+
}
317+
var replaceSeq []string
318+
for _, s := range strToErase {
319+
replaceSeq = append(replaceSeq, s, "")
320+
}
321+
322+
replacer := strings.NewReplacer(replaceSeq...)
323+
324+
return replacer.Replace(value)
325+
}
326+
327+
func quoteColumns(cols []string, quoteFunc func(string) string, sep string) string {
328+
for i := range cols {
329+
cols[i] = quoteFunc(cols[i])
330+
}
331+
return strings.Join(cols, sep+" ")
332+
}

helpers_test.go

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,11 @@
44

55
package xorm
66

7-
import "testing"
7+
import (
8+
"testing"
9+
10+
"github.com/stretchr/testify/assert"
11+
)
812

913
func TestSplitTag(t *testing.T) {
1014
var cases = []struct {
@@ -24,3 +28,19 @@ func TestSplitTag(t *testing.T) {
2428
}
2529
}
2630
}
31+
32+
func TestEraseAny(t *testing.T) {
33+
raw := "SELECT * FROM `table`.[table_name]"
34+
assert.EqualValues(t, raw, eraseAny(raw))
35+
assert.EqualValues(t, "SELECT * FROM table.[table_name]", eraseAny(raw, "`"))
36+
assert.EqualValues(t, "SELECT * FROM table.table_name", eraseAny(raw, "`", "[", "]"))
37+
}
38+
39+
func TestQuoteColumns(t *testing.T) {
40+
cols := []string{"f1", "f2", "f3"}
41+
quoteFunc := func(value string) string {
42+
return "[" + value + "]"
43+
}
44+
45+
assert.EqualValues(t, "[f1], [f2], [f3]", quoteColumns(cols, quoteFunc, ","))
46+
}

session_insert.go

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -242,23 +242,17 @@ func (session *Session) innerInsertMulti(rowsSlicePtr interface{}) (int64, error
242242

243243
var sql string
244244
if session.engine.dialect.DBType() == core.ORACLE {
245-
temp := fmt.Sprintf(") INTO %s (%v%v%v) VALUES (",
245+
temp := fmt.Sprintf(") INTO %s (%v) VALUES (",
246246
session.engine.Quote(tableName),
247-
session.engine.QuoteStr(),
248-
strings.Join(colNames, session.engine.QuoteStr()+", "+session.engine.QuoteStr()),
249-
session.engine.QuoteStr())
250-
sql = fmt.Sprintf("INSERT ALL INTO %s (%v%v%v) VALUES (%v) SELECT 1 FROM DUAL",
247+
quoteColumns(colNames, session.engine.Quote, ","))
248+
sql = fmt.Sprintf("INSERT ALL INTO %s (%v) VALUES (%v) SELECT 1 FROM DUAL",
251249
session.engine.Quote(tableName),
252-
session.engine.QuoteStr(),
253-
strings.Join(colNames, session.engine.QuoteStr()+", "+session.engine.QuoteStr()),
254-
session.engine.QuoteStr(),
250+
quoteColumns(colNames, session.engine.Quote, ","),
255251
strings.Join(colMultiPlaces, temp))
256252
} else {
257-
sql = fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)",
253+
sql = fmt.Sprintf("INSERT INTO %s (%v) VALUES (%v)",
258254
session.engine.Quote(tableName),
259-
session.engine.QuoteStr(),
260-
strings.Join(colNames, session.engine.QuoteStr()+", "+session.engine.QuoteStr()),
261-
session.engine.QuoteStr(),
255+
quoteColumns(colNames, session.engine.Quote, ","),
262256
strings.Join(colMultiPlaces, "),("))
263257
}
264258
res, err := session.exec(sql, args...)
@@ -378,11 +372,9 @@ func (session *Session) innerInsert(bean interface{}) (int64, error) {
378372
output = fmt.Sprintf(" OUTPUT Inserted.%s", table.AutoIncrement)
379373
}
380374
if len(colPlaces) > 0 {
381-
sqlStr = fmt.Sprintf("INSERT INTO %s (%v%v%v)%s VALUES (%v)",
375+
sqlStr = fmt.Sprintf("INSERT INTO %s (%v)%s VALUES (%v)",
382376
session.engine.Quote(tableName),
383-
session.engine.QuoteStr(),
384-
strings.Join(colNames, session.engine.Quote(", ")),
385-
session.engine.QuoteStr(),
377+
quoteColumns(colNames, session.engine.Quote, ","),
386378
output,
387379
colPlaces)
388380
} else {

session_update.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -96,14 +96,15 @@ func (session *Session) cacheUpdate(table *core.Table, tableName, sqlStr string,
9696
return ErrCacheFailed
9797
}
9898
kvs := strings.Split(strings.TrimSpace(sqls[1]), ",")
99+
99100
for idx, kv := range kvs {
100101
sps := strings.SplitN(kv, "=", 2)
101102
sps2 := strings.Split(sps[0], ".")
102103
colName := sps2[len(sps2)-1]
103-
if strings.Contains(colName, "`") {
104-
colName = strings.TrimSpace(strings.Replace(colName, "`", "", -1))
105-
} else if strings.Contains(colName, session.engine.QuoteStr()) {
106-
colName = strings.TrimSpace(strings.Replace(colName, session.engine.QuoteStr(), "", -1))
104+
// treat quote prefix, suffix and '`' as quotes
105+
quotes := append(strings.Split(session.engine.Quote(""), ""), "`")
106+
if strings.ContainsAny(colName, strings.Join(quotes, "")) {
107+
colName = strings.TrimSpace(eraseAny(colName, quotes...))
107108
} else {
108109
session.engine.logger.Debug("[cacheUpdate] cannot find column", tableName, colName)
109110
return ErrCacheFailed
@@ -221,19 +222,19 @@ func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int6
221222
}
222223
}
223224

224-
//for update action to like "column = column + ?"
225+
// for update action to like "column = column + ?"
225226
incColumns := session.statement.getInc()
226227
for _, v := range incColumns {
227228
colNames = append(colNames, session.engine.Quote(v.colName)+" = "+session.engine.Quote(v.colName)+" + ?")
228229
args = append(args, v.arg)
229230
}
230-
//for update action to like "column = column - ?"
231+
// for update action to like "column = column - ?"
231232
decColumns := session.statement.getDec()
232233
for _, v := range decColumns {
233234
colNames = append(colNames, session.engine.Quote(v.colName)+" = "+session.engine.Quote(v.colName)+" - ?")
234235
args = append(args, v.arg)
235236
}
236-
//for update action to like "column = expression"
237+
// for update action to like "column = expression"
237238
exprColumns := session.statement.getExpr()
238239
for _, v := range exprColumns {
239240
colNames = append(colNames, session.engine.Quote(v.colName)+" = "+v.expr)
@@ -382,7 +383,7 @@ func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int6
382383
}
383384

384385
if cacher := session.engine.getCacher(tableName); cacher != nil && session.statement.UseCache {
385-
//session.cacheUpdate(table, tableName, sqlStr, args...)
386+
// session.cacheUpdate(table, tableName, sqlStr, args...)
386387
session.engine.logger.Debug("[cacheUpdate] clear table ", tableName)
387388
cacher.ClearIds(tableName)
388389
cacher.ClearBeans(tableName)

session_update_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@ import (
1111
"testing"
1212
"time"
1313

14-
"xorm.io/core"
1514
"github.com/stretchr/testify/assert"
15+
"xorm.io/core"
1616
)
1717

1818
func TestUpdateMap(t *testing.T) {

statement.go

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ package xorm
66

77
import (
88
"database/sql/driver"
9-
"errors"
109
"fmt"
1110
"reflect"
1211
"strings"
@@ -398,7 +397,7 @@ func (statement *Statement) buildUpdates(bean interface{},
398397
continue
399398
}
400399
} else {
401-
//TODO: how to handler?
400+
// TODO: how to handler?
402401
panic("not supported")
403402
}
404403
} else {
@@ -579,21 +578,9 @@ func (statement *Statement) getExpr() map[string]exprParam {
579578

580579
func (statement *Statement) col2NewColsWithQuote(columns ...string) []string {
581580
newColumns := make([]string, 0)
581+
quotes := append(strings.Split(statement.Engine.Quote(""), ""), "`")
582582
for _, col := range columns {
583-
col = strings.Replace(col, "`", "", -1)
584-
col = strings.Replace(col, statement.Engine.QuoteStr(), "", -1)
585-
ccols := strings.Split(col, ",")
586-
for _, c := range ccols {
587-
fields := strings.Split(strings.TrimSpace(c), ".")
588-
if len(fields) == 1 {
589-
newColumns = append(newColumns, statement.Engine.quote(fields[0]))
590-
} else if len(fields) == 2 {
591-
newColumns = append(newColumns, statement.Engine.quote(fields[0])+"."+
592-
statement.Engine.quote(fields[1]))
593-
} else {
594-
panic(errors.New("unwanted colnames"))
595-
}
596-
}
583+
newColumns = append(newColumns, statement.Engine.Quote(eraseAny(col, quotes...)))
597584
}
598585
return newColumns
599586
}
@@ -764,7 +751,9 @@ func (statement *Statement) Join(joinOP string, tablename interface{}, condition
764751
return statement
765752
}
766753
tbs := strings.Split(tp.TableName(), ".")
767-
var aliasName = strings.Trim(tbs[len(tbs)-1], statement.Engine.QuoteStr())
754+
quotes := append(strings.Split(statement.Engine.Quote(""), ""), "`")
755+
756+
var aliasName = strings.Trim(tbs[len(tbs)-1], strings.Join(quotes, ""))
768757
fmt.Fprintf(&buf, "(%s) %s ON %v", subSQL, aliasName, condition)
769758
statement.joinArgs = append(statement.joinArgs, subQueryArgs...)
770759
case *builder.Builder:
@@ -774,7 +763,9 @@ func (statement *Statement) Join(joinOP string, tablename interface{}, condition
774763
return statement
775764
}
776765
tbs := strings.Split(tp.TableName(), ".")
777-
var aliasName = strings.Trim(tbs[len(tbs)-1], statement.Engine.QuoteStr())
766+
quotes := append(strings.Split(statement.Engine.Quote(""), ""), "`")
767+
768+
var aliasName = strings.Trim(tbs[len(tbs)-1], strings.Join(quotes, ""))
778769
fmt.Fprintf(&buf, "(%s) %s ON %v", subSQL, aliasName, condition)
779770
statement.joinArgs = append(statement.joinArgs, subQueryArgs...)
780771
default:
@@ -1246,7 +1237,7 @@ func (statement *Statement) convertUpdateSQL(sqlStr string) (string, string) {
12461237

12471238
var whereStr = sqls[1]
12481239

1249-
//TODO: for postgres only, if any other database?
1240+
// TODO: for postgres only, if any other database?
12501241
var paraStr string
12511242
if statement.Engine.dialect.DBType() == core.POSTGRES {
12521243
paraStr = "$"

statement_test.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ import (
99
"strings"
1010
"testing"
1111

12-
"xorm.io/core"
1312
"github.com/stretchr/testify/assert"
13+
"xorm.io/core"
1414
)
1515

1616
var colStrTests = []struct {
@@ -237,3 +237,12 @@ func TestUpdateIgnoreOnlyFromDBFields(t *testing.T) {
237237
testEngine.Update(record)
238238
assertGetRecord()
239239
}
240+
241+
func TestCol2NewColsWithQuote(t *testing.T) {
242+
cols := []string{"f1", "f2", "t3.f3"}
243+
244+
statement := createTestStatement()
245+
246+
quotedCols := statement.col2NewColsWithQuote(cols...)
247+
assert.EqualValues(t, []string{statement.Engine.Quote("f1"), statement.Engine.Quote("f2"), statement.Engine.Quote("t3.f3")}, quotedCols)
248+
}

0 commit comments

Comments
 (0)