Add README and fix some lints #2079

Merged
lunny merged 2 commits from lunny/update_README into master 5 months ago
  1. 24
      .golangci.yml
  2. 22
      Makefile
  3. 18
      README.md
  4. 18
      README_CN.md
  5. 6
      caches/encode.go
  6. 24
      caches/lru.go
  7. 2
      contexts/hook.go
  8. 2
      core/db.go
  9. 14
      core/db_test.go
  10. 2
      core/rows.go
  11. 40
      dialects/dameng.go
  12. 6
      dialects/dialect.go
  13. 24
      dialects/mysql.go
  14. 12
      dialects/postgres.go
  15. 21
      dialects/table_name.go
  16. 10
      engine.go
  17. 6
      integrations/engine_test.go
  18. 4
      integrations/processors_test.go
  19. 2
      integrations/session_insert_test.go
  20. 16
      integrations/session_pk_test.go
  21. 2
      integrations/session_schema_test.go
  22. 14
      integrations/session_update_test.go
  23. 6
      integrations/tags_test.go
  24. 6
      integrations/tests.go
  25. 12
      internal/statements/query.go
  26. 18
      internal/statements/statement.go
  27. 2
      internal/statements/statement_test.go
  28. 1
      internal/utils/slice.go
  29. 16
      log/logger.go
  30. 17
      log/syslogger.go
  31. 2
      migrate/migrate.go
  32. 2
      migrate/migrate_test.go
  33. 2
      rows.go
  34. 6
      scan.go
  35. 2
      schemas/index.go
  36. 10
      schemas/quote.go
  37. 11
      schemas/quote_test.go
  38. 2
      session.go
  39. 2
      session_delete.go
  40. 7
      session_find.go
  41. 11
      session_get.go
  42. 29
      session_insert.go
  43. 2
      session_iterate.go
  44. 18
      session_schema.go
  45. 2
      session_tx.go
  46. 11
      session_update.go

24
.golangci.yml

@ -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

22
Makefile

@ -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:

18
README.md

@ -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

18
README_CN.md

@ -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` 查询单条记录

6
caches/encode.go

@ -16,19 +16,19 @@ 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))
}
// Encode Encode data
func Encode(data interface{}) ([]byte, error) {
//return JsonEncode(data)
// return JsonEncode(data)
return GobEncode(data)
}
// Decode decode data
func Decode(data []byte, to interface{}) error {
//return JsonDecode(data, to)
// return JsonDecode(data, to)
return GobDecode(data, to)
}

24
caches/lru.go

@ -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)
}

2
contexts/hook.go

@ -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

2
core/db.go

@ -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()
}

14
core/db_test.go

@ -96,7 +96,7 @@ func BenchmarkOriQuery(b *testing.B) {
if err != nil {
b.Error(err)
}
//fmt.Println(Id, Name, Title, Age, Alias, NickName)
// fmt.Println(Id, Name, Title, Age, Alias, NickName)
}
rows.Close()
}
@ -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"))
}

2
core/rows.go

@ -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++
}
}

40
dialects/dameng.go

@ -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
}
}
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
}
b.WriteString(fmt.Sprintf("CONSTRAINT PK_%s PRIMARY KEY (", tableName))
quoter.JoinWrite(&b, pkList, ",")
b.WriteString(")")
if _, err := b.WriteString(")"); err != nil {
return "", false, err
}
}
if _, err := b.WriteString(")"); err != nil {
return "", false, err
}
b.WriteString(")")
return b.String(), false, nil
}

6
dialects/dialect.go

@ -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() {

24
dialects/mysql.go

@ -6,7 +6,6 @@ package dialects
import (
"context"
"crypto/tls"
"database/sql"
"errors"
"fmt"
@ -172,16 +171,7 @@ 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
rowFormat string
}
func (db *mysql) Init(uri *URI) error {
@ -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" {
// col.is
}
// 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

12
dialects/postgres.go

@ -1206,9 +1206,7 @@ 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")
}
col.Default = strings.TrimSuffix(col.Default, "::timestamp without time zone")
}
}
cols[col.Name] = col
@ -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 {

21
dialects/table_name.go

@ -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)
}

10
engine.go

@ -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
}
}

6
integrations/engine_test.go

@ -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)

4
integrations/processors_test.go

@ -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) {

2
integrations/session_insert_test.go

@ -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
}

16
integrations/session_pk_test.go

@ -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))

2
integrations/session_schema_test.go

@ -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
}

14
integrations/session_update_test.go

@ -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)
}

6
integrations/tags_test.go

@ -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)
}

6
integrations/tests.go

@ -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
}

12
internal/statements/query.go

@ -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
}

18
internal/statements/statement.go

@ -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

2
internal/statements/statement_test.go

@ -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 {

1
internal/utils/slice.go

@ -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 {

16
log/logger.go

@ -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...))
}
}

17
log/syslogger.go

@ -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

2
migrate/migrate.go

@ -203,7 +203,7 @@ func (m *Migrate) migrationDidRun(mig *Migration) (bool, error) {
func (m *Migrate) isFirstRun() bool