Fix some comments lint and bug (#1888)

Reviewed-on: https://gitea.com/xorm/xorm/pulls/1888
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-committed-by: Lunny Xiao <xiaolunwen@gmail.com>
This commit is contained in:
Lunny Xiao 2021-04-10 10:57:36 +08:00
parent b92d951eac
commit 4bfe6853f5
19 changed files with 90 additions and 46 deletions

View File

@ -19,6 +19,7 @@ type LevelDBStore struct {
var _ CacheStore = &LevelDBStore{} var _ CacheStore = &LevelDBStore{}
// NewLevelDBStore creates a leveldb store
func NewLevelDBStore(dbfile string) (*LevelDBStore, error) { func NewLevelDBStore(dbfile string) (*LevelDBStore, error) {
db := &LevelDBStore{} db := &LevelDBStore{}
h, err := leveldb.OpenFile(dbfile, nil) h, err := leveldb.OpenFile(dbfile, nil)
@ -29,6 +30,7 @@ func NewLevelDBStore(dbfile string) (*LevelDBStore, error) {
return db, nil return db, nil
} }
// Put implements CacheStore
func (s *LevelDBStore) Put(key string, value interface{}) error { func (s *LevelDBStore) Put(key string, value interface{}) error {
val, err := Encode(value) val, err := Encode(value)
if err != nil { if err != nil {
@ -50,6 +52,7 @@ func (s *LevelDBStore) Put(key string, value interface{}) error {
return err return err
} }
// Get implements CacheStore
func (s *LevelDBStore) Get(key string) (interface{}, error) { func (s *LevelDBStore) Get(key string) (interface{}, error) {
data, err := s.store.Get([]byte(key), nil) data, err := s.store.Get([]byte(key), nil)
if err != nil { if err != nil {
@ -75,6 +78,7 @@ func (s *LevelDBStore) Get(key string) (interface{}, error) {
return s.v, err return s.v, err
} }
// Del implements CacheStore
func (s *LevelDBStore) Del(key string) error { func (s *LevelDBStore) Del(key string) error {
err := s.store.Delete([]byte(key), nil) err := s.store.Delete([]byte(key), nil)
if err != nil { if err != nil {
@ -89,6 +93,7 @@ func (s *LevelDBStore) Del(key string) error {
return err return err
} }
// Close implements CacheStore
func (s *LevelDBStore) Close() { func (s *LevelDBStore) Close() {
s.store.Close() s.store.Close()
} }

View File

@ -6,6 +6,7 @@ package caches
import "sync" import "sync"
// Manager represents a cache manager
type Manager struct { type Manager struct {
cacher Cacher cacher Cacher
disableGlobalCache bool disableGlobalCache bool
@ -14,6 +15,7 @@ type Manager struct {
cacherLock sync.RWMutex cacherLock sync.RWMutex
} }
// NewManager creates a cache manager
func NewManager() *Manager { func NewManager() *Manager {
return &Manager{ return &Manager{
cachers: make(map[string]Cacher), cachers: make(map[string]Cacher),
@ -27,12 +29,14 @@ func (mgr *Manager) SetDisableGlobalCache(disable bool) {
} }
} }
// SetCacher set cacher of table
func (mgr *Manager) SetCacher(tableName string, cacher Cacher) { func (mgr *Manager) SetCacher(tableName string, cacher Cacher) {
mgr.cacherLock.Lock() mgr.cacherLock.Lock()
mgr.cachers[tableName] = cacher mgr.cachers[tableName] = cacher
mgr.cacherLock.Unlock() mgr.cacherLock.Unlock()
} }
// GetCacher returns a cache of a table
func (mgr *Manager) GetCacher(tableName string) Cacher { func (mgr *Manager) GetCacher(tableName string) Cacher {
var cacher Cacher var cacher Cacher
var ok bool var ok bool

View File

@ -31,6 +31,7 @@ func NewContextHook(ctx context.Context, sql string, args []interface{}) *Contex
} }
} }
// End finish the hook invokation
func (c *ContextHook) End(ctx context.Context, result sql.Result, err error) { func (c *ContextHook) End(ctx context.Context, result sql.Result, err error) {
c.Ctx = ctx c.Ctx = ctx
c.Result = result c.Result = result
@ -38,19 +39,23 @@ func (c *ContextHook) End(ctx context.Context, result sql.Result, err error) {
c.ExecuteTime = time.Now().Sub(c.start) c.ExecuteTime = time.Now().Sub(c.start)
} }
// Hook represents a hook behaviour
type Hook interface { type Hook interface {
BeforeProcess(c *ContextHook) (context.Context, error) BeforeProcess(c *ContextHook) (context.Context, error)
AfterProcess(c *ContextHook) error AfterProcess(c *ContextHook) error
} }
// Hooks implements Hook interface but contains multiple Hook
type Hooks struct { type Hooks struct {
hooks []Hook hooks []Hook
} }
// AddHook adds a Hook
func (h *Hooks) AddHook(hooks ...Hook) { func (h *Hooks) AddHook(hooks ...Hook) {
h.hooks = append(h.hooks, hooks...) h.hooks = append(h.hooks, hooks...)
} }
// BeforeProcess invoked before execute the process
func (h *Hooks) BeforeProcess(c *ContextHook) (context.Context, error) { func (h *Hooks) BeforeProcess(c *ContextHook) (context.Context, error) {
ctx := c.Ctx ctx := c.Ctx
for _, h := range h.hooks { for _, h := range h.hooks {
@ -63,6 +68,7 @@ func (h *Hooks) BeforeProcess(c *ContextHook) (context.Context, error) {
return ctx, nil return ctx, nil
} }
// AfterProcess invoked after exetue the process
func (h *Hooks) AfterProcess(c *ContextHook) error { func (h *Hooks) AfterProcess(c *ContextHook) error {
firstErr := c.Err firstErr := c.Err
for _, h := range h.hooks { for _, h := range h.hooks {

View File

@ -79,32 +79,34 @@ type Base struct {
quoter schemas.Quoter quoter schemas.Quoter
} }
func (b *Base) Quoter() schemas.Quoter { // Quoter returns the current database Quoter
return b.quoter func (db *Base) Quoter() schemas.Quoter {
return db.quoter
} }
func (b *Base) Init(dialect Dialect, uri *URI) error { // Init initialize the dialect
b.dialect, b.uri = dialect, uri func (db *Base) Init(dialect Dialect, uri *URI) error {
db.dialect, db.uri = dialect, uri
return nil return nil
} }
func (b *Base) URI() *URI { // URI returns the uri of database
return b.uri func (db *Base) URI() *URI {
return db.uri
} }
func (b *Base) DBType() schemas.DBType { // FormatBytes formats bytes
return b.uri.DBType func (db *Base) FormatBytes(bs []byte) string {
}
func (b *Base) FormatBytes(bs []byte) string {
return fmt.Sprintf("0x%x", bs) return fmt.Sprintf("0x%x", bs)
} }
// DropTableSQL returns drop table SQL
func (db *Base) DropTableSQL(tableName string) (string, bool) { func (db *Base) DropTableSQL(tableName string) (string, bool) {
quote := db.dialect.Quoter().Quote quote := db.dialect.Quoter().Quote
return fmt.Sprintf("DROP TABLE IF EXISTS %s", quote(tableName)), true return fmt.Sprintf("DROP TABLE IF EXISTS %s", quote(tableName)), true
} }
// HasRecords returns true if the SQL has records returned
func (db *Base) HasRecords(queryer core.Queryer, ctx context.Context, query string, args ...interface{}) (bool, error) { func (db *Base) HasRecords(queryer core.Queryer, ctx context.Context, query string, args ...interface{}) (bool, error) {
rows, err := queryer.QueryContext(ctx, query, args...) rows, err := queryer.QueryContext(ctx, query, args...)
if err != nil { if err != nil {
@ -118,6 +120,7 @@ func (db *Base) HasRecords(queryer core.Queryer, ctx context.Context, query stri
return false, nil return false, nil
} }
// IsColumnExist returns true if the column of the table exist
func (db *Base) IsColumnExist(queryer core.Queryer, ctx context.Context, tableName, colName string) (bool, error) { func (db *Base) IsColumnExist(queryer core.Queryer, ctx context.Context, tableName, colName string) (bool, error) {
quote := db.dialect.Quoter().Quote quote := db.dialect.Quoter().Quote
query := fmt.Sprintf( query := fmt.Sprintf(
@ -132,11 +135,13 @@ func (db *Base) IsColumnExist(queryer core.Queryer, ctx context.Context, tableNa
return db.HasRecords(queryer, ctx, query, db.uri.DBName, tableName, colName) return db.HasRecords(queryer, ctx, query, db.uri.DBName, tableName, colName)
} }
// AddColumnSQL returns a SQL to add a column
func (db *Base) AddColumnSQL(tableName string, col *schemas.Column) string { func (db *Base) AddColumnSQL(tableName string, col *schemas.Column) string {
s, _ := ColumnString(db.dialect, col, true) s, _ := ColumnString(db.dialect, col, true)
return fmt.Sprintf("ALTER TABLE %v ADD %v", db.dialect.Quoter().Quote(tableName), s) return fmt.Sprintf("ALTER TABLE %v ADD %v", db.dialect.Quoter().Quote(tableName), s)
} }
// CreateIndexSQL returns a SQL to create index
func (db *Base) CreateIndexSQL(tableName string, index *schemas.Index) string { func (db *Base) CreateIndexSQL(tableName string, index *schemas.Index) string {
quoter := db.dialect.Quoter() quoter := db.dialect.Quoter()
var unique string var unique string
@ -150,6 +155,7 @@ func (db *Base) CreateIndexSQL(tableName string, index *schemas.Index) string {
quoter.Join(index.Cols, ",")) quoter.Join(index.Cols, ","))
} }
// DropIndexSQL returns a SQL to drop index
func (db *Base) DropIndexSQL(tableName string, index *schemas.Index) string { func (db *Base) DropIndexSQL(tableName string, index *schemas.Index) string {
quote := db.dialect.Quoter().Quote quote := db.dialect.Quoter().Quote
var name string var name string
@ -161,16 +167,19 @@ func (db *Base) DropIndexSQL(tableName string, index *schemas.Index) string {
return fmt.Sprintf("DROP INDEX %v ON %s", quote(name), quote(tableName)) return fmt.Sprintf("DROP INDEX %v ON %s", quote(name), quote(tableName))
} }
// ModifyColumnSQL returns a SQL to modify SQL
func (db *Base) ModifyColumnSQL(tableName string, col *schemas.Column) string { func (db *Base) ModifyColumnSQL(tableName string, col *schemas.Column) string {
s, _ := ColumnString(db.dialect, col, false) s, _ := ColumnString(db.dialect, col, false)
return fmt.Sprintf("ALTER TABLE %s MODIFY COLUMN %s", tableName, s) return fmt.Sprintf("ALTER TABLE %s MODIFY COLUMN %s", tableName, s)
} }
func (b *Base) ForUpdateSQL(query string) string { // ForUpdateSQL returns for updateSQL
func (db *Base) ForUpdateSQL(query string) string {
return query + " FOR UPDATE" return query + " FOR UPDATE"
} }
func (b *Base) SetParams(params map[string]string) { // SetParams set params
func (db *Base) SetParams(params map[string]string) {
} }
var ( var (

View File

@ -1278,6 +1278,7 @@ func (engine *Engine) SetSchema(schema string) {
engine.dialect.URI().SetSchema(schema) engine.dialect.URI().SetSchema(schema)
} }
// AddHook adds a context Hook
func (engine *Engine) AddHook(hook contexts.Hook) { func (engine *Engine) AddHook(hook contexts.Hook) {
engine.db.AddHook(hook) engine.db.AddHook(hook)
} }
@ -1293,7 +1294,7 @@ func (engine *Engine) tbNameWithSchema(v string) string {
return dialects.TableNameWithSchema(engine.dialect, v) return dialects.TableNameWithSchema(engine.dialect, v)
} }
// ContextHook creates a session with the context // Context creates a session with the context
func (engine *Engine) Context(ctx context.Context) *Session { func (engine *Engine) Context(ctx context.Context) *Session {
session := engine.NewSession() session := engine.NewSession()
session.isAutoClose = true session.isAutoClose = true

View File

@ -79,7 +79,7 @@ func (eg *EngineGroup) Close() error {
return nil return nil
} }
// ContextHook returned a group session // Context returned a group session
func (eg *EngineGroup) Context(ctx context.Context) *Session { func (eg *EngineGroup) Context(ctx context.Context) *Session {
sess := eg.NewSession() sess := eg.NewSession()
sess.isAutoClose = true sess.isAutoClose = true
@ -144,6 +144,7 @@ func (eg *EngineGroup) SetLogger(logger interface{}) {
} }
} }
// AddHook adds Hook
func (eg *EngineGroup) AddHook(hook contexts.Hook) { func (eg *EngineGroup) AddHook(hook contexts.Hook) {
eg.Engine.AddHook(hook) eg.Engine.AddHook(hook)
for i := 0; i < len(eg.slaves); i++ { for i := 0; i < len(eg.slaves); i++ {

View File

@ -190,7 +190,7 @@ func TestSetSchema(t *testing.T) {
func TestImport(t *testing.T) { func TestImport(t *testing.T) {
if testEngine.Dialect().URI().DBType != schemas.MYSQL { if testEngine.Dialect().URI().DBType != schemas.MYSQL {
t.SkipNow() t.Skip()
return return
} }
sess := testEngine.NewSession() sess := testEngine.NewSession()

View File

@ -8,6 +8,7 @@ import (
"database/sql" "database/sql"
"flag" "flag"
"fmt" "fmt"
"net/url"
"os" "os"
"strings" "strings"
"testing" "testing"
@ -97,6 +98,13 @@ func createEngine(dbType, connStr string) error {
return fmt.Errorf("db.Exec: %v", err) return fmt.Errorf("db.Exec: %v", err)
} }
db.Close() db.Close()
case schemas.SQLITE, "sqlite":
u, err := url.Parse(connStr)
if err != nil {
return err
}
connStr = u.Path
*ignoreSelectUpdate = true
default: default:
*ignoreSelectUpdate = true *ignoreSelectUpdate = true
} }
@ -164,10 +172,12 @@ func createEngine(dbType, connStr string) error {
return nil return nil
} }
// PrepareEngine prepare tests ORM engine
func PrepareEngine() error { func PrepareEngine() error {
return createEngine(dbType, connString) return createEngine(dbType, connString)
} }
// MainTest the tests entrance
func MainTest(m *testing.M) { func MainTest(m *testing.M) {
flag.Parse() flag.Parse()

View File

@ -6,15 +6,15 @@ package json
import "encoding/json" import "encoding/json"
// JSONInterface represents an interface to handle json data // Interface represents an interface to handle json data
type JSONInterface interface { type Interface interface {
Marshal(v interface{}) ([]byte, error) Marshal(v interface{}) ([]byte, error)
Unmarshal(data []byte, v interface{}) error Unmarshal(data []byte, v interface{}) error
} }
var ( var (
// DefaultJSONHandler default json handler // DefaultJSONHandler default json handler
DefaultJSONHandler JSONInterface = StdJSON{} DefaultJSONHandler Interface = StdJSON{}
) )
// StdJSON implements JSONInterface via encoding/json // StdJSON implements JSONInterface via encoding/json

View File

@ -8,6 +8,7 @@ import (
"fmt" "fmt"
) )
// IndexName returns index name
func IndexName(tableName, idxName string) string { func IndexName(tableName, idxName string) string {
return fmt.Sprintf("IDX_%v_%v", tableName, idxName) return fmt.Sprintf("IDX_%v_%v", tableName, idxName)
} }

View File

@ -8,6 +8,7 @@ import (
"reflect" "reflect"
) )
// ReflectValue returns value of a bean
func ReflectValue(bean interface{}) reflect.Value { func ReflectValue(bean interface{}) reflect.Value {
return reflect.Indirect(reflect.ValueOf(bean)) return reflect.Indirect(reflect.ValueOf(bean))
} }

View File

@ -8,6 +8,7 @@ import (
"strings" "strings"
) )
// IsSubQuery returns true if it contains a sub query
func IsSubQuery(tbName string) bool { func IsSubQuery(tbName string) bool {
const selStr = "select" const selStr = "select"
if len(tbName) <= len(selStr)+1 { if len(tbName) <= len(selStr)+1 {

View File

@ -8,10 +8,12 @@ import (
"strings" "strings"
) )
// IndexNoCase index a string in a string with no care of capitalize
func IndexNoCase(s, sep string) int { func IndexNoCase(s, sep string) int {
return strings.Index(strings.ToLower(s), strings.ToLower(sep)) return strings.Index(strings.ToLower(s), strings.ToLower(sep))
} }
// SplitNoCase split a string by a seperator with no care of capitalize
func SplitNoCase(s, sep string) []string { func SplitNoCase(s, sep string) []string {
idx := IndexNoCase(s, sep) idx := IndexNoCase(s, sep)
if idx < 0 { if idx < 0 {
@ -20,6 +22,7 @@ func SplitNoCase(s, sep string) []string {
return strings.Split(s, s[idx:idx+len(sep)]) return strings.Split(s, s[idx:idx+len(sep)])
} }
// SplitNNoCase split n by a seperator with no care of capitalize
func SplitNNoCase(s, sep string, n int) []string { func SplitNNoCase(s, sep string, n int) []string {
idx := IndexNoCase(s, sep) idx := IndexNoCase(s, sep)
if idx < 0 { if idx < 0 {

View File

@ -9,6 +9,7 @@ import (
"time" "time"
) )
// Zeroable represents an interface which could know if it's a zero value
type Zeroable interface { type Zeroable interface {
IsZero() bool IsZero() bool
} }
@ -21,39 +22,39 @@ func IsZero(k interface{}) bool {
return true return true
} }
switch k.(type) { switch t := k.(type) {
case int: case int:
return k.(int) == 0 return t == 0
case int8: case int8:
return k.(int8) == 0 return t == 0
case int16: case int16:
return k.(int16) == 0 return t == 0
case int32: case int32:
return k.(int32) == 0 return t == 0
case int64: case int64:
return k.(int64) == 0 return t == 0
case uint: case uint:
return k.(uint) == 0 return t == 0
case uint8: case uint8:
return k.(uint8) == 0 return t == 0
case uint16: case uint16:
return k.(uint16) == 0 return t == 0
case uint32: case uint32:
return k.(uint32) == 0 return t == 0
case uint64: case uint64:
return k.(uint64) == 0 return t == 0
case float32: case float32:
return k.(float32) == 0 return t == 0
case float64: case float64:
return k.(float64) == 0 return t == 0
case bool: case bool:
return k.(bool) == false return !t
case string: case string:
return k.(string) == "" return t == ""
case *time.Time: case *time.Time:
return k.(*time.Time) == nilTime || IsTimeZero(*k.(*time.Time)) return t == nilTime || IsTimeZero(*t)
case time.Time: case time.Time:
return IsTimeZero(k.(time.Time)) return IsTimeZero(t)
case Zeroable: case Zeroable:
return k.(Zeroable) == nil || k.(Zeroable).IsZero() return k.(Zeroable) == nil || k.(Zeroable).IsZero()
case reflect.Value: // for go version less than 1.13 because reflect.Value has no method IsZero case reflect.Value: // for go version less than 1.13 because reflect.Value has no method IsZero
@ -65,6 +66,7 @@ func IsZero(k interface{}) bool {
var zeroType = reflect.TypeOf((*Zeroable)(nil)).Elem() var zeroType = reflect.TypeOf((*Zeroable)(nil)).Elem()
// IsValueZero returns true if the reflect Value is a zero
func IsValueZero(v reflect.Value) bool { func IsValueZero(v reflect.Value) bool {
switch v.Kind() { switch v.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Slice: case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Slice:
@ -88,6 +90,7 @@ func IsValueZero(v reflect.Value) bool {
return false return false
} }
// IsStructZero returns true if the Value is a struct and all fields is zero
func IsStructZero(v reflect.Value) bool { func IsStructZero(v reflect.Value) bool {
if !v.IsValid() || v.NumField() == 0 { if !v.IsValid() || v.NumField() == 0 {
return true return true
@ -120,6 +123,7 @@ func IsStructZero(v reflect.Value) bool {
return true return true
} }
// IsArrayZero returns true is a slice of array is zero
func IsArrayZero(v reflect.Value) bool { func IsArrayZero(v reflect.Value) bool {
if !v.IsValid() || v.Len() == 0 { if !v.IsValid() || v.Len() == 0 {
return true return true
@ -134,11 +138,13 @@ func IsArrayZero(v reflect.Value) bool {
return true return true
} }
// represents all zero times
const ( const (
ZeroTime0 = "0000-00-00 00:00:00" ZeroTime0 = "0000-00-00 00:00:00"
ZeroTime1 = "0001-01-01 00:00:00" ZeroTime1 = "0001-01-01 00:00:00"
) )
// IsTimeZero return true if a time is zero
func IsTimeZero(t time.Time) bool { func IsTimeZero(t time.Time) bool {
return t.IsZero() || t.Format("2006-01-02 15:04:05") == ZeroTime0 || return t.IsZero() || t.Format("2006-01-02 15:04:05") == ZeroTime0 ||
t.Format("2006-01-02 15:04:05") == ZeroTime1 t.Format("2006-01-02 15:04:05") == ZeroTime1

View File

@ -110,10 +110,7 @@ func (m *Migrate) RollbackLast() error {
return err return err
} }
if err := m.RollbackMigration(lastRunnedMigration); err != nil { return m.RollbackMigration(lastRunnedMigration)
return err
}
return nil
} }
func (m *Migrate) getLastRunnedMigration() (*Migration, error) { func (m *Migrate) getLastRunnedMigration() (*Migration, error) {

View File

@ -106,10 +106,7 @@ func TestInitSchema(t *testing.T) {
if err := tx.Sync2(&Person{}); err != nil { if err := tx.Sync2(&Person{}); err != nil {
return err return err
} }
if err := tx.Sync2(&Pet{}); err != nil { return tx.Sync2(&Pet{})
return err
}
return nil
}) })
err = m.Migrate() err = m.Migrate()

View File

@ -169,6 +169,7 @@ func (session *Session) db() *core.DB {
return session.engine.db return session.engine.db
} }
// Engine returns session Engine
func (session *Session) Engine() *Engine { func (session *Session) Engine() *Engine {
return session.engine return session.engine
} }
@ -895,7 +896,7 @@ func (session *Session) incrVersionFieldValue(fieldValue *reflect.Value) {
} }
} }
// ContextHook sets the context on this session // Context sets the context on this session
func (session *Session) Context(ctx context.Context) *Session { func (session *Session) Context(ctx context.Context) *Session {
session.ctx = ctx session.ctx = ctx
return session return session

View File

@ -17,6 +17,7 @@ import (
) )
var ( var (
// ErrObjectIsNil return error of object is nil
ErrObjectIsNil = errors.New("object should not be nil") ErrObjectIsNil = errors.New("object should not be nil")
) )

View File

@ -85,7 +85,7 @@ func (session *Session) Commit() error {
return nil return nil
} }
// if current session is in a transaction // IsInTx if current session is in a transaction
func (session *Session) IsInTx() bool { func (session *Session) IsInTx() bool {
return !session.isAutoCommit return !session.isAutoCommit
} }