Files
2026-12-01 19:40:55 +01:00

223 lines
6.2 KiB
Go

package dbcopy
import (
"database/sql/driver"
"math"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"github.com/mattn/go-sqlite3"
"github.com/phishingclub/phishingclub/database/dbengine"
)
// invalidKind names why a source value can not be copied. The report shows
// the kind, never the value.
type invalidKind string
const (
invalidNull invalidKind = "null_in_not_null"
invalidUUID invalidKind = "uuid"
invalidTime invalidKind = "time"
invalidBool invalidKind = "bool"
invalidInt invalidKind = "int"
invalidRange invalidKind = "int_range"
invalidTooLong invalidKind = "too_long"
invalidFloat invalidKind = "float"
invalidBytes invalidKind = "bytes"
invalidRowID invalidKind = "rowid_too_large"
)
// converted is a source value made ready for its target column
type converted struct {
value any
// cleaned is set when text was changed by dbengine.CleanText
cleaned bool
// raw is the source text of a cleaned value
raw string
// invalid is set when the value can not be copied
invalid invalidKind
// size is the number of bytes of the value, for the batch budget
size int
// truncated is set for a time with digits below a microsecond, which
// postgres drops
truncated bool
}
// convert turns a value read from sqlite into the value for the target
// column. The source value is the storage class value mattn returns for an
// expression without a declared type: int64, float64, string, []byte or nil.
// Each rule follows what the application reads from sqlite today (mattn,
// database/sql and the scan of the field), so the target holds what the
// application reads now; a value the application would read as a silent
// zero or fail to scan is refused instead.
func convert(c *column, v any) converted {
if v == nil {
if !c.nullable {
return converted{invalid: invalidNull}
}
return converted{}
}
switch c.kind {
case kindUUID:
return convertUUID(v)
case kindTime:
return convertTime(v)
case kindBool:
return convertBool(c, v)
case kindInt:
return convertInt(c, v)
case kindText:
return convertText(c, v)
case kindFloat:
return convertFloat(v)
case kindBytes:
return convertBytes(v)
}
return converted{invalid: invalidBytes}
}
// convertUUID accepts only the canonical text form gorm writes. An empty text
// is refused: the application reads it as the nil uuid, postgres refuses it,
// and a NULL or the nil uuid would change what the row means.
func convertUUID(v any) converted {
s, ok := v.(string)
if !ok {
return converted{invalid: invalidUUID}
}
u, err := uuid.Parse(s)
if err != nil || u.String() != s {
return converted{invalid: invalidUUID}
}
return converted{value: s, size: len(s)}
}
// convertTime reads a time as mattn reads a datetime column: text in one of
// the sqlite formats, in UTC when it has no offset, and an integer as unix
// seconds, or milliseconds when it is too large for seconds. Text mattn can
// not parse, which it reads as year 1 without an error, is refused.
func convertTime(v any) converted {
switch x := v.(type) {
case string:
s := strings.TrimSuffix(x, "Z")
for _, format := range sqlite3.SQLiteTimestampFormats {
if t, err := time.ParseInLocation(format, s, time.UTC); err == nil {
return converted{value: t.UTC(), size: 8, truncated: t.Nanosecond()%1000 != 0}
}
}
return converted{invalid: invalidTime}
case int64:
var t time.Time
if x > 1e12 || x < -1e12 {
t = time.Unix(0, x*int64(time.Millisecond))
} else {
t = time.Unix(x, 0)
}
return converted{value: t.UTC(), size: 8}
}
return converted{invalid: invalidTime}
}
// convertBool reads a bool as the application does: mattn turns an integer
// of a column declared boolean into value > 0, any other value goes through
// the database/sql bool rule (0, 1, true, false, t, f and the like)
func convertBool(c *column, v any) converted {
if x, ok := v.(int64); ok && c.srcType == "boolean" {
return converted{value: x > 0, size: 1}
}
b, err := driver.Bool.ConvertValue(v)
if err != nil {
return converted{invalid: invalidBool}
}
return converted{value: b, size: 1}
}
// convertInt reads an integer, a text holding one or a real without a
// fraction, within the range of the target column
func convertInt(c *column, v any) converted {
var n int64
switch x := v.(type) {
case int64:
n = x
case string:
p, err := strconv.ParseInt(x, 10, 64)
if err != nil {
return converted{invalid: invalidInt}
}
n = p
case float64:
if x != math.Trunc(x) || x >= math.MaxInt64 || x < math.MinInt64 {
return converted{invalid: invalidInt}
}
n = int64(x)
default:
return converted{invalid: invalidInt}
}
if c.intBits < 64 {
limit := int64(1) << (c.intBits - 1)
if n >= limit || n < -limit {
return converted{invalid: invalidRange}
}
}
return converted{value: n, size: 8}
}
// convertText reads text as the string scan of the application does, then
// cleans it as the postgres dialector cleans every write (dbengine.CleanText)
// and checks the character limit of a varchar column
func convertText(c *column, v any) converted {
var s string
switch x := v.(type) {
case string:
s = x
case []byte:
s = string(x)
case int64:
s = strconv.FormatInt(x, 10)
case float64:
s = strconv.FormatFloat(x, 'g', -1, 64)
default:
return converted{invalid: invalidBytes}
}
cleaned := dbengine.CleanText(s)
out := converted{value: cleaned, size: len(cleaned)}
if cleaned != s {
out.cleaned = true
out.raw = s
}
if c.maxLen > 0 && utf8.RuneCountInString(cleaned) > c.maxLen {
return converted{invalid: invalidTooLong}
}
return out
}
// convertFloat reads a number or a text holding one
func convertFloat(v any) converted {
switch x := v.(type) {
case int64:
return converted{value: float64(x), size: 8}
case float64:
return converted{value: x, size: 8}
case string:
f, err := strconv.ParseFloat(strings.TrimSpace(x), 64)
if err != nil {
return converted{invalid: invalidFloat}
}
return converted{value: f, size: 8}
}
return converted{invalid: invalidFloat}
}
// convertBytes reads a blob or a text as bytes
func convertBytes(v any) converted {
switch x := v.(type) {
case []byte:
return converted{value: x, size: len(x)}
case string:
return converted{value: []byte(x), size: len(x)}
}
return converted{invalid: invalidBytes}
}