mirror of
https://github.com/coder/coder.git
synced 2026-09-24 15:04:27 +08:00
chore: Implement joins with golang templates (#6429)
* feat: Implement view for workspace builds to include rbac info * Removes the need to fetch the workspace to run an rbac check. * chore: Use workspace build as RBAC object * chore: Use golang templates instead of sqlc files
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
package sqlxqueries
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"embed"
|
||||
"sync"
|
||||
"text/template"
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
)
|
||||
|
||||
//go:embed *.gosql
|
||||
var sqlxQueries embed.FS
|
||||
|
||||
var (
|
||||
// Only parse the queries once.
|
||||
once sync.Once
|
||||
cached *template.Template
|
||||
//nolint:errname
|
||||
cachedError error
|
||||
)
|
||||
|
||||
// LoadQueries parses the embedded queries and returns the template.
|
||||
// Results are cached.
|
||||
func LoadQueries() (*template.Template, error) {
|
||||
once.Do(func() {
|
||||
tpls, err := template.New("").
|
||||
Funcs(template.FuncMap{
|
||||
"int32": func(i int) int32 { return int32(i) },
|
||||
}).ParseFS(sqlxQueries, "*.gosql")
|
||||
if err != nil {
|
||||
cachedError = xerrors.Errorf("developer error parse sqlx queries: %w", err)
|
||||
return
|
||||
}
|
||||
cached = tpls
|
||||
})
|
||||
|
||||
return cached, cachedError
|
||||
}
|
||||
|
||||
// query executes the named template with the given data and returns the result.
|
||||
// The returned query string is SQL.
|
||||
func query(name string, data interface{}) (string, error) {
|
||||
tpls, err := LoadQueries()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var out bytes.Buffer
|
||||
err = tpls.ExecuteTemplate(&out, name, data)
|
||||
if err != nil {
|
||||
return "", xerrors.Errorf("execute template %s: %w", name, err)
|
||||
}
|
||||
return out.String(), nil
|
||||
}
|
||||
Reference in New Issue
Block a user