aboutsummaryrefslogtreecommitdiff
path: root/common/db.go
diff options
context:
space:
mode:
Diffstat (limited to 'common/db.go')
-rw-r--r--common/db.go30
1 files changed, 30 insertions, 0 deletions
diff --git a/common/db.go b/common/db.go
index 76e39a2..992ca37 100644
--- a/common/db.go
+++ b/common/db.go
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"embed"
+ "errors"
"fmt"
"log/slog"
"path"
@@ -55,3 +56,32 @@ func Migrate(ctx context.Context, log *slog.Logger, db *sql.DB, migrations embed
}
return nil
}
+
+type Loadable interface {
+ Load(context.Context, *sql.DB, *sql.Rows) error
+}
+
+func GetValues[T Loadable](ctx context.Context, db *sql.DB, table, data, where string, args ...any) ([]T, error) {
+ arr := make([]T, 0)
+ rows, err := db.QueryContext(
+ ctx,
+ fmt.Sprintf(`SELECT %s FROM %s WHERE %s`, data, table, where),
+ args...,
+ )
+ if err != nil {
+ if !errors.Is(err, sql.ErrNoRows) {
+ return arr, err
+ }
+ } else {
+ defer rows.Close()
+ for rows.Next() {
+ var v T
+ err = v.Load(ctx, db, rows)
+ if err != nil {
+ return nil, err
+ }
+ arr = append(arr, v)
+ }
+ }
+ return arr, nil
+}