Fix auto migration for sqlite

This commit is contained in:
Jinzhu 2014-04-29 15:39:06 +08:00
parent 514a32e547
commit 3264b82368
2 changed files with 3 additions and 11 deletions

View File

@ -190,8 +190,6 @@ FYI, AutoMigrate will only add new columns, it won't change the current columns'
If the table doesn't exist when AutoMigrate is called, gorm will create the table automatically. If the table doesn't exist when AutoMigrate is called, gorm will create the table automatically.
(the database first needs to be created manually though...). (the database first needs to be created manually though...).
(only postgres and mysql supported)
```go ```go
db.AutoMigrate(User{}) db.AutoMigrate(User{})
``` ```

View File

@ -63,18 +63,12 @@ func (s *sqlite3) Quote(key string) string {
func (s *sqlite3) HasTable(scope *Scope, tableName string) bool { func (s *sqlite3) HasTable(scope *Scope, tableName string) bool {
var count int var count int
newScope := scope.New(nil) 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 sqlite_master WHERE type='table' AND name=%v", newScope.AddToVars(tableName)))
newScope.DB().QueryRow(newScope.Sql, newScope.SqlVars...).Scan(&count) newScope.DB().QueryRow(newScope.Sql, newScope.SqlVars...).Scan(&count)
return count > 0 return count > 0
} }
func (s *sqlite3) HasColumn(scope *Scope, tableName string, columnName string) bool { func (s *sqlite3) HasColumn(scope *Scope, tableName string, columnName string) bool {
var count int _, err := scope.DB().Exec(fmt.Sprintf("SELECT %v FROM %v LIMIT 1", columnName, tableName))
newScope := scope.New(nil) return err == nil
newScope.Raw(fmt.Sprintf("SELECT count(*) FROM information_schema.columns WHERE table_name = %v AND column_name = %v",
newScope.AddToVars(tableName),
newScope.AddToVars(columnName),
))
newScope.DB().QueryRow(newScope.Sql, newScope.SqlVars...).Scan(&count)
return count > 0
} }