SimpleCloudNotifier/server/models/utils.go

64 lines
1.1 KiB
Go
Raw Normal View History

2022-11-18 21:25:40 +01:00
package models
import (
"database/sql"
"errors"
"github.com/jmoiron/sqlx"
2022-11-18 21:25:40 +01:00
"gogs.mikescher.com/BlackForestBytes/goext/langext"
"time"
)
func timeOptFmt(t *time.Time, fmt string) *string {
if t == nil {
return nil
} else {
return langext.Ptr(t.Format(fmt))
}
}
2022-11-18 23:12:37 +01:00
func timeOptFromMilli(millis *int64) *time.Time {
if millis == nil {
return nil
}
return langext.Ptr(time.UnixMilli(*millis))
}
func scanSingle[TData any](rows *sqlx.Rows) (TData, error) {
if rows.Next() {
var data TData
err := rows.StructScan(&data)
if err != nil {
return *new(TData), err
}
if rows.Next() {
2022-12-08 11:31:52 +01:00
_ = rows.Close()
return *new(TData), errors.New("sql returned more than onw row")
}
2022-12-08 11:31:52 +01:00
err = rows.Close()
if err != nil {
return *new(TData), err
}
return data, nil
} else {
2022-12-08 11:31:52 +01:00
_ = rows.Close()
return *new(TData), sql.ErrNoRows
}
}
func scanAll[TData any](rows *sqlx.Rows) ([]TData, error) {
res := make([]TData, 0)
for rows.Next() {
var data TData
err := rows.StructScan(&data)
if err != nil {
return nil, err
}
res = append(res, data)
}
2022-12-08 11:31:52 +01:00
err := rows.Close()
if err != nil {
return nil, err
}
return res, nil
}