From 5cf67c444088882e4c4834f85df481a6ac5b301a Mon Sep 17 00:00:00 2001 From: Andras Banki-Horvath Date: Wed, 22 Nov 2023 16:49:20 +0100 Subject: [PATCH] sqldb: add utility functions for SQL NULL types --- sqldb/sqlutils.go | 54 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 sqldb/sqlutils.go diff --git a/sqldb/sqlutils.go b/sqldb/sqlutils.go new file mode 100644 index 000000000..b71c5f00c --- /dev/null +++ b/sqldb/sqlutils.go @@ -0,0 +1,54 @@ +package sqldb + +import ( + "database/sql" + "time" + + "golang.org/x/exp/constraints" +) + +// 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. +func sqlInt32[T constraints.Integer](num T) sql.NullInt32 { + return sql.NullInt32{ + Int32: int32(num), + Valid: true, + } +} + +// 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. +func sqlInt64[T constraints.Integer](num T) sql.NullInt64 { + return sql.NullInt64{ + Int64: int64(num), + Valid: true, + } +} + +// sqlStr turns a string into the NullString that sql/sqlc uses when a string +// can be permitted to be NULL. +func sqlStr(s string) sql.NullString { + if s == "" { + return sql.NullString{} + } + + return sql.NullString{ + String: s, + Valid: true, + } +} + +// sqlTime turns a time.Time into the NullTime that sql/sqlc uses when a time +// can be permitted to be NULL. +func sqlTime(t time.Time) sql.NullTime { + return sql.NullTime{ + Time: t, + Valid: true, + } +}