Add support for column alias.
This commit is contained in:
parent
83a8b2b70f
commit
31736ec13e
2 changed files with 49 additions and 1 deletions
|
|
@ -16,6 +16,8 @@ type Column interface {
|
|||
isProjectionInterface
|
||||
isExpressionInterface
|
||||
|
||||
As(alias string) Column
|
||||
|
||||
Name() string
|
||||
// Serialization for use in column lists
|
||||
SerializeSqlForColumnList(out *bytes.Buffer) error
|
||||
|
|
@ -74,6 +76,14 @@ type baseColumn struct {
|
|||
name string
|
||||
nullable NullableColumn
|
||||
table string
|
||||
alias string
|
||||
}
|
||||
|
||||
func (c *baseColumn) As(alias string) Column {
|
||||
newBaseColumn := *c
|
||||
newBaseColumn.alias = alias
|
||||
|
||||
return &newBaseColumn
|
||||
}
|
||||
|
||||
func (c *baseColumn) Name() string {
|
||||
|
|
@ -89,7 +99,9 @@ func (c *baseColumn) SerializeSqlForColumnList(out *bytes.Buffer) error {
|
|||
|
||||
c.SerializeSql(out)
|
||||
|
||||
if c.table != "" {
|
||||
if c.alias != "" {
|
||||
_, _ = out.WriteString(" AS \"" + c.alias + "\"")
|
||||
} else if c.table != "" {
|
||||
_, _ = out.WriteString(" AS \"" + c.table + "." + c.name + "\"")
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -328,6 +328,42 @@ func TestSelectSelfJoin(t *testing.T) {
|
|||
assert.Equal(t, len(theSameLengthFilms), 6972)
|
||||
}
|
||||
|
||||
func TestSelectAliasColumn(t *testing.T) {
|
||||
f1 := Film.As("f1")
|
||||
f2 := Film.As("f2")
|
||||
|
||||
type thesameLengthFilms struct {
|
||||
Title1 string
|
||||
Title2 string
|
||||
Length int16
|
||||
}
|
||||
|
||||
query := f1.
|
||||
InnerJoinOn(f2, f1.FilmID.Neq(f2.FilmID).And(f1.Length.Eq(f2.Length))).
|
||||
Select(f1.Title.As("thesame_length_films.title1"),
|
||||
f2.Title.As("thesame_length_films.title2"),
|
||||
f1.Length.As("thesame_length_films.length")).
|
||||
OrderBy(f1.Length.Asc()).
|
||||
Limit(1000)
|
||||
|
||||
queryStr, err := query.String()
|
||||
|
||||
assert.NilError(t, err)
|
||||
|
||||
fmt.Println(queryStr)
|
||||
|
||||
films := []thesameLengthFilms{}
|
||||
|
||||
err = query.Execute(db, &films)
|
||||
|
||||
assert.NilError(t, err)
|
||||
|
||||
//spew.Dump(films)
|
||||
|
||||
assert.Equal(t, len(films), 1000)
|
||||
assert.DeepEqual(t, films[0], thesameLengthFilms{"Ridgemont Submarine", "Iron Moon", 46})
|
||||
}
|
||||
|
||||
func int32Ptr(i int32) *int32 {
|
||||
return &i
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue