60 lines
1.0 KiB
Go
60 lines
1.0 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
)
|
|
|
|
type Role struct {
|
|
ID int64 `json:"id"`
|
|
Name string `json:"name"`
|
|
Level int64 `json:"level"`
|
|
Description string `json:"description"`
|
|
}
|
|
|
|
type RoleStore struct {
|
|
db *sql.DB
|
|
|
|
getByNameStmt *sql.Stmt
|
|
}
|
|
|
|
func NewRoleStore(db *sql.DB) (*RoleStore, error) {
|
|
getByNameStmt, err := db.PrepareContext(context.Background(), `
|
|
SELECT id, name, level, description
|
|
FROM roles
|
|
WHERE name = $1
|
|
`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &RoleStore{
|
|
db: db,
|
|
getByNameStmt: getByNameStmt,
|
|
}, nil
|
|
}
|
|
|
|
func (s *RoleStore) GetByName(ctx context.Context, name string) (*Role, error) {
|
|
ctx, cancel := context.WithTimeout(ctx, QueryTimeout)
|
|
defer cancel()
|
|
|
|
role := &Role{}
|
|
|
|
err := s.getByNameStmt.QueryRowContext(ctx, name).Scan(
|
|
&role.ID,
|
|
&role.Name,
|
|
&role.Level,
|
|
&role.Description,
|
|
)
|
|
if err != nil {
|
|
switch err {
|
|
case sql.ErrNoRows:
|
|
return nil, ErrNotFound
|
|
default:
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return role, nil
|
|
}
|