diff options
| author | Anhgelus Morhtuuzh <william@herges.fr> | 2026-03-09 18:47:40 +0100 |
|---|---|---|
| committer | Anhgelus Morhtuuzh <william@herges.fr> | 2026-03-09 18:47:40 +0100 |
| commit | 9c3f1ea5ffe9ad70caf306faff7a3e3948cef6ab (patch) | |
| tree | d7931c65a40a7bf22764473c0dd330f83a4bc071 /common | |
| parent | 6e92feaba23a4992e0ec4b529660921a6bcb492a (diff) | |
feat(config): preload role reactfeat/leave-gorm
Diffstat (limited to 'common')
| -rw-r--r-- | common/db.go | 30 |
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 +} |
