lnd/sqldb/sqlutils.go

78 lines
2 KiB
Go
Raw Normal View History

package sqldb
import (
"database/sql"
"time"
"golang.org/x/exp/constraints"
)
// NoOpReset is a no-op function that can be used as a default
// reset function ExecTx calls.
var NoOpReset = func() {}
2025-06-30 12:28:55 +02:00
// SQLInt16 turns a numerical integer type into the NullInt16 that sql/sqlc
// uses when an integer field can be permitted to be NULL.
//
// We use this constraints.Integer constraint here which maps to all signed and
// unsigned integer types.
func SQLInt16[T constraints.Integer](num T) sql.NullInt16 {
return sql.NullInt16{
Int16: int16(num),
Valid: true,
}
}
2024-03-29 10:17:57 +01:00
// SQLInt32 turns a numerical integer type into the NullInt32 that sql/sqlc
// uses when an integer field can be permitted to be NULL.
//
// We use this constraints.Integer constraint here which maps to all signed and
// unsigned integer types.
2024-03-29 10:17:57 +01:00
func SQLInt32[T constraints.Integer](num T) sql.NullInt32 {
return sql.NullInt32{
Int32: int32(num),
Valid: true,
}
}
2024-03-29 10:17:57 +01:00
// SQLInt64 turns a numerical integer type into the NullInt64 that sql/sqlc
// uses when an integer field can be permitted to be NULL.
//
// We use this constraints.Integer constraint here which maps to all signed and
// unsigned integer types.
2024-03-29 10:17:57 +01:00
func SQLInt64[T constraints.Integer](num T) sql.NullInt64 {
return sql.NullInt64{
Int64: int64(num),
Valid: true,
}
}
2024-03-29 10:17:57 +01:00
// SQLStr turns a string into the NullString that sql/sqlc uses when a string
// can be permitted to be NULL.
2024-03-29 10:17:57 +01:00
func SQLStr(s string) sql.NullString {
if s == "" {
return sql.NullString{}
}
return sql.NullString{
String: s,
Valid: true,
}
}
2024-03-29 10:17:57 +01:00
// SQLTime turns a time.Time into the NullTime that sql/sqlc uses when a time
// can be permitted to be NULL.
2024-03-29 10:17:57 +01:00
func SQLTime(t time.Time) sql.NullTime {
return sql.NullTime{
Time: t,
Valid: true,
}
}
// ExtractSqlInt16 turns a NullInt16 into a numerical type. This can be useful
// when reading directly from the database, as this function handles extracting
// the inner value from the "option"-like struct.
func ExtractSqlInt16[T constraints.Integer](num sql.NullInt16) T {
return T(num.Int16)
}