FIX: Handle NULL transports array with custom StringArray type

This commit is contained in:
Leon Bösche
2026-01-11 22:53:24 +01:00
parent 6a4cd8c672
commit c330381281

View File

@@ -3,11 +3,12 @@ package database
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"log"
"time"
"github.com/google/uuid"
"github.com/lib/pq"
)
type DB struct {
@@ -18,6 +19,49 @@ func New(db *sql.DB) *DB {
return &DB{DB: db}
}
// StringArray handles nullable string arrays from PostgreSQL
type StringArray []string
// Scan handles NULL values properly
func (sa *StringArray) Scan(value interface{}) error {
if value == nil {
*sa = StringArray{}
return nil
}
// Handle byte slice from PostgreSQL array
if bytes, ok := value.([]byte); ok {
var arr []string
if err := json.Unmarshal(bytes, &arr); err != nil {
// If JSON parse fails, try as raw string
*sa = StringArray{string(bytes)}
return nil
}
*sa = StringArray(arr)
return nil
}
// Handle string directly
if str, ok := value.(string); ok {
if str == "" {
*sa = StringArray{}
return nil
}
*sa = StringArray{str}
return nil
}
return nil
}
// Value implements the driver.Valuer interface
func (sa StringArray) Value() (driver.Value, error) {
if len(sa) == 0 {
return nil, nil
}
return json.Marshal(sa)
}
type User struct {
ID uuid.UUID
Email string
@@ -36,7 +80,7 @@ type Credential struct {
SignCount int64
CreatedAt time.Time
LastUsedAt *time.Time
Transports pq.StringArray
Transports StringArray
}
type AuthChallenge struct {