Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alias issue #70

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions builder/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,19 @@ func (b *Buffer) WriteEscape(value string) {
b.WriteString(b.escape("", value))
}

func (b Buffer) escapeSchema(table string) string {
if b.AllowTableSchema && strings.IndexByte(table, '.') >= 0 {
parts := strings.Split(table, ".")
for i, part := range parts {
part = strings.TrimSpace(part)
parts[i] = b.Quoter.ID(part)
}
return strings.Join(parts, ".")
} else {
return b.Quoter.ID(strings.ReplaceAll(strings.TrimSpace(table), ".", "_"))
}
}

func (b Buffer) escape(table, value string) string {
if table == "" && value == "*" {
return value
Expand All @@ -134,17 +147,9 @@ func (b Buffer) escape(table, value string) string {
var escaped_table string
if table != "" {
if i := strings.Index(strings.ToLower(table), " as "); i > -1 {
return b.escape(table[:i], "") + " AS " + b.Quoter.ID(table[i+4:])
}
if b.AllowTableSchema && strings.IndexByte(table, '.') >= 0 {
parts := strings.Split(table, ".")
for i, part := range parts {
part = strings.TrimSpace(part)
parts[i] = b.Quoter.ID(part)
}
escaped_table = strings.Join(parts, ".")
escaped_table = b.escapeSchema(table[:i]) + " AS " + b.Quoter.ID(strings.TrimSpace(table[i+4:]))
} else {
escaped_table = b.Quoter.ID(strings.ReplaceAll(table, ".", "_"))
escaped_table = b.escapeSchema(table)
}
}

Expand Down
8 changes: 8 additions & 0 deletions builder/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@ func TestQuery_Build(t *testing.T) {
result: "SELECT `users`.* FROM `users` FOR UPDATE;",
query: rel.From("users").Lock("FOR UPDATE"),
},
{
result: "SELECT `c`.`id`,`c`.`name` FROM `contacts` AS `c`;",
query: rel.Select("c.id", "c.name").From("contacts as c"),
},
}

for _, test := range tests {
Expand Down Expand Up @@ -185,6 +189,10 @@ func TestQuery_Build_ordinal(t *testing.T) {
result: "SELECT \"users\".* FROM \"users\" FOR UPDATE;",
query: rel.From("users").Lock("FOR UPDATE"),
},
{
result: "SELECT \"c\".\"id\",\"c\".\"name\" FROM \"contacts\" AS \"c\";",
query: rel.Select("c.id", "c.name").From("contacts as c"),
},
}

for _, test := range tests {
Expand Down
Loading