2021-06-11 05:35:50 +00:00
|
|
|
// 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"
|
|
|
|
)
|
|
|
|
|
2021-06-12 01:51:31 +00:00
|
|
|
// Interface2String converts an interface to string
|
|
|
|
func Interface2String(v interface{}) (string, error) {
|
2021-06-11 15:48:58 +00:00
|
|
|
if v == nil {
|
|
|
|
return "", nil
|
|
|
|
}
|
2021-06-11 05:35:50 +00:00
|
|
|
switch vv := v.(type) {
|
2021-06-11 15:48:58 +00:00
|
|
|
case *int64:
|
|
|
|
return strconv.FormatInt(*vv, 10), nil
|
|
|
|
case *int8:
|
|
|
|
return strconv.FormatInt(int64(*vv), 10), nil
|
2021-06-11 05:35:50 +00:00
|
|
|
case *sql.NullString:
|
|
|
|
if vv.Valid {
|
|
|
|
return vv.String, nil
|
|
|
|
}
|
|
|
|
return "", nil
|
2021-06-11 15:48:58 +00:00
|
|
|
case *sql.RawBytes:
|
|
|
|
if len([]byte(*vv)) > 0 {
|
|
|
|
return string(*vv), nil
|
2021-06-11 05:35:50 +00:00
|
|
|
}
|
|
|
|
return "", nil
|
2021-06-11 15:48:58 +00:00
|
|
|
case *sql.NullInt32:
|
|
|
|
if vv.Valid {
|
|
|
|
return fmt.Sprintf("%d", vv.Int32), nil
|
2021-06-11 05:35:50 +00:00
|
|
|
}
|
|
|
|
return "", nil
|
2021-06-11 15:48:58 +00:00
|
|
|
case *sql.NullInt64:
|
|
|
|
if vv.Valid {
|
|
|
|
return fmt.Sprintf("%d", vv.Int64), nil
|
|
|
|
}
|
|
|
|
return "", nil
|
|
|
|
case *sql.NullFloat64:
|
|
|
|
if vv.Valid {
|
|
|
|
return fmt.Sprintf("%g", vv.Float64), nil
|
|
|
|
}
|
|
|
|
return "", nil
|
|
|
|
case *sql.NullBool:
|
|
|
|
if vv.Valid {
|
|
|
|
if vv.Bool {
|
|
|
|
return "true", nil
|
|
|
|
}
|
|
|
|
return "false", nil
|
|
|
|
}
|
|
|
|
return "", nil
|
|
|
|
case *sql.NullTime:
|
|
|
|
if vv.Valid {
|
|
|
|
return vv.Time.Format("2006-01-02 15:04:05"), nil
|
2021-06-11 05:35:50 +00:00
|
|
|
}
|
|
|
|
return "", nil
|
|
|
|
default:
|
2021-06-11 15:48:58 +00:00
|
|
|
return "", fmt.Errorf("convert assign string unsupported type: %#v", vv)
|
2021-06-11 05:35:50 +00:00
|
|
|
}
|
|
|
|
}
|