// sql - A tool for querying databases.
// Copyright (C) 2021 Noel Cower
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package vdb
import (
"database/sql"
"database/sql/driver"
"encoding/base64"
"encoding/json"
"fmt"
"math/big"
"strconv"
"strings"
"time"
)
type Value struct {
Options *QueryOptions
Type *sql.ColumnType
Dest interface{}
}
const numericBytes = "+-0123456789"
func (v *Value) Value() (driver.Value, error) {
// Implemented in case someone passes this data back into a query.
switch d := v.Dest.(type) {
case *big.Float:
return d.Text('f', -1), nil
case *big.Int:
return d.String(), nil
case time.Time:
switch v.Options.TimeFormat {
case TimeString:
return d.Format(time.RFC3339Nano), nil
case TimeFloat:
t := d.Truncate(time.Second)
sub := d.Sub(t)
f := new(big.Float).SetPrec(0).SetFloat64(float64(sub))
f = f.Quo(f, big.NewFloat(float64(time.Second)))
f = f.Add(f, big.NewFloat(float64(t.Unix())))
return f.Text('f', -1), nil
case TimeUnix:
return d.Unix(), nil
case TimeUnixNano, TimeUnixMicro, TimeUnixMilli:
t := d.Truncate(time.Second)
sub := d.Sub(t)
b := big.NewInt(t.Unix())
b = b.Mul(b, big.NewInt(int64(time.Second)))
b = b.Add(b, big.NewInt(int64(sub)))
switch v.Options.TimeFormat {
case TimeUnixMicro:
b = b.Quo(b, big.NewInt(int64(time.Microsecond)))
case TimeUnixMilli:
b = b.Quo(b, big.NewInt(int64(time.Millisecond)))
}
return b.String(), nil
case TimeCustom:
return d.Format(v.Options.TimeLayout), nil
}
case map[string]interface{}, []interface{}:
p, err := json.Marshal(v.Dest)
return string(p), err
}
return v.Dest, nil
}
func (v *Value) Opaque() interface{} {
switch d := v.Dest.(type) {
case *big.Float:
// Convert to float64 for concrete value use.
f, _ := d.Float64()
return f
case *big.Int:
// Convert to int64 for concrete value use.
return d.Int64()
case time.Time:
switch v.Options.TimeFormat {
case TimeString:
return d.Format(time.RFC3339Nano)
case TimeFloat:
t := d.Truncate(time.Second)
sub := d.Sub(t)
f := new(big.Float).SetPrec(0).SetFloat64(float64(sub))
f = f.Quo(f, big.NewFloat(float64(time.Second)))
f = f.Add(f, big.NewFloat(float64(t.Unix())))
return f.Text('f', -1)
case TimeUnix:
return d.Unix()
case TimeUnixNano, TimeUnixMicro, TimeUnixMilli:
t := d.Truncate(time.Second)
sub := d.Sub(t)
b := big.NewInt(t.Unix())
b = b.Mul(b, big.NewInt(int64(time.Second)))
b = b.Add(b, big.NewInt(int64(sub)))
switch v.Options.TimeFormat {
case TimeUnixMicro:
b = b.Quo(b, big.NewInt(int64(time.Microsecond)))
case TimeUnixMilli:
b = b.Quo(b, big.NewInt(int64(time.Millisecond)))
}
return b.String()
case TimeCustom:
return d.Format(v.Options.TimeLayout)
}
}
return v.Dest
}
func (v *Value) parseFloat(src string) bool {
b, ok := new(big.Int).SetString(src, 0)
if ok {
v.Dest = b
}
return ok
}
func (v *Value) parseInt(src string) bool {
f, ok := new(big.Float).SetPrec(0).SetString(src)
if ok {
v.Dest = f
}
return ok
}
func (v *Value) Scan(src interface{}) error {
tryJSON := v.Options.TryJSON && !v.Options.SkipJSON
if !tryJSON && !v.Options.SkipJSON && v.Type != nil {
name := strings.ToLower(v.Type.Name())
tryJSON = strings.HasSuffix(name, "_json") ||
name == "json" ||
strings.HasPrefix(strings.ToLower(v.Type.DatabaseTypeName()), "json")
}
switch conc := src.(type) {
case nil:
v.Dest = nil
return nil
case int64, float64, time.Time, bool:
v.Dest = conc
return nil
case string:
v.Dest = conc
src = []byte(conc)
}
p, ok := src.([]byte)
if !ok {
return fmt.Errorf("unexpected scan type %T", src)
}
var text func() string
text = func() string {
t, ok := src.(string)
if !ok {
t = string(p)
}
text = func() string { return t }
return t
}
if tryJSON && len(p) > 0 {
if strings.IndexByte(numericBytes, p[0]) > -1 && (v.parseInt(text()) || v.parseFloat(text())) {
return nil
}
if json.Unmarshal(p, &v.Dest) == nil {
return nil
}
}
t := strings.ToLower(v.Type.DatabaseTypeName())
// TODO: Support Postgres array types?
switch t {
case "tinyint",
"smallint",
"mediumint",
"bigint",
"integer",
"smallserial",
"serial",
"bigserial":
if v.parseInt(text()) {
return nil
}
case "decimal",
"numeric",
"float",
"double",
"fixed",
"dec",
"double precision",
"real",
"money":
if v.parseFloat(text()) {
return nil
}
case "text",
"char",
"character",
"varchar",
"character varying",
"tinytext",
"mediumtext",
"longtext",
"enum",
"set":
v.Dest = string(p)
return nil
case "blob",
"bytea",
"tinyblob",
"mediumblob",
"longblob",
"binary",
"varbinary":
v.Dest = append([]byte(nil), p...)
return nil
case "json", "jsonb":
if v.Options.SkipJSON {
break
}
return json.Unmarshal(p, &v.Dest)
}
// Fallback:
v.Dest = string(p)
return nil
}
func (v *Value) MarshalJSON() ([]byte, error) {
switch d := v.Dest.(type) {
case *big.Float:
return []byte(d.Text('f', -1)), nil
case *big.Int:
return []byte(d.String()), nil
case time.Time:
switch v.Options.TimeFormat {
case TimeString:
return json.Marshal(d.Format(time.RFC3339Nano))
case TimeFloat:
t := d.Truncate(time.Second)
sub := d.Sub(t)
f := new(big.Float).SetPrec(0).SetFloat64(float64(sub))
f = f.Quo(f, big.NewFloat(float64(time.Second)))
f = f.Add(f, big.NewFloat(float64(t.Unix())))
return []byte(f.Text('f', -1)), nil
case TimeUnix:
return []byte(strconv.FormatInt(d.Unix(), 10)), nil
case TimeUnixNano, TimeUnixMicro, TimeUnixMilli:
t := d.Truncate(time.Second)
sub := d.Sub(t)
b := big.NewInt(t.Unix())
b = b.Mul(b, big.NewInt(int64(time.Second)))
b = b.Add(b, big.NewInt(int64(sub)))
switch v.Options.TimeFormat {
case TimeUnixMicro:
b = b.Quo(b, big.NewInt(int64(time.Microsecond)))
case TimeUnixMilli:
b = b.Quo(b, big.NewInt(int64(time.Millisecond)))
}
return []byte(b.String()), nil
case TimeCustom:
return json.Marshal(d.Format(v.Options.TimeLayout))
}
case []byte:
return json.Marshal(base64.StdEncoding.EncodeToString(d))
}
return json.Marshal(v.Dest)
}