From 31736ec13e472a759dd64b4678438dc006d501c7 Mon Sep 17 00:00:00 2001 From: sub0Zero Date: Sun, 17 Mar 2019 20:41:03 +0100 Subject: [PATCH] Add support for column alias. --- sqlbuilder/column.go | 14 +++++++++++++- tests/generator_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/sqlbuilder/column.go b/sqlbuilder/column.go index aff18ba..e6ebf6c 100644 --- a/sqlbuilder/column.go +++ b/sqlbuilder/column.go @@ -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 + "\"") } diff --git a/tests/generator_test.go b/tests/generator_test.go index 894d8f6..9a4450e 100644 --- a/tests/generator_test.go +++ b/tests/generator_test.go @@ -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 }