coverage/db/query.go

76 lines
1.7 KiB
Go

package db
import (
"database/sql"
"errors"
"strconv"
)
var ErrNoData = errors.New("no badge found with the provided data")
type CoverageData struct {
Namespace string
Project string
Coverage float64
HTML string
}
// QueryByBranch returns CoverageData for the provided branch for the project.
// If there is no such data, it returns ErrNoData.
func QueryByBranch(namespace, project, branch string) (CoverageData, error) {
result, err := db.Query(`SELECT coverage,html FROM badge WHERE
namespace=? AND
project_name=? AND
branch=?`,
namespace, project, branch)
if err != nil {
return CoverageData{}, err
}
return parseRows(result, namespace, project)
}
// QueryByBranch returns CoverageData for the provided pull request of the project.
// If there is no such data, it returns ErrNoData.
func QueryByPull(namespace, project, pullStr string) (CoverageData, error) {
pull, err := strconv.Atoi(pullStr)
if err != nil {
return CoverageData{}, ErrNoData
}
result, err := db.Query(`SELECT coverage, html FROM badge WHERE
namespace=? AND
project_name=? AND
pull=?`,
namespace, project, pull)
if err != nil {
return CoverageData{}, err
}
return parseRows(result, namespace, project)
}
func parseRows(result *sql.Rows, namespace, project string) (CoverageData, error) {
if !result.Next() {
return CoverageData{}, ErrNoData
}
var coverage float64
var html string
err := result.Scan(&coverage, &html)
if err != nil {
return CoverageData{}, err
}
if err = result.Close(); err != nil {
return CoverageData{}, ErrNoData
}
return CoverageData{
Namespace: namespace,
Project: project,
Coverage: coverage,
HTML: html,
}, nil
}