dialect/sql: add support for setting the table_schema in select_table (#1001)

This commit is contained in:
Ariel Mashraki
2020-11-30 13:36:49 +02:00
committed by GitHub
parent d0b41ab0f6
commit 1270ba1bd8
2 changed files with 32 additions and 8 deletions

View File

@@ -1382,9 +1382,10 @@ type TableView interface {
// SelectTable is a table selector.
type SelectTable struct {
Builder
quote bool
name string
as string
as string
name string
schema string
quote bool
}
// Table returns a new table selector.
@@ -1396,6 +1397,12 @@ func Table(name string) *SelectTable {
return &SelectTable{quote: true, name: name}
}
// Schema sets the schema name of the table.
func (s *SelectTable) Schema(name string) *SelectTable {
s.schema = name
return s
}
// As adds the AS clause to the table selector.
func (s *SelectTable) As(alias string) *SelectTable {
s.as = alias
@@ -1409,9 +1416,10 @@ func (s *SelectTable) C(column string) string {
name = s.as
}
b := &Builder{dialect: s.dialect}
b.Ident(name)
b.WriteByte('.')
b.Ident(column)
if s.schema != "" && s.as == "" {
b.Ident(s.schema).WriteByte('.')
}
b.Ident(name).WriteByte('.').Ident(column)
return b.String()
}
@@ -1438,6 +1446,9 @@ func (s *SelectTable) ref() string {
return s.name
}
b := &Builder{dialect: s.dialect}
if s.schema != "" {
b.Ident(s.schema).WriteByte('.')
}
b.Ident(s.name)
if s.as != "" {
b.WriteString(" AS ")

View File

@@ -680,8 +680,8 @@ func TestBuilder(t *testing.T) {
return Select(t1.C("id"), As(Count("`*`"), "group_count")).
From(t1).
LeftJoin(t2).
OnP(P(func(builder *Builder) {
builder.Ident(t1.C("id")).WriteOp(OpEQ).Ident(t2.C("user_id"))
OnP(P(func(b *Builder) {
b.Ident(t1.C("id")).WriteOp(OpEQ).Ident(t2.C("user_id"))
})).
GroupBy(t1.C("id")).Clone()
}(),
@@ -1271,6 +1271,19 @@ WHERE
wantQuery: `SELECT * FROM "test" WHERE nlevel("path") > $1`,
wantArgs: []interface{}{1},
},
{
input: func() Querier {
t1, t2 := Table("users").Schema("s1"), Table("pets").Schema("s2")
return Select("*").
From(t1).Join(t2).
OnP(P(func(b *Builder) {
b.Ident(t1.C("id")).WriteOp(OpEQ).Ident(t2.C("owner_id"))
})).
Where(EQ(t2.C("name"), "pedro"))
}(),
wantQuery: "SELECT * FROM `s1`.`users` JOIN `s2`.`pets` AS `t0` ON `s1`.`users`.`id` = `t0`.`owner_id` WHERE `t0`.`name` = ?",
wantArgs: []interface{}{"pedro"},
},
}
for i, tt := range tests {
t.Run(strconv.Itoa(i), func(t *testing.T) {