grafana/pkg/infra/db/sqlbuilder.go

86 lines
2.3 KiB
Go
Raw Normal View History

package db
2018-02-07 10:54:21 -06:00
import (
"bytes"
"github.com/grafana/grafana/pkg/services/auth/identity"
"github.com/grafana/grafana/pkg/services/dashboards"
"github.com/grafana/grafana/pkg/services/featuremgmt"
"github.com/grafana/grafana/pkg/services/sqlstore/migrator"
"github.com/grafana/grafana/pkg/services/sqlstore/permissions"
"github.com/grafana/grafana/pkg/setting"
2018-02-07 10:54:21 -06:00
)
func NewSqlBuilder(cfg *setting.Cfg, features featuremgmt.FeatureToggles, dialect migrator.Dialect, recursiveQueriesAreSupported bool) SQLBuilder {
return SQLBuilder{cfg: cfg, features: features, dialect: dialect, recursiveQueriesAreSupported: recursiveQueriesAreSupported}
}
type SQLBuilder struct {
cfg *setting.Cfg
features featuremgmt.FeatureToggles
sql bytes.Buffer
params []any
leftJoin string
recQry string
recQryParams []any
recursiveQueriesAreSupported bool
dialect migrator.Dialect
2018-02-07 10:54:21 -06:00
}
func (sb *SQLBuilder) Write(sql string, params ...any) {
sb.sql.WriteString(sql)
if len(params) > 0 {
sb.params = append(sb.params, params...)
}
}
func (sb *SQLBuilder) GetSQLString() string {
if sb.recQry == "" {
return sb.sql.String()
}
var bf bytes.Buffer
bf.WriteString(sb.recQry)
bf.WriteString(sb.sql.String())
if sb.leftJoin != "" {
bf.WriteString(" LEFT OUTER JOIN " + sb.leftJoin)
}
return bf.String()
}
func (sb *SQLBuilder) GetParams() []any {
if len(sb.recQryParams) == 0 {
return sb.params
}
sb.params = append(sb.recQryParams, sb.params...)
return sb.params
}
func (sb *SQLBuilder) AddParams(params ...any) {
sb.params = append(sb.params, params...)
}
func (sb *SQLBuilder) WriteDashboardPermissionFilter(user identity.Requester, permission dashboards.PermissionType, queryType string) {
var (
sql string
params []any
recQry string
recQryParams []any
leftJoin string
)
filterRBAC := permissions.NewAccessControlDashboardPermissionFilter(user, permission, queryType, sb.features, sb.recursiveQueriesAreSupported)
leftJoin = filterRBAC.LeftJoin()
sql, params = filterRBAC.Where()
recQry, recQryParams = filterRBAC.With()
2018-02-07 10:54:21 -06:00
sb.sql.WriteString(" AND " + sql)
sb.params = append(sb.params, params...)
sb.recQry = recQry
sb.recQryParams = recQryParams
sb.leftJoin = leftJoin
2018-02-07 10:54:21 -06:00
}