From 20b616768dd665c3ec2de0d29a491597de3bb83e Mon Sep 17 00:00:00 2001 From: Andrey Elenskiy Date: Sun, 25 Jul 2021 12:14:32 -0700 Subject: [PATCH] dialect/sql: return selector's alias as a table name (#1745) In case selector's from clause has *Selector instead of *SelectTable, TableName() function (used for column checking) will panic. Instead, return selector's alias which is useful if the query returns a table with the same schema as some entity. Essentially, this allows materialized views to reuse the same entity code as long as columns are matching. --- dialect/sql/builder.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/dialect/sql/builder.go b/dialect/sql/builder.go index d820510e6..c683d8d74 100644 --- a/dialect/sql/builder.go +++ b/dialect/sql/builder.go @@ -1946,9 +1946,16 @@ func (s *Selector) Table() *SelectTable { return s.from.(*SelectTable) } -// TableName returns the name of the selected table. +// TableName returns the name of the selected table or alias of selector. func (s *Selector) TableName() string { - return s.Table().name + switch view := s.from.(type) { + case *SelectTable: + return view.name + case *Selector: + return view.as + default: + panic(fmt.Sprintf("unhandled TableView type %T", s.from)) + } } // Join appends a `JOIN` clause to the statement.