xorm/convert/bool.go
Lunny Xiao cace6862e2
All checks were successful
continuous-integration/drone/push Build is passing
Move convert back to xorm.io/xorm/convert (#2030)
Since `conversion.Conversion` has been referenced by external package, it should not be moved as internal package.

Reviewed-on: #2030
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-committed-by: Lunny Xiao <xiaolunwen@gmail.com>
2021-08-10 23:20:53 +08:00

52 lines
995 B
Go

// Copyright 2021 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package convert
import (
"database/sql"
"fmt"
"strconv"
)
// AsBool convert interface as bool
func AsBool(src interface{}) (bool, error) {
switch v := src.(type) {
case bool:
return v, nil
case *bool:
return *v, nil
case *sql.NullBool:
return v.Bool, nil
case int64:
return v > 0, nil
case int:
return v > 0, nil
case int8:
return v > 0, nil
case int16:
return v > 0, nil
case int32:
return v > 0, nil
case []byte:
if len(v) == 0 {
return false, nil
}
if v[0] == 0x00 {
return false, nil
} else if v[0] == 0x01 {
return true, nil
}
return strconv.ParseBool(string(v))
case string:
return strconv.ParseBool(v)
case *sql.NullInt64:
return v.Int64 > 0, nil
case *sql.NullInt32:
return v.Int32 > 0, nil
default:
return false, fmt.Errorf("unknow type %T as bool", src)
}
}