Add README and fix some lints #2079

Merged
lunny merged 2 commits from lunny/update_README into master 2021-12-14 01:00:35 +00:00
46 changed files with 278 additions and 208 deletions

24
.golangci.yml Normal file
View File

@ -0,0 +1,24 @@
linters:
enable:
- gosimple
- deadcode
- typecheck
- govet
- errcheck
- staticcheck
- unused
- structcheck
- varcheck
- dupl
#- gocyclo # The cyclomatic complexety of a lot of functions is too high, we should refactor those another time.
- gofmt
- misspell
- gocritic
- bidichk
- ineffassign
enable-all: false
disable-all: true
fast: false
run:
timeout: 3m

View File

@ -98,7 +98,7 @@ help:
@echo " - build creates the entire project"
@echo " - clean delete integration files and build files but not css and js files"
@echo " - fmt format the code"
@echo " - lint run code linter revive"
@echo " - lint run code linter"
@echo " - misspell check if a word is written wrong"
@echo " - test run default unit test"
@echo " - test-cockroach run integration tests for cockroach"
@ -111,7 +111,25 @@ help:
@echo " - vet examines Go source code and reports suspicious constructs"
.PHONY: lint
lint: revive
lint: golangci-lint
.PHONY: golangci-lint
golangci-lint: golangci-lint-check
golangci-lint run --timeout 10m
.PHONY: golangci-lint-check
golangci-lint-check:
$(eval GOLANGCI_LINT_VERSION := $(shell printf "%03d%03d%03d" $(shell golangci-lint --version | grep -Eo '[0-9]+\.[0-9.]+' | tr '.' ' ');))
$(eval MIN_GOLANGCI_LINT_VER_FMT := $(shell printf "%g.%g.%g" $(shell echo $(MIN_GOLANGCI_LINT_VERSION) | grep -o ...)))
@hash golangci-lint > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
echo "Downloading golangci-lint v${MIN_GOLANGCI_LINT_VER_FMT}"; \
export BINARY="golangci-lint"; \
curl -sfL "https://raw.githubusercontent.com/golangci/golangci-lint/v${MIN_GOLANGCI_LINT_VER_FMT}/install.sh" | sh -s -- -b $(GOPATH)/bin v$(MIN_GOLANGCI_LINT_VER_FMT); \
elif [ "$(GOLANGCI_LINT_VERSION)" -lt "$(MIN_GOLANGCI_LINT_VERSION)" ]; then \
echo "Downloading newer version of golangci-lint v${MIN_GOLANGCI_LINT_VER_FMT}"; \
export BINARY="golangci-lint"; \
curl -sfL "https://raw.githubusercontent.com/golangci/golangci-lint/v${MIN_GOLANGCI_LINT_VER_FMT}/install.sh" | sh -s -- -b $(GOPATH)/bin v$(MIN_GOLANGCI_LINT_VER_FMT); \
fi
.PHONY: revive
revive:

View File

@ -141,6 +141,24 @@ affected, err := engine.Insert(&users)
affected, err := engine.Insert(&user1, &users)
// INSERT INTO struct1 () values ()
// INSERT INTO struct2 () values (),(),()
affected, err := engine.Table("user").Insert(map[string]interface{}{
"name": "lunny",
"age": 18,
})
// INSERT INTO user (name, age) values (?,?)
affected, err := engine.Table("user").Insert([]map[string]interface{}{
{
"name": "lunny",
"age": 18,
},
{
"name": "lunny2",
"age": 19,
},
})
// INSERT INTO user (name, age) values (?,?),(?,?)
```
* `Get` query one record from database

View File

@ -138,6 +138,24 @@ affected, err := engine.Insert(&users)
affected, err := engine.Insert(&user1, &users)
// INSERT INTO struct1 () values ()
// INSERT INTO struct2 () values (),(),()
affected, err := engine.Table("user").Insert(map[string]interface{}{
"name": "lunny",
"age": 18,
})
// INSERT INTO user (name, age) values (?,?)
affected, err := engine.Table("user").Insert([]map[string]interface{}{
{
"name": "lunny",
"age": 18,
},
{
"name": "lunny2",
"age": 19,
},
})
// INSERT INTO user (name, age) values (?,?),(?,?)
```
* `Get` 查询单条记录

View File

@ -16,7 +16,7 @@ import (
// Md5 return md5 hash string
func Md5(str string) string {
m := md5.New()
io.WriteString(m, str)
_, _ = io.WriteString(m, str)
return fmt.Sprintf("%x", m.Sum(nil))
}

View File

@ -56,7 +56,7 @@ func (m *LRUCacher) GC() {
var removedNum int
for e := m.idList.Front(); e != nil; {
if removedNum <= CacheGcMaxRemoved &&
time.Now().Sub(e.Value.(*idNode).lastVisit) > m.Expired {
time.Since(e.Value.(*idNode).lastVisit) > m.Expired {
removedNum++
next := e.Next()
node := e.Value.(*idNode)
@ -70,7 +70,7 @@ func (m *LRUCacher) GC() {
removedNum = 0
for e := m.sqlList.Front(); e != nil; {
if removedNum <= CacheGcMaxRemoved &&
time.Now().Sub(e.Value.(*sqlNode).lastVisit) > m.Expired {
time.Since(e.Value.(*sqlNode).lastVisit) > m.Expired {
removedNum++
next := e.Next()
node := e.Value.(*sqlNode)
@ -96,7 +96,7 @@ func (m *LRUCacher) GetIds(tableName, sql string) interface{} {
} else {
lastTime := el.Value.(*sqlNode).lastVisit
// if expired, remove the node and return nil
if time.Now().Sub(lastTime) > m.Expired {
if time.Since(lastTime) > m.Expired {
m.delIds(tableName, sql)
return nil
}
@ -122,7 +122,7 @@ func (m *LRUCacher) GetBean(tableName string, id string) interface{} {
if el, ok := m.idIndex[tableName][id]; ok {
lastTime := el.Value.(*idNode).lastVisit
// if expired, remove the node and return nil
if time.Now().Sub(lastTime) > m.Expired {
if time.Since(lastTime) > m.Expired {
m.delBean(tableName, id)
return nil
}
@ -145,7 +145,7 @@ func (m *LRUCacher) clearIds(tableName string) {
if tis, ok := m.sqlIndex[tableName]; ok {
for sql, v := range tis {
m.sqlList.Remove(v)
m.store.Del(sql)
_ = m.store.Del(sql)
}
}
m.sqlIndex[tableName] = make(map[string]*list.Element)
@ -163,7 +163,7 @@ func (m *LRUCacher) clearBeans(tableName string) {
for id, v := range tis {
m.idList.Remove(v)
tid := genID(tableName, id)
m.store.Del(tid)
_ = m.store.Del(tid)
}
}
m.idIndex[tableName] = make(map[string]*list.Element)
@ -188,7 +188,7 @@ func (m *LRUCacher) PutIds(tableName, sql string, ids interface{}) {
} else {
el.Value.(*sqlNode).lastVisit = time.Now()
}
m.store.Put(sql, ids)
_ = m.store.Put(sql, ids)
if m.sqlList.Len() > m.MaxElementSize {
e := m.sqlList.Front()
node := e.Value.(*sqlNode)
@ -210,7 +210,7 @@ func (m *LRUCacher) PutBean(tableName string, id string, obj interface{}) {
el.Value.(*idNode).lastVisit = time.Now()
}
m.store.Put(genID(tableName, id), obj)
_ = m.store.Put(genID(tableName, id), obj)
if m.idList.Len() > m.MaxElementSize {
e := m.idList.Front()
node := e.Value.(*idNode)
@ -226,7 +226,7 @@ func (m *LRUCacher) delIds(tableName, sql string) {
m.sqlList.Remove(el)
}
}
m.store.Del(sql)
_ = m.store.Del(sql)
}
// DelIds deletes ids
@ -243,7 +243,7 @@ func (m *LRUCacher) delBean(tableName string, id string) {
m.idList.Remove(el)
m.clearIds(tableName)
}
m.store.Del(tid)
_ = m.store.Del(tid)
}
// DelBean deletes beans in some table
@ -265,10 +265,6 @@ type sqlNode struct {
lastVisit time.Time
}
func genSQLKey(sql string, args interface{}) string {
return fmt.Sprintf("%s-%v", sql, args)
}
func genID(prefix string, id string) string {
return fmt.Sprintf("%s-%s", prefix, id)
}

View File

@ -36,7 +36,7 @@ func (c *ContextHook) End(ctx context.Context, result sql.Result, err error) {
c.Ctx = ctx
c.Result = result
c.Err = err
c.ExecuteTime = time.Now().Sub(c.start)
c.ExecuteTime = time.Since(c.start)
}
// Hook represents a hook behaviour

View File

@ -136,7 +136,7 @@ func (db *DB) reflectNew(typ reflect.Type) reflect.Value {
cs = &cacheStruct{reflect.MakeSlice(reflect.SliceOf(typ), DefaultCacheSize, DefaultCacheSize), 0}
db.reflectCache[typ] = cs
} else {
cs.idx = cs.idx + 1
cs.idx++
}
return cs.value.Index(cs.idx).Addr()
}

View File

@ -245,13 +245,13 @@ func BenchmarkSliceInterfaceQuery(b *testing.B) {
b.Error(err)
}
b.Log(slice)
switch slice[1].(type) {
switch st := slice[1].(type) {
case *string:
if *slice[1].(*string) != "xlw" {
if *st != "xlw" {
b.Error(errors.New("name should be xlw"))
}
case []byte:
if string(slice[1].([]byte)) != "xlw" {
if string(st) != "xlw" {
b.Error(errors.New("name should be xlw"))
}
}
@ -399,14 +399,14 @@ func BenchmarkMapInterfaceQuery(b *testing.B) {
if err != nil {
b.Error(err)
}
switch m["name"].(type) {
switch t := m["name"].(type) {
case string:
if m["name"].(string) != "xlw" {
if t != "xlw" {
b.Log(m)
b.Error(errors.New("name should be xlw"))
}
case []byte:
if string(m["name"].([]byte)) != "xlw" {
if string(t) != "xlw" {
b.Log(m)
b.Error(errors.New("name should be xlw"))
}

View File

@ -62,7 +62,7 @@ func (rs *Rows) ScanStructByIndex(dest ...interface{}) error {
for _, vvv := range vvvs {
for j := 0; j < vvv.NumField(); j++ {
newDest[i] = vvv.Field(j).Addr().Interface()
i = i + 1
i++
}
}

View File

@ -670,9 +670,15 @@ func (db *dameng) CreateTableSQL(ctx context.Context, queryer core.Queryer, tabl
quoter := db.Quoter()
var b strings.Builder
b.WriteString("CREATE TABLE ")
quoter.QuoteTo(&b, tableName)
b.WriteString(" (")
if _, err := b.WriteString("CREATE TABLE "); err != nil {
return "", false, err
}
if err := quoter.QuoteTo(&b, tableName); err != nil {
return "", false, err
}
if _, err := b.WriteString(" ("); err != nil {
return "", false, err
}
pkList := table.PrimaryKeys
@ -687,21 +693,35 @@ func (db *dameng) CreateTableSQL(ctx context.Context, queryer core.Queryer, tabl
}
s, _ := ColumnString(db, col, false)
b.WriteString(s)
if _, err := b.WriteString(s); err != nil {
return "", false, err
}
if i != len(table.ColumnsSeq())-1 {
b.WriteString(", ")
if _, err := b.WriteString(", "); err != nil {
return "", false, err
}
}
}
if len(pkList) > 0 {
if len(table.ColumnsSeq()) > 0 {
b.WriteString(", ")
if _, err := b.WriteString(", "); err != nil {
return "", false, err
}
b.WriteString(fmt.Sprintf("CONSTRAINT PK_%s PRIMARY KEY (", tableName))
quoter.JoinWrite(&b, pkList, ",")
b.WriteString(")")
}
b.WriteString(")")
if _, err := b.WriteString(fmt.Sprintf("CONSTRAINT PK_%s PRIMARY KEY (", tableName)); err != nil {
return "", false, err
}
if err := quoter.JoinWrite(&b, pkList, ","); err != nil {
return "", false, err
}
if _, err := b.WriteString(")"); err != nil {
return "", false, err
}
}
if _, err := b.WriteString(")"); err != nil {
return "", false, err
}
return b.String(), false, nil
}

View File

@ -38,11 +38,13 @@ func (uri *URI) SetSchema(schema string) {
}
}
// enumerates all autoincr mode
const (
IncrAutoincrMode = iota
SequenceAutoincrMode
)
// DialectFeatures represents a dialect parameters
type DialectFeatures struct {
AutoincrMode int // 0 autoincrement column, 1 sequence
}
@ -126,7 +128,9 @@ func (db *Base) CreateTableSQL(ctx context.Context, queryer core.Queryer, table
quoter := db.dialect.Quoter()
var b strings.Builder
b.WriteString("CREATE TABLE IF NOT EXISTS ")
quoter.QuoteTo(&b, tableName)
if err := quoter.QuoteTo(&b, tableName); err != nil {
return "", false, err
}
b.WriteString(" (")
for i, colName := range table.ColumnsSeq() {

View File

@ -6,7 +6,6 @@ package dialects
import (
"context"
"crypto/tls"
"database/sql"
"errors"
"fmt"
@ -172,15 +171,6 @@ var (
type mysql struct {
Base
net string
addr string
params map[string]string
loc *time.Location
timeout time.Duration
tls *tls.Config
allowAllFiles bool
allowOldPasswords bool
clientFoundRows bool
rowFormat string
}
@ -497,15 +487,15 @@ func (db *mysql) GetColumns(queryer core.Queryer, ctx context.Context, tableName
if _, ok := schemas.SqlTypes[colType]; ok {
col.SQLType = schemas.SQLType{Name: colType, DefaultLength: len1, DefaultLength2: len2}
} else {
return nil, nil, fmt.Errorf("Unknown colType %v", colType)
return nil, nil, fmt.Errorf("unknown colType %v", colType)
}
if colKey == "PRI" {
col.IsPrimaryKey = true
}
if colKey == "UNI" {
// if colKey == "UNI" {
// col.is
}
// }
if extra == "auto_increment" {
col.IsAutoIncrement = true
@ -785,7 +775,7 @@ func (p *mymysqlDriver) Parse(driverName, dataSourceName string) (*URI, error) {
// Parse protocol part of URI
p := strings.SplitN(pd[0], ":", 2)
if len(p) != 2 {
return nil, errors.New("Wrong protocol part of URI")
return nil, errors.New("wrong protocol part of URI")
}
uri.Proto = p[0]
options := strings.Split(p[1], ",")
@ -808,7 +798,7 @@ func (p *mymysqlDriver) Parse(driverName, dataSourceName string) (*URI, error) {
}
uri.Timeout = to
default:
return nil, errors.New("Unknown option: " + k)
return nil, errors.New("unknown option: " + k)
}
}
// Remove protocol part

View File

@ -1206,11 +1206,9 @@ WHERE n.nspname= s.table_schema AND c.relkind = 'r'::char AND c.relname = $1%s A
col.Default = "'" + col.Default + "'"
}
} else if col.SQLType.IsTime() {
if strings.HasSuffix(col.Default, "::timestamp without time zone") {
col.Default = strings.TrimSuffix(col.Default, "::timestamp without time zone")
}
}
}
cols[col.Name] = col
colSeq = append(colSeq, col.Name)
}
@ -1269,7 +1267,7 @@ func (db *postgres) GetIndexes(queryer core.Queryer, ctx context.Context, tableN
s := "SELECT indexname, indexdef FROM pg_indexes WHERE tablename=$1"
if len(db.getSchema()) != 0 {
args = append(args, db.getSchema())
s = s + " AND schemaname=$2"
s += " AND schemaname=$2"
}
rows, err := queryer.QueryContext(ctx, s, args...)
@ -1337,13 +1335,13 @@ func (db *postgres) CreateTableSQL(ctx context.Context, queryer core.Queryer, ta
return "", ok, err
}
commentSql := "; "
commentSQL := "; "
if table.Comment != "" {
// support schema.table -> "schema"."table"
commentSql += fmt.Sprintf("COMMENT ON TABLE %s IS '%s'", quoter.Quote(tableName), table.Comment)
commentSQL += fmt.Sprintf("COMMENT ON TABLE %s IS '%s'", quoter.Quote(tableName), table.Comment)
}
return createTableSQL + commentSql, true, nil
return createTableSQL + commentSQL, true, nil
}
func (db *postgres) Filters() []Filter {

View File

@ -17,8 +17,7 @@ import (
func TableNameWithSchema(dialect Dialect, tableName string) string {
// Add schema name as prefix of table name.
// Only for postgres database.
if dialect.URI().Schema != "" &&
strings.Index(tableName, ".") == -1 {
if dialect.URI().Schema != "" && !strings.Contains(tableName, ".") {
return fmt.Sprintf("%s.%s", dialect.URI().Schema, tableName)
}
return tableName
@ -27,20 +26,18 @@ func TableNameWithSchema(dialect Dialect, tableName string) string {
// TableNameNoSchema returns table name with given tableName
func TableNameNoSchema(dialect Dialect, mapper names.Mapper, tableName interface{}) string {
quote := dialect.Quoter().Quote
switch tableName.(type) {
switch tt := tableName.(type) {
case []string:
t := tableName.([]string)
if len(t) > 1 {
return fmt.Sprintf("%v AS %v", quote(t[0]), quote(t[1]))
} else if len(t) == 1 {
return quote(t[0])
if len(tt) > 1 {
return fmt.Sprintf("%v AS %v", quote(tt[0]), quote(tt[1]))
} else if len(tt) == 1 {
return quote(tt[0])
}
case []interface{}:
t := tableName.([]interface{})
l := len(t)
l := len(tt)
var table string
if l > 0 {
f := t[0]
f := tt[0]
switch f.(type) {
case string:
table = f.(string)
@ -57,7 +54,7 @@ func TableNameNoSchema(dialect Dialect, mapper names.Mapper, tableName interface
}
}
if l > 1 {
return fmt.Sprintf("%v AS %v", quote(table), quote(fmt.Sprintf("%v", t[1])))
return fmt.Sprintf("%v AS %v", quote(table), quote(fmt.Sprintf("%v", tt[1])))
} else if l == 1 {
return quote(table)
}

View File

@ -467,7 +467,9 @@ func (engine *Engine) dumpTables(ctx context.Context, tables []*schemas.Table, w
DBName: uri.DBName,
Schema: uri.Schema,
}
dstDialect.Init(&destURI)
if err := dstDialect.Init(&destURI); err != nil {
return err
}
}
cacherMgr := caches.NewManager()
dstTableCache := tags.NewParser("xorm", dstDialect, engine.GetTableMapper(), engine.GetColumnMapper(), cacherMgr)
@ -588,7 +590,7 @@ func (engine *Engine) dumpTables(ctx context.Context, tables []*schemas.Table, w
return err
}
} else if sess.engine.dialect.URI().DBType == schemas.DAMENG && stp.IsTime() && len(s.String) == 25 {
r := strings.Replace(s.String[:19], "T", " ", -1)
r := strings.ReplaceAll(s.String[:19], "T", " ")
if _, err = io.WriteString(w, "'"+r+"'"); err != nil {
return err
}
@ -946,7 +948,7 @@ func (engine *Engine) CreateTables(beans ...interface{}) error {
for _, bean := range beans {
err = session.createTable(bean)
if err != nil {
session.Rollback()
_ = session.Rollback()
return err
}
}
@ -966,7 +968,7 @@ func (engine *Engine) DropTables(beans ...interface{}) error {
for _, bean := range beans {
err = session.dropTable(bean)
if err != nil {
session.Rollback()
_ = session.Rollback()
return err
}
}

View File

@ -58,12 +58,13 @@ func TestAutoTransaction(t *testing.T) {
engine := testEngine.(*xorm.Engine)
// will success
engine.Transaction(func(session *xorm.Session) (interface{}, error) {
_, err := engine.Transaction(func(session *xorm.Session) (interface{}, error) {
_, err := session.Insert(TestTx{Msg: "hi"})
assert.NoError(t, err)
return nil, nil
})
assert.NoError(t, err)
has, err := engine.Exist(&TestTx{Msg: "hi"})
assert.NoError(t, err)
@ -149,13 +150,14 @@ func TestDumpTables(t *testing.T) {
assertSync(t, new(TestDumpTableStruct))
testEngine.Insert([]TestDumpTableStruct{
_, err := testEngine.Insert([]TestDumpTableStruct{
{Name: "1", IsMan: true},
{Name: "2\n"},
{Name: "3;"},
{Name: "4\n;\n''"},
{Name: "5'\n"},
})
assert.NoError(t, err)
fp := fmt.Sprintf("%v-table.sql", testEngine.Dialect().URI().DBType)
os.Remove(fp)

View File

@ -104,7 +104,7 @@ func (p *ProcessorsStruct) BeforeDelete() {
}
func (p *ProcessorsStruct) BeforeSet(col string, cell xorm.Cell) {
p.BeforeSetFlag = p.BeforeSetFlag + 1
p.BeforeSetFlag++
}
func (p *ProcessorsStruct) AfterInsert() {
@ -120,7 +120,7 @@ func (p *ProcessorsStruct) AfterDelete() {
}
func (p *ProcessorsStruct) AfterSet(col string, cell xorm.Cell) {
p.AfterSetFlag = p.AfterSetFlag + 1
p.AfterSetFlag++
}
func TestProcessors(t *testing.T) {

View File

@ -101,7 +101,7 @@ func callbackLooper(datas interface{}, step int, actionFunc func(interface{}) er
if err = actionFunc(tempInterface); err != nil {
return
}
processedLen = processedLen - step
processedLen -= step
}
return
}

View File

@ -121,7 +121,7 @@ func TestInt16Id(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, 1, len(beans))
beans2 := make(map[int16]Int16Id, 0)
beans2 := make(map[int16]Int16Id)
err = testEngine.Find(&beans2)
assert.NoError(t, err)
assert.EqualValues(t, 1, len(beans2))
@ -154,7 +154,7 @@ func TestInt32Id(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, 1, len(beans))
beans2 := make(map[int32]Int32Id, 0)
beans2 := make(map[int32]Int32Id)
err = testEngine.Find(&beans2)
assert.NoError(t, err)
assert.EqualValues(t, 1, len(beans2))
@ -205,7 +205,7 @@ func TestUintId(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, 3, len(beans))
beans2 := make(map[uint]UintId, 0)
beans2 := make(map[uint]UintId)
err = testEngine.Find(&beans2)
assert.NoError(t, err)
assert.EqualValues(t, 3, len(beans2))
@ -239,7 +239,7 @@ func TestUint16Id(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, 1, len(beans))
beans2 := make(map[uint16]Uint16Id, 0)
beans2 := make(map[uint16]Uint16Id)
err = testEngine.Find(&beans2)
assert.NoError(t, err)
assert.EqualValues(t, 1, len(beans2))
@ -273,7 +273,7 @@ func TestUint32Id(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, 1, len(beans))
beans2 := make(map[uint32]Uint32Id, 0)
beans2 := make(map[uint32]Uint32Id)
err = testEngine.Find(&beans2)
assert.NoError(t, err)
assert.EqualValues(t, 1, len(beans2))
@ -310,7 +310,7 @@ func TestUint64Id(t *testing.T) {
assert.EqualValues(t, 1, len(beans))
assert.EqualValues(t, *bean, beans[0])
beans2 := make(map[uint64]Uint64Id, 0)
beans2 := make(map[uint64]Uint64Id)
err = testEngine.Find(&beans2)
assert.NoError(t, err)
assert.EqualValues(t, 1, len(beans2))
@ -533,7 +533,7 @@ func TestMyIntId(t *testing.T) {
assert.EqualValues(t, 1, len(beans))
assert.EqualValues(t, *bean, beans[0])
beans2 := make(map[ID]MyIntPK, 0)
beans2 := make(map[ID]MyIntPK)
err = testEngine.Find(&beans2)
assert.NoError(t, err)
assert.EqualValues(t, 1, len(beans2))
@ -570,7 +570,7 @@ func TestMyStringId(t *testing.T) {
assert.EqualValues(t, 1, len(beans))
assert.EqualValues(t, *bean, beans[0])
beans2 := make(map[StrID]MyStringPK, 0)
beans2 := make(map[StrID]MyStringPK)
err = testEngine.Find(&beans2)
assert.NoError(t, err)
assert.EqualValues(t, 1, len(beans2))

View File

@ -328,7 +328,7 @@ func TestIsTableEmpty(t *testing.T) {
Created time.Time `xorm:"created"`
ILike int
PageView int
From_url string
From_url string // nolint
Pre_url string `xorm:"unique"` //pre view image's url
Uid int64
}

View File

@ -231,14 +231,12 @@ func TestForUpdate(t *testing.T) {
f := new(ForUpdate)
f.Name = "updated by session1"
session1.Where("`id` = ?", 1)
session1.Update(f)
_, err = session1.Update(f)
assert.NoError(t, err)
// release lock
err = session1.Commit()
if err != nil {
t.Error(err)
return
}
assert.NoError(t, err)
wg.Wait()
}
@ -253,7 +251,7 @@ func TestWithIn(t *testing.T) {
assert.NoError(t, PrepareEngine())
assert.NoError(t, testEngine.Sync(new(temp3)))
testEngine.Insert(&[]temp3{
_, err := testEngine.Insert(&[]temp3{
{
Name: "user1",
},
@ -264,6 +262,7 @@ func TestWithIn(t *testing.T) {
Name: "user1",
},
})
assert.NoError(t, err)
cnt, err := testEngine.In("Id", 1, 2, 3, 4).Update(&temp3{Name: "aa"}, &temp3{Name: "user1"})
assert.NoError(t, err)
@ -318,6 +317,7 @@ func TestUpdate1(t *testing.T) {
_, err := testEngine.Insert(&Userinfo{
Username: "user1",
})
assert.NoError(t, err)
var ori Userinfo
has, err := testEngine.Get(&ori)
@ -925,6 +925,7 @@ func TestDeletedUpdate(t *testing.T) {
var s1 DeletedUpdatedStruct
has, err := testEngine.ID(s.Id).Get(&s1)
assert.NoError(t, err)
assert.EqualValues(t, true, has)
cnt, err = testEngine.ID(s.Id).Delete(&DeletedUpdatedStruct{})
@ -941,6 +942,7 @@ func TestDeletedUpdate(t *testing.T) {
var s2 DeletedUpdatedStruct
has, err = testEngine.ID(s.Id).Get(&s2)
assert.NoError(t, err)
assert.EqualValues(t, true, has)
}

View File

@ -1202,7 +1202,7 @@ func TestTagTime(t *testing.T) {
assert.NoError(t, err)
assert.True(t, has)
assert.EqualValues(t, s.Created.UTC().Format("2006-01-02 15:04:05"),
strings.Replace(strings.Replace(tm, "T", " ", -1), "Z", "", -1))
strings.ReplaceAll(strings.ReplaceAll(tm, "T", " "), "Z", ""))
}
func TestTagAutoIncr(t *testing.T) {
@ -1287,7 +1287,7 @@ func TestVersion1(t *testing.T) {
assert.EqualValues(t, newVer.Ver, 2)
newVer = new(VersionS)
has, err = testEngine.ID(ver.Id).Get(newVer)
_, err = testEngine.ID(ver.Id).Get(newVer)
assert.NoError(t, err)
assert.EqualValues(t, newVer.Ver, 2)
}
@ -1345,7 +1345,7 @@ func TestVersion3(t *testing.T) {
assert.EqualValues(t, newVer.Ver, 2)
newVer = new(VersionUintS)
has, err = testEngine.ID(ver.Id).Get(newVer)
_, err = testEngine.ID(ver.Id).Get(newVer)
assert.NoError(t, err)
assert.EqualValues(t, newVer.Ver, 2)
}

View File

@ -51,7 +51,7 @@ func createEngine(dbType, connStr string) error {
if !*cluster {
switch schemas.DBType(strings.ToLower(dbType)) {
case schemas.MSSQL:
db, err := sql.Open(dbType, strings.Replace(connStr, "xorm_test", "master", -1))
db, err := sql.Open(dbType, strings.ReplaceAll(connStr, "xorm_test", "master"))
if err != nil {
return err
}
@ -61,7 +61,7 @@ func createEngine(dbType, connStr string) error {
db.Close()
*ignoreSelectUpdate = true
case schemas.POSTGRES:
db, err := sql.Open(dbType, strings.Replace(connStr, "xorm_test", "postgres", -1))
db, err := sql.Open(dbType, strings.ReplaceAll(connStr, "xorm_test", "postgres"))
if err != nil {
return err
}
@ -90,7 +90,7 @@ func createEngine(dbType, connStr string) error {
db.Close()
*ignoreSelectUpdate = true
case schemas.MYSQL:
db, err := sql.Open(dbType, strings.Replace(connStr, "xorm_test", "mysql", -1))
db, err := sql.Open(dbType, strings.ReplaceAll(connStr, "xorm_test", "mysql"))
if err != nil {
return err
}

View File

@ -79,7 +79,9 @@ func (statement *Statement) GenSumSQL(bean interface{}, columns ...string) (stri
return statement.GenRawSQL(), statement.RawParams, nil
}
statement.SetRefBean(bean)
if err := statement.SetRefBean(bean); err != nil {
return "", nil, err
}
var sumStrs = make([]string, 0, len(columns))
for _, colName := range columns {
@ -111,7 +113,9 @@ func (statement *Statement) GenGetSQL(bean interface{}) (string, []interface{},
v := rValue(bean)
isStruct = v.Kind() == reflect.Struct
if isStruct {
statement.SetRefBean(bean)
if err := statement.SetRefBean(bean); err != nil {
return "", nil, err
}
}
}
@ -168,7 +172,9 @@ func (statement *Statement) GenCountSQL(beans ...interface{}) (string, []interfa
var condArgs []interface{}
var err error
if len(beans) > 0 {
statement.SetRefBean(beans[0])
if err := statement.SetRefBean(beans[0]); err != nil {
return "", nil, err
}
if err := statement.mergeConds(beans[0]); err != nil {
return "", nil, err
}

View File

@ -473,7 +473,7 @@ func (statement *Statement) Desc(colNames ...string) *Statement {
if i > 0 {
fmt.Fprint(&buf, ", ")
}
statement.dialect.Quoter().QuoteTo(&buf, col)
_ = statement.dialect.Quoter().QuoteTo(&buf, col)
fmt.Fprint(&buf, " DESC")
}
statement.OrderStr = buf.String()
@ -490,7 +490,7 @@ func (statement *Statement) Asc(colNames ...string) *Statement {
if i > 0 {
fmt.Fprint(&buf, ", ")
}
statement.dialect.Quoter().QuoteTo(&buf, col)
_ = statement.dialect.Quoter().QuoteTo(&buf, col)
fmt.Fprint(&buf, " ASC")
}
statement.OrderStr = buf.String()
@ -558,7 +558,7 @@ func (statement *Statement) Join(joinOP string, tablename interface{}, condition
tbName := dialects.FullTableName(statement.dialect, statement.tagParser.GetTableMapper(), tablename, true)
if !utils.IsSubQuery(tbName) {
var buf strings.Builder
statement.dialect.Quoter().QuoteTo(&buf, tbName)
_ = statement.dialect.Quoter().QuoteTo(&buf, tbName)
tbName = buf.String()
} else {
tbName = statement.ReplaceQuote(tbName)
@ -571,15 +571,6 @@ func (statement *Statement) Join(joinOP string, tablename interface{}, condition
return statement
}
// tbNameNoSchema get some table's table name
func (statement *Statement) tbNameNoSchema(table *schemas.Table) string {
if len(statement.AltTableName) > 0 {
return statement.AltTableName
}
return table.Name
}
// GroupBy generate "Group By keys" statement
func (statement *Statement) GroupBy(keys string) *Statement {
statement.GroupByStr = statement.ReplaceQuote(keys)
@ -857,9 +848,6 @@ func (statement *Statement) buildConds2(table *schemas.Table, bean interface{},
fieldValuePtr, err := col.ValueOf(bean)
if err != nil {
if !strings.Contains(err.Error(), "is not valid") {
//engine.logger.Warn(err)
}
continue
} else if fieldValuePtr == nil {
continue

View File

@ -5,6 +5,7 @@
package statements
import (
"os"
"reflect"
"strings"
"testing"
@ -37,6 +38,7 @@ func TestMain(m *testing.M) {
panic("tags parser is nil")
}
m.Run()
os.Exit(0)
}
var colStrTests = []struct {

View File

@ -21,6 +21,7 @@ func SliceEq(left, right []string) bool {
return true
}
// IndexSlice search c in slice s and return the index, return -1 if s don't contain c
func IndexSlice(s []string, c string) int {
for i, ss := range s {
if c == ss {

View File

@ -130,56 +130,56 @@ func NewSimpleLogger3(out io.Writer, prefix string, flag int, l LogLevel) *Simpl
// Error implement ILogger
func (s *SimpleLogger) Error(v ...interface{}) {
if s.level <= LOG_ERR {
s.ERR.Output(2, fmt.Sprintln(v...))
_ = s.ERR.Output(2, fmt.Sprintln(v...))
}
}
// Errorf implement ILogger
func (s *SimpleLogger) Errorf(format string, v ...interface{}) {
if s.level <= LOG_ERR {
s.ERR.Output(2, fmt.Sprintf(format, v...))
_ = s.ERR.Output(2, fmt.Sprintf(format, v...))
}
}
// Debug implement ILogger
func (s *SimpleLogger) Debug(v ...interface{}) {
if s.level <= LOG_DEBUG {
s.DEBUG.Output(2, fmt.Sprintln(v...))
_ = s.DEBUG.Output(2, fmt.Sprintln(v...))
}
}
// Debugf implement ILogger
func (s *SimpleLogger) Debugf(format string, v ...interface{}) {
if s.level <= LOG_DEBUG {
s.DEBUG.Output(2, fmt.Sprintf(format, v...))
_ = s.DEBUG.Output(2, fmt.Sprintf(format, v...))
}
}
// Info implement ILogger
func (s *SimpleLogger) Info(v ...interface{}) {
if s.level <= LOG_INFO {
s.INFO.Output(2, fmt.Sprintln(v...))
_ = s.INFO.Output(2, fmt.Sprintln(v...))
}
}
// Infof implement ILogger
func (s *SimpleLogger) Infof(format string, v ...interface{}) {
if s.level <= LOG_INFO {
s.INFO.Output(2, fmt.Sprintf(format, v...))
_ = s.INFO.Output(2, fmt.Sprintf(format, v...))
}
}
// Warn implement ILogger
func (s *SimpleLogger) Warn(v ...interface{}) {
if s.level <= LOG_WARNING {
s.WARN.Output(2, fmt.Sprintln(v...))
_ = s.WARN.Output(2, fmt.Sprintln(v...))
}
}
// Warnf implement ILogger
func (s *SimpleLogger) Warnf(format string, v ...interface{}) {
if s.level <= LOG_WARNING {
s.WARN.Output(2, fmt.Sprintf(format, v...))
_ = s.WARN.Output(2, fmt.Sprintf(format, v...))
}
}

View File

@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build !windows && !nacl && !plan9
// +build !windows,!nacl,!plan9
package log
@ -26,42 +27,42 @@ func NewSyslogLogger(w *syslog.Writer) *SyslogLogger {
// Debug log content as Debug
func (s *SyslogLogger) Debug(v ...interface{}) {
s.w.Debug(fmt.Sprint(v...))
_ = s.w.Debug(fmt.Sprint(v...))
}
// Debugf log content as Debug and format
func (s *SyslogLogger) Debugf(format string, v ...interface{}) {
s.w.Debug(fmt.Sprintf(format, v...))
_ = s.w.Debug(fmt.Sprintf(format, v...))
}
// Error log content as Error
func (s *SyslogLogger) Error(v ...interface{}) {
s.w.Err(fmt.Sprint(v...))
_ = s.w.Err(fmt.Sprint(v...))
}
// Errorf log content as Errorf and format
func (s *SyslogLogger) Errorf(format string, v ...interface{}) {
s.w.Err(fmt.Sprintf(format, v...))
_ = s.w.Err(fmt.Sprintf(format, v...))
}
// Info log content as Info
func (s *SyslogLogger) Info(v ...interface{}) {
s.w.Info(fmt.Sprint(v...))
_ = s.w.Info(fmt.Sprint(v...))
}
// Infof log content as Infof and format
func (s *SyslogLogger) Infof(format string, v ...interface{}) {
s.w.Info(fmt.Sprintf(format, v...))
_ = s.w.Info(fmt.Sprintf(format, v...))
}
// Warn log content as Warn
func (s *SyslogLogger) Warn(v ...interface{}) {
s.w.Warning(fmt.Sprint(v...))
_ = s.w.Warning(fmt.Sprint(v...))
}
// Warnf log content as Warnf and format
func (s *SyslogLogger) Warnf(format string, v ...interface{}) {
s.w.Warning(fmt.Sprintf(format, v...))
_ = s.w.Warning(fmt.Sprintf(format, v...))
}
// Level shows log level

View File

@ -203,7 +203,7 @@ func (m *Migrate) migrationDidRun(mig *Migration) (bool, error) {
func (m *Migrate) isFirstRun() bool {
row := m.db.DB().QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", m.options.TableName))
var count int
row.Scan(&count)
_ = row.Scan(&count)
return count == 0
}

View File

@ -142,6 +142,6 @@ func TestMissingID(t *testing.T) {
func tableCount(db *xorm.Engine, tableName string) (count int) {
row := db.DB().QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", tableName))
row.Scan(&count)
_ = row.Scan(&count)
return
}

View File

@ -40,7 +40,7 @@ func newRows(session *Session, bean interface{}) (*Rows, error) {
return nil, err
}
if len(session.statement.TableName()) <= 0 {
if len(session.statement.TableName()) == 0 {
return nil, ErrTableNotFound
}

View File

@ -235,6 +235,7 @@ func (engine *Engine) row2mapInterface(rows *core.Rows, types []*sql.ColumnType,
return resultsMap, nil
}
// ScanInterfaceMap scan result from *core.Rows and return a map
func (engine *Engine) ScanInterfaceMap(rows *core.Rows) (map[string]interface{}, error) {
fields, err := rows.Columns()
if err != nil {
@ -248,6 +249,7 @@ func (engine *Engine) ScanInterfaceMap(rows *core.Rows) (map[string]interface{},
return engine.row2mapInterface(rows, types, fields)
}
// ScanInterfaceMaps scan results from *core.Rows and return a slice of map
func (engine *Engine) ScanInterfaceMaps(rows *core.Rows) (resultsSlice []map[string]interface{}, err error) {
fields, err := rows.Columns()
if err != nil {
@ -309,6 +311,7 @@ func (engine *Engine) row2mapStr(rows *core.Rows, types []*sql.ColumnType, field
return result, nil
}
// ScanStringMap scan results from *core.Rows and return a map
func (engine *Engine) ScanStringMap(rows *core.Rows) (map[string]string, error) {
fields, err := rows.Columns()
if err != nil {
@ -321,6 +324,7 @@ func (engine *Engine) ScanStringMap(rows *core.Rows) (map[string]string, error)
return engine.row2mapStr(rows, types, fields)
}
// ScanStringMaps scan results from *core.Rows and return a slice of map
func (engine *Engine) ScanStringMaps(rows *core.Rows) (resultsSlice []map[string]string, err error) {
fields, err := rows.Columns()
if err != nil {
@ -395,6 +399,7 @@ func (engine *Engine) row2sliceStr(rows *core.Rows, types []*sql.ColumnType, fie
return results, nil
}
// ScanStringSlice scan results from *core.Rows and return a slice of one row
func (engine *Engine) ScanStringSlice(rows *core.Rows) ([]string, error) {
fields, err := rows.Columns()
if err != nil {
@ -408,6 +413,7 @@ func (engine *Engine) ScanStringSlice(rows *core.Rows) ([]string, error) {
return engine.row2sliceStr(rows, types, fields)
}
// ScanStringSlices scan results from *core.Rows and return a slice of all rows
func (engine *Engine) ScanStringSlices(rows *core.Rows) (resultsSlice [][]string, err error) {
fields, err := rows.Columns()
if err != nil {

View File

@ -32,7 +32,7 @@ func NewIndex(name string, indexType int) *Index {
func (index *Index) XName(tableName string) string {
if !strings.HasPrefix(index.Name, "UQE_") &&
!strings.HasPrefix(index.Name, "IDX_") {
tableParts := strings.Split(strings.Replace(tableName, `"`, "", -1), ".")
tableParts := strings.Split(strings.ReplaceAll(tableName, `"`, ""), ".")
tableName = tableParts[len(tableParts)-1]
if index.Type == UniqueType {
return fmt.Sprintf("UQE_%v_%v", tableName, index.Name)

View File

@ -37,7 +37,7 @@ func (q Quoter) IsEmpty() bool {
// Quote quote a string
func (q Quoter) Quote(s string) string {
var buf strings.Builder
q.QuoteTo(&buf, s)
_ = q.QuoteTo(&buf, s)
return buf.String()
}
@ -64,7 +64,7 @@ func (q Quoter) Trim(s string) string {
// Join joins a slice with quoters
func (q Quoter) Join(a []string, sep string) string {
var b strings.Builder
q.JoinWrite(&b, a, sep)
_ = q.JoinWrite(&b, a, sep)
return b.String()
}
@ -86,7 +86,9 @@ func (q Quoter) JoinWrite(b *strings.Builder, a []string, sep string) error {
return err
}
}
q.QuoteTo(b, strings.TrimSpace(s))
if err := q.QuoteTo(b, strings.TrimSpace(s)); err != nil {
return err
}
}
return nil
}
@ -121,7 +123,7 @@ func findStart(value string, start int) int {
}
if (value[k] == 'A' || value[k] == 'a') && (value[k+1] == 'S' || value[k+1] == 's') {
k = k + 2
k += 2
}
for j := k; j < len(value); j++ {

View File

@ -45,7 +45,8 @@ func TestAlwaysQuoteTo(t *testing.T) {
for _, v := range kases {
t.Run(v.value, func(t *testing.T) {
buf := &strings.Builder{}
quoter.QuoteTo(buf, v.value)
err := quoter.QuoteTo(buf, v.value)
assert.NoError(t, err)
assert.EqualValues(t, v.expected, buf.String())
})
}
@ -54,10 +55,7 @@ func TestAlwaysQuoteTo(t *testing.T) {
func TestReversedQuoteTo(t *testing.T) {
var (
quoter = Quoter{'[', ']', func(s string) bool {
if s == "mytable" {
return true
}
return false
return s == "mytable"
}}
kases = []struct {
expected string
@ -118,7 +116,8 @@ func TestNoQuoteTo(t *testing.T) {
for _, v := range kases {
t.Run(v.value, func(t *testing.T) {
buf := &strings.Builder{}
quoter.QuoteTo(buf, v.value)
err := quoter.QuoteTo(buf, v.value)
assert.NoError(t, err)
assert.EqualValues(t, v.expected, buf.String())
})
}

View File

@ -704,7 +704,7 @@ func (session *Session) slice2Bean(scanResults []interface{}, fields []string, b
if idx, ok = tempMap[lKey]; !ok {
idx = 0
} else {
idx = idx + 1
idx++
}
tempMap[lKey] = idx

View File

@ -232,7 +232,7 @@ func (session *Session) Delete(beans ...interface{}) (int64, error) {
}
if cacher := session.engine.GetCacher(tableNameNoQuote); cacher != nil && session.statement.UseCache {
session.cacheDelete(table, tableNameNoQuote, deleteSQL, argsForCache...)
_ = session.cacheDelete(table, tableNameNoQuote, deleteSQL, argsForCache...)
}
session.statement.RefTable = table

View File

@ -71,9 +71,13 @@ func (session *Session) FindAndCount(rowsSlicePtr interface{}, condiBean ...inte
}
// session has stored the conditions so we use `unscoped` to avoid duplicated condition.
if sliceElementType.Kind() == reflect.Struct {
return session.Unscoped().Count(reflect.New(sliceElementType).Interface())
}
return session.Unscoped().Count()
}
func (session *Session) find(rowsSlicePtr interface{}, condiBean ...interface{}) error {
defer session.resetStatement()
if session.statement.LastError != nil {
@ -152,7 +156,6 @@ func (session *Session) find(rowsSlicePtr interface{}, condiBean ...interface{})
if err != ErrCacheFailed {
return err
}
err = nil // !nashtsai! reset err to nil for ErrCacheFailed
session.engine.logger.Warnf("Cache Find Failed")
}
}

View File

@ -6,7 +6,6 @@ package xorm
import (
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"math/big"
@ -79,7 +78,7 @@ func (session *Session) get(beans ...interface{}) (bool, error) {
var err error
if session.statement.RawSQL == "" {
if len(session.statement.TableName()) <= 0 {
if len(session.statement.TableName()) == 0 {
return false, ErrTableNotFound
}
session.statement.Limit(1)
@ -130,14 +129,6 @@ func (session *Session) get(beans ...interface{}) (bool, error) {
return true, nil
}
var (
valuerTypePlaceHolder driver.Valuer
valuerType = reflect.TypeOf(&valuerTypePlaceHolder).Elem()
conversionTypePlaceHolder convert.Conversion
conversionType = reflect.TypeOf(&conversionTypePlaceHolder).Elem()
)
func isScannableStruct(bean interface{}, typeLen int) bool {
switch bean.(type) {
case *time.Time:

View File

@ -80,7 +80,7 @@ func (session *Session) insertMultipleStruct(rowsSlicePtr interface{}) (int64, e
}
tableName := session.statement.TableName()
if len(tableName) <= 0 {
if len(tableName) == 0 {
return 0, ErrTableNotFound
}
@ -90,7 +90,6 @@ func (session *Session) insertMultipleStruct(rowsSlicePtr interface{}) (int64, e
colNames []string
colMultiPlaces []string
args []interface{}
cols []*schemas.Column
)
for i := 0; i < size; i++ {
@ -172,7 +171,6 @@ func (session *Session) insertMultipleStruct(rowsSlicePtr interface{}) (int64, e
if i == 0 {
colNames = append(colNames, col.Name)
cols = append(cols, col)
}
colPlaces = append(colPlaces, "?")
}
@ -203,7 +201,7 @@ func (session *Session) insertMultipleStruct(rowsSlicePtr interface{}) (int64, e
return 0, err
}
session.cacheInsert(tableName)
_ = session.cacheInsert(tableName)
lenAfterClosures := len(session.afterClosures)
for i := 0; i < size; i++ {
@ -257,7 +255,7 @@ func (session *Session) insertStruct(bean interface{}) (int64, error) {
if err := session.statement.SetRefBean(bean); err != nil {
return 0, err
}
if len(session.statement.TableName()) <= 0 {
if len(session.statement.TableName()) == 0 {
return 0, ErrTableNotFound
}
@ -360,7 +358,7 @@ func (session *Session) insertStruct(bean interface{}) (int64, error) {
defer handleAfterInsertProcessorFunc(bean)
session.cacheInsert(tableName)
_ = session.cacheInsert(tableName)
if table.Version != "" && session.statement.CheckVersion {
verValue, err := table.VersionColumn().ValueOf(bean)
@ -390,7 +388,7 @@ func (session *Session) insertStruct(bean interface{}) (int64, error) {
defer handleAfterInsertProcessorFunc(bean)
session.cacheInsert(tableName)
_ = session.cacheInsert(tableName)
if table.Version != "" && session.statement.CheckVersion {
verValue, err := table.VersionColumn().ValueOf(bean)
@ -430,6 +428,7 @@ func (session *Session) insertStruct(bean interface{}) (int64, error) {
// InsertOne insert only one struct into database as a record.
// The in parameter bean must a struct or a point to struct. The return
// parameter is inserted and error
// Deprecated: Please use Insert directly
func (session *Session) InsertOne(bean interface{}) (int64, error) {
if session.isAutoClose {
defer session.Close()
@ -537,7 +536,7 @@ func (session *Session) insertMapInterface(m map[string]interface{}) (int64, err
}
tableName := session.statement.TableName()
if len(tableName) <= 0 {
if len(tableName) == 0 {
return 0, ErrTableNotFound
}
@ -559,12 +558,12 @@ func (session *Session) insertMapInterface(m map[string]interface{}) (int64, err
}
func (session *Session) insertMultipleMapInterface(maps []map[string]interface{}) (int64, error) {
if len(maps) <= 0 {
if len(maps) == 0 {
return 0, ErrNoElementsOnSlice
}
tableName := session.statement.TableName()
if len(tableName) <= 0 {
if len(tableName) == 0 {
return 0, ErrTableNotFound
}
@ -595,7 +594,7 @@ func (session *Session) insertMapString(m map[string]string) (int64, error) {
}
tableName := session.statement.TableName()
if len(tableName) <= 0 {
if len(tableName) == 0 {
return 0, ErrTableNotFound
}
@ -618,12 +617,12 @@ func (session *Session) insertMapString(m map[string]string) (int64, error) {
}
func (session *Session) insertMultipleMapString(maps []map[string]string) (int64, error) {
if len(maps) <= 0 {
if len(maps) == 0 {
return 0, ErrNoElementsOnSlice
}
tableName := session.statement.TableName()
if len(tableName) <= 0 {
if len(tableName) == 0 {
return 0, ErrTableNotFound
}
@ -650,7 +649,7 @@ func (session *Session) insertMultipleMapString(maps []map[string]string) (int64
func (session *Session) insertMap(columns []string, args []interface{}) (int64, error) {
tableName := session.statement.TableName()
if len(tableName) <= 0 {
if len(tableName) == 0 {
return 0, ErrTableNotFound
}
@ -677,7 +676,7 @@ func (session *Session) insertMap(columns []string, args []interface{}) (int64,
func (session *Session) insertMultipleMap(columns []string, argss [][]interface{}) (int64, error) {
tableName := session.statement.TableName()
if len(tableName) <= 0 {
if len(tableName) == 0 {
return 0, ErrTableNotFound
}

View File

@ -95,7 +95,7 @@ func (session *Session) bufferIterate(bean interface{}, fun IterFunc) error {
break
}
start = start + slice.Elem().Len()
start += slice.Elem().Len()
if pLimitN != nil && start+bufferSize > *pLimitN {
bufferSize = *pLimitN - start
}

View File

@ -223,24 +223,6 @@ func (session *Session) isTableEmpty(tableName string) (bool, error) {
return total == 0, nil
}
// find if index is exist according cols
func (session *Session) isIndexExist2(tableName string, cols []string, unique bool) (bool, error) {
indexes, err := session.engine.dialect.GetIndexes(session.getQueryer(), session.ctx, tableName)
if err != nil {
return false, err
}
for _, index := range indexes {
if utils.SliceEq(index.Cols, cols) {
if unique {
return index.Type == schemas.UniqueType, nil
}
return index.Type == schemas.IndexType, nil
}
}
return false, nil
}
func (session *Session) addColumn(colName string) error {
col := session.statement.RefTable.GetColumn(colName)
sql := session.engine.dialect.AddColumnSQL(session.statement.TableName(), col)

View File

@ -75,7 +75,7 @@ func (session *Session) Commit() error {
}
cleanUpFunc := func(slices *map[interface{}]*[]func(interface{})) {
if len(*slices) > 0 {
*slices = make(map[interface{}]*[]func(interface{}), 0)
*slices = make(map[interface{}]*[]func(interface{}))
}
}
cleanUpFunc(&session.afterInsertBeans)

View File

@ -22,6 +22,7 @@ var (
ErrNoColumnsTobeUpdated = errors.New("no columns found to be updated")
)
//revive:disable
func (session *Session) cacheUpdate(table *schemas.Table, tableName, sqlStr string, args ...interface{}) error {
if table == nil ||
session.tx != nil {
@ -39,7 +40,7 @@ func (session *Session) cacheUpdate(table *schemas.Table, tableName, sqlStr stri
var nStart int
if len(args) > 0 {
if strings.Index(sqlStr, "?") > -1 {
if strings.Contains(sqlStr, "?") {
nStart = strings.Count(oldhead, "?")
} else {
// only for pq, TODO: if any other databse?
@ -182,7 +183,7 @@ func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int6
return 0, err
}
if len(session.statement.TableName()) <= 0 {
if len(session.statement.TableName()) == 0 {
return 0, ErrTableNotFound
}
@ -342,7 +343,7 @@ func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int6
}
}
if len(colNames) <= 0 {
if len(colNames) == 0 {
return 0, ErrNoColumnsTobeUpdated
}
@ -356,7 +357,7 @@ func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int6
}
if st.OrderStr != "" {
condSQL = condSQL + fmt.Sprintf(" ORDER BY %v", st.OrderStr)
condSQL += fmt.Sprintf(" ORDER BY %v", st.OrderStr)
}
var tableName = session.statement.TableName()
@ -366,7 +367,7 @@ func (session *Session) Update(bean interface{}, condiBean ...interface{}) (int6
limitValue := *st.LimitN
switch session.engine.dialect.URI().DBType {
case schemas.MYSQL:
condSQL = condSQL + fmt.Sprintf(" LIMIT %d", limitValue)
condSQL += fmt.Sprintf(" LIMIT %d", limitValue)
case schemas.SQLITE:
tempCondSQL := condSQL + fmt.Sprintf(" LIMIT %d", limitValue)
cond = cond.And(builder.Expr(fmt.Sprintf("rowid IN (SELECT rowid FROM %v %v)",