Skip to content

Commit

Permalink
Include table_schema when query from INFORMATION_SCHEMA for mysql
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Apr 25, 2014
1 parent 66e6c9a commit 6dc332e
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gorm

import (
"fmt"
"strings"

"reflect"
)
Expand Down Expand Up @@ -68,18 +69,30 @@ func (s *mysql) Quote(key string) string {
return fmt.Sprintf("`%s`", key)
}

func (s *mysql) databaseName(scope *Scope) string {
from := strings.Index(scope.db.parent.source, "/") + 1
to := strings.Index(scope.db.parent.source, "?")
if to == -1 {
to = len(scope.db.parent.source)
}
return scope.db.parent.source[from:to]
}

func (s *mysql) HasTable(scope *Scope, tableName string) bool {
var count int
newScope := scope.New(nil)
newScope.Raw(fmt.Sprintf("SELECT count(*) FROM INFORMATION_SCHEMA.tables where table_name = %v", newScope.AddToVars(tableName)))
newScope.Raw(fmt.Sprintf("SELECT count(*) FROM INFORMATION_SCHEMA.tables where table_name = %v AND table_schema = %v",
newScope.AddToVars(tableName),
newScope.AddToVars(s.databaseName(scope))))
newScope.DB().QueryRow(newScope.Sql, newScope.SqlVars...).Scan(&count)
return count > 0
}

func (s *mysql) HasColumn(scope *Scope, tableName string, columnName string) bool {
var count int
newScope := scope.New(nil)
newScope.Raw(fmt.Sprintf("SELECT count(*) FROM information_schema.columns WHERE table_name = %v AND column_name = %v",
newScope.Raw(fmt.Sprintf("SELECT count(*) FROM information_schema.columns WHERE table_schema = %v AND table_name = %v AND column_name = %v",
newScope.AddToVars(s.databaseName(scope)),
newScope.AddToVars(tableName),
newScope.AddToVars(columnName),
))
Expand Down

0 comments on commit 6dc332e

Please sign in to comment.