sqldb: add SQLStrValid helper

The SQL* helpers are meant to always set the `Valid` field of the
sql.Null* type to true. Otherwise they cannot be used to set a valid,
empty field. However, we dont want to break the behaviour of the
existing SQLStr helper and so this commit adds a new helper with the
desired functionality.
This commit is contained in:
Elle Mouton
2025-09-03 14:47:44 +02:00
parent ea6cc8154f
commit 40b279687f
3 changed files with 19 additions and 4 deletions

View File

@@ -1380,8 +1380,8 @@ func insertNodeSQLMig(ctx context.Context, db SQLQueries,
if node.HaveNodeAnnouncement {
params.LastUpdate = sqldb.SQLInt64(node.LastUpdate.Unix())
params.Color = sqldb.SQLStr(EncodeHexColor(node.Color))
params.Alias = sqldb.SQLStr(node.Alias)
params.Color = sqldb.SQLStrValid(EncodeHexColor(node.Color))
params.Alias = sqldb.SQLStrValid(node.Alias)
params.Signature = node.AuthSigBytes
}

View File

@@ -3391,8 +3391,8 @@ func upsertNode(ctx context.Context, db SQLQueries,
if node.HaveNodeAnnouncement {
params.LastUpdate = sqldb.SQLInt64(node.LastUpdate.Unix())
params.Color = sqldb.SQLStr(EncodeHexColor(node.Color))
params.Alias = sqldb.SQLStr(node.Alias)
params.Color = sqldb.SQLStrValid(EncodeHexColor(node.Color))
params.Alias = sqldb.SQLStrValid(node.Alias)
params.Signature = node.AuthSigBytes
}

View File

@@ -49,6 +49,10 @@ func SQLInt64[T constraints.Integer](num T) sql.NullInt64 {
// SQLStr turns a string into the NullString that sql/sqlc uses when a string
// can be permitted to be NULL.
//
// NOTE: If the input string is empty, it returns a NullString with Valid set to
// false. If this is not the desired behavior, consider using SQLStrValid
// instead.
func SQLStr(s string) sql.NullString {
if s == "" {
return sql.NullString{}
@@ -60,6 +64,17 @@ func SQLStr(s string) sql.NullString {
}
}
// SQLStrValid turns a string into the NullString that sql/sqlc uses when a
// string can be permitted to be NULL.
//
// NOTE: Valid is always set to true, even if the input string is empty.
func SQLStrValid(s string) 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 {