Storage: Add support for sortBy selector (#80680)

* add support for sortBy field selector

* use label selectors instead of field selectors

* set entity_labels on create & update

* make entity server integration tests work

* test fixes

* be more consistent with handling of empty body, meta or status

* workaround for database is locked errors during migration

* fix double import of sqlite3

* rename functions and tidy up

* refactor update

* disable integration tests until we can fix the database locking issue
This commit is contained in:
Dan Cech
2024-02-07 15:05:10 -05:00
committed by GitHub
parent bb6db46ecc
commit 1f1461734c
13 changed files with 429 additions and 202 deletions
@@ -6,15 +6,33 @@ import (
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
)
type Direction int
const (
Ascending Direction = iota
Descending
)
func (d Direction) String() string {
if d == Descending {
return "DESC"
}
return "ASC"
}
type selectQuery struct {
dialect migrator.Dialect
fields []string // SELECT xyz
from string // FROM object
offset int64
limit int64
oneExtra bool
where []string
args []any
orderBy []string
direction []Direction
}
func (q *selectQuery) addWhere(f string, val ...any) {
@@ -53,6 +71,11 @@ func (q *selectQuery) addWhereIn(f string, vals []string) {
}
}
func (q *selectQuery) addOrderBy(field string, direction Direction) {
q.orderBy = append(q.orderBy, field)
q.direction = append(q.direction, direction)
}
func (q *selectQuery) toQuery() (string, []any) {
args := q.args
sb := strings.Builder{}
@@ -77,17 +100,27 @@ func (q *selectQuery) toQuery() (string, []any) {
}
}
if q.limit > 0 || q.oneExtra {
limit := q.limit
if limit < 1 {
limit = 20
q.limit = limit
if len(q.orderBy) > 0 && len(q.direction) == len(q.orderBy) {
sb.WriteString(" ORDER BY ")
for i, f := range q.orderBy {
if i > 0 {
sb.WriteString(",")
}
sb.WriteString(q.dialect.Quote(f))
sb.WriteString(" ")
sb.WriteString(q.direction[i].String())
}
if q.oneExtra {
limit = limit + 1
}
sb.WriteString(" LIMIT ?")
args = append(args, limit)
}
limit := q.limit
if limit < 1 {
limit = 20
q.limit = limit
}
if q.oneExtra {
limit = limit + 1
}
sb.WriteString(q.dialect.LimitOffset(limit, q.offset))
return sb.String(), args
}