use group by instead of distinct when possible
This commit is contained in:
18
tools/dbutils/select.go
Normal file
18
tools/dbutils/select.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package dbutils
|
||||
|
||||
import "regexp"
|
||||
|
||||
// Regexp for columns and tables (the same as the one in dbx).
|
||||
var selectRegex = regexp.MustCompile(`(?i:\s+as\s+|\s+)([\w\-_\.]+)$`)
|
||||
|
||||
// AliasOrIdentifier returns the alias from a column or table identifier,
|
||||
// Returns the identifier unmodified if no alias was found.
|
||||
func AliasOrIdentifier(columnOrTableIdentifier string) string {
|
||||
matches := selectRegex.FindStringSubmatch(columnOrTableIdentifier)
|
||||
|
||||
if len(matches) > 0 && matches[1] != "" {
|
||||
return matches[1]
|
||||
}
|
||||
|
||||
return columnOrTableIdentifier
|
||||
}
|
||||
38
tools/dbutils/select_test.go
Normal file
38
tools/dbutils/select_test.go
Normal file
@@ -0,0 +1,38 @@
|
||||
package dbutils_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/pocketbase/pocketbase/tools/dbutils"
|
||||
)
|
||||
|
||||
func TestAliasOrIdentifier(t *testing.T) {
|
||||
scenarios := []struct {
|
||||
value string
|
||||
expected string
|
||||
}{
|
||||
{"", ""},
|
||||
{"abc", "abc"},
|
||||
{"abc ", "abc "}, // return unmodified
|
||||
{"abc.def", "abc.def"},
|
||||
{"abc.123 def", "def"},
|
||||
{"abc.123 as def.456", "def.456"},
|
||||
{"(abc) def", "def"},
|
||||
{"(abc) as def", "def"},
|
||||
{"abc def", "def"},
|
||||
{"abc as def", "def"},
|
||||
// technically invalid identifier but consistent with the dbx regex matching
|
||||
{"a b c d", "d"},
|
||||
{"a b c as d", "d"},
|
||||
}
|
||||
|
||||
for _, s := range scenarios {
|
||||
t.Run(s.value, func(t *testing.T) {
|
||||
result := dbutils.AliasOrIdentifier(s.value)
|
||||
|
||||
if result != s.expected {
|
||||
t.Fatalf("Expected\n%v\ngot\n%v", s.expected, result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user