csv2db/types.go

114 lines
1.9 KiB
Go
Raw Normal View History

2022-09-18 12:43:16 +05:00
package main
import (
"fmt"
"strconv"
"strings"
"time"
2022-10-09 17:23:59 +05:00
"github.com/urfave/cli/v2"
2022-09-18 12:43:16 +05:00
)
type FieldType int
const (
Skip FieldType = iota
Integer
String
Float
Money
Date
Timestamp
)
2022-10-09 17:23:59 +05:00
func (ft FieldType) ParseValue(c *cli.Context, s string) (any, error) {
2022-09-21 21:36:40 +05:00
s = strings.TrimSpace(s)
2022-10-05 19:45:04 +05:00
if s == "" {
return nil, nil
}
2022-09-18 12:43:16 +05:00
switch ft {
case String:
return s, nil
case Integer:
return strconv.ParseInt(s, 10, 64)
case Float:
return strconv.ParseFloat(strings.ReplaceAll(s, ",", "."), 64)
case Date:
2022-10-09 17:23:59 +05:00
return time.Parse(c.String("dateformat"), s)
2022-09-18 12:43:16 +05:00
case Timestamp:
2022-10-09 17:23:59 +05:00
return time.Parse(c.String("timestampformat"), s)
2022-09-18 12:43:16 +05:00
}
return nil, fmt.Errorf("unknown type id = %d", ft)
}
func (ft FieldType) SqlFieldType() string {
switch ft {
case Integer:
return "bigint"
case String:
return "nvarchar(255)"
case Float:
return "float"
case Money:
panic("do not implemented - see https://github.com/denisenkom/go-mssqldb/issues/460") // TODO: https://github.com/denisenkom/go-mssqldb/issues/460
case Date:
return "date"
2022-09-21 21:36:40 +05:00
case Timestamp:
2022-09-18 12:43:16 +05:00
return "datetime2"
}
return ""
}
func (ft FieldType) MarshalText() (text []byte, err error) {
switch ft {
case Skip:
return []byte(" "), nil
case Integer:
return []byte("i"), nil
case String:
return []byte("s"), nil
case Float:
return []byte("f"), nil
case Money:
return []byte("m"), nil
case Date:
return []byte("d"), nil
case Timestamp:
return []byte("t"), nil
}
return nil, fmt.Errorf("unknown type id = %d", ft)
}
func (ft *FieldType) UnmarshalText(text []byte) error {
switch string(text) {
case " ":
*ft = Skip
2022-09-21 21:36:40 +05:00
return nil
2022-09-18 12:43:16 +05:00
case "i":
*ft = Integer
2022-09-21 21:36:40 +05:00
return nil
2022-09-18 12:43:16 +05:00
case "s":
*ft = String
2022-09-21 21:36:40 +05:00
return nil
2022-09-18 12:43:16 +05:00
case "f":
*ft = Float
2022-09-21 21:36:40 +05:00
return nil
2022-09-18 12:43:16 +05:00
case "m":
*ft = Money
2022-09-21 21:36:40 +05:00
return nil
2022-09-18 12:43:16 +05:00
case "d":
*ft = Date
2022-09-21 21:36:40 +05:00
return nil
2022-09-18 12:43:16 +05:00
case "t":
*ft = Timestamp
2022-09-21 21:36:40 +05:00
return nil
2022-09-18 12:43:16 +05:00
}
2022-09-21 21:36:40 +05:00
return fmt.Errorf(`unknown format code "%s"`, string(text))
2022-09-18 12:43:16 +05:00
}