Merge branch 'jaytaylor-jay/ddl-errors'

This commit is contained in:
Jinzhu 2015-08-13 09:09:37 +08:00
commit e1ce3b7066
10 changed files with 113 additions and 71 deletions

View File

@ -73,7 +73,7 @@ func (c commonDialect) HasTable(scope *Scope, tableName string) bool {
count int count int
databaseName = c.CurrentDatabase(scope) databaseName = c.CurrentDatabase(scope)
) )
scope.NewDB().Raw("SELECT count(*) FROM INFORMATION_SCHEMA.TABLES WHERE table_name = ? AND table_schema = ?", tableName, databaseName).Row().Scan(&count) c.RawScanInt(scope, &count, "SELECT count(*) FROM INFORMATION_SCHEMA.TABLES WHERE table_name = ? AND table_schema = ?", tableName, databaseName)
return count > 0 return count > 0
} }
@ -82,18 +82,30 @@ func (c commonDialect) HasColumn(scope *Scope, tableName string, columnName stri
count int count int
databaseName = c.CurrentDatabase(scope) databaseName = c.CurrentDatabase(scope)
) )
scope.NewDB().Raw("SELECT count(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = ? AND table_name = ? AND column_name = ?", databaseName, tableName, columnName).Row().Scan(&count) c.RawScanInt(scope, &count, "SELECT count(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = ? AND table_name = ? AND column_name = ?", databaseName, tableName, columnName)
return count > 0 return count > 0
} }
func (commonDialect) HasIndex(scope *Scope, tableName string, indexName string) bool { func (c commonDialect) HasIndex(scope *Scope, tableName string, indexName string) bool {
var count int var count int
scope.NewDB().Raw("SELECT count(*) FROM INFORMATION_SCHEMA.STATISTICS where table_name = ? AND index_name = ?", tableName, indexName).Row().Scan(&count) c.RawScanInt(scope, &count, "SELECT count(*) FROM INFORMATION_SCHEMA.STATISTICS where table_name = ? AND index_name = ?", tableName, indexName)
return count > 0 return count > 0
} }
func (commonDialect) RemoveIndex(scope *Scope, indexName string) { func (commonDialect) RemoveIndex(scope *Scope, indexName string) {
scope.NewDB().Exec(fmt.Sprintf("DROP INDEX %v ON %v", indexName, scope.QuotedTableName())) scope.Err(scope.NewDB().Exec(fmt.Sprintf("DROP INDEX %v ON %v", indexName, scope.QuotedTableName())).Error)
}
// RawScanInt scans the first column of the first row into the `scan' int pointer.
// This function captures raw query errors and propagates them to the original scope.
func (commonDialect) RawScanInt(scope *Scope, scanPtr *int, query string, args ...interface{}) {
scope.Err(scope.NewDB().Raw(query, args...).Row().Scan(scanPtr))
}
// RawScanString scans the first column of the first row into the `scan' string pointer.
// This function captures raw query errors and propagates them to the original scope.
func (commonDialect) RawScanString(scope *Scope, scanPtr *string, query string, args ...interface{}) {
scope.Err(scope.NewDB().Raw(query, args...).Row().Scan(scanPtr))
} }
func (commonDialect) CurrentDatabase(scope *Scope) (name string) { func (commonDialect) CurrentDatabase(scope *Scope) (name string) {

24
ddl_errors_test.go Normal file
View File

@ -0,0 +1,24 @@
package gorm_test
import (
"testing"
)
func TestDdlErrors(t *testing.T) {
var err error
if err = DB.Close(); err != nil {
t.Errorf("Closing DDL test db connection err=%s", err)
}
defer func() {
// Reopen DB connection.
if DB, err = OpenTestConnection(); err != nil {
t.Fatalf("Failed re-opening db connection: %s", err)
}
}()
DB.HasTable("foobarbaz")
if DB.Error == nil {
t.Errorf("Expected operation on closed db to produce an error, but err was nil")
}
}

View File

@ -10,8 +10,8 @@ func TestDelete(t *testing.T) {
DB.Save(&user1) DB.Save(&user1)
DB.Save(&user2) DB.Save(&user2)
if DB.Delete(&user1).Error != nil { if err := DB.Delete(&user1).Error; err != nil {
t.Errorf("No error should happen when delete a record") t.Errorf("No error should happen when delete a record, err=%s", err)
} }
if !DB.Where("name = ?", user1.Name).First(&User{}).RecordNotFound() { if !DB.Where("name = ?", user1.Name).First(&User{}).RecordNotFound() {
@ -34,8 +34,8 @@ func TestInlineDelete(t *testing.T) {
t.Errorf("User can't be found after delete") t.Errorf("User can't be found after delete")
} }
if DB.Delete(&User{}, "name = ?", user2.Name).Error != nil { if err := DB.Delete(&User{}, "name = ?", user2.Name).Error; err != nil {
t.Errorf("No error should happen when delete a record") t.Errorf("No error should happen when delete a record, err=%s", err)
} else if !DB.Where("name = ?", user2.Name).First(&User{}).RecordNotFound() { } else if !DB.Where("name = ?", user2.Name).First(&User{}).RecordNotFound() {
t.Errorf("User can't be found after delete") t.Errorf("User can't be found after delete")
} }
@ -57,8 +57,8 @@ func TestSoftDelete(t *testing.T) {
t.Errorf("Can't find a soft deleted record") t.Errorf("Can't find a soft deleted record")
} }
if DB.Unscoped().First(&User{}, "name = ?", user.Name).Error != nil { if err := DB.Unscoped().First(&User{}, "name = ?", user.Name).Error; err != nil {
t.Errorf("Should be able to find soft deleted record with Unscoped") t.Errorf("Should be able to find soft deleted record with Unscoped, but err=%s", err)
} }
DB.Unscoped().Delete(&user) DB.Unscoped().Delete(&user)

View File

@ -51,33 +51,33 @@ func (foundation) SqlTag(value reflect.Value, size int, autoIncrease bool) strin
panic(fmt.Sprintf("invalid sql type %s (%s) for foundation", value.Type().Name(), value.Kind().String())) panic(fmt.Sprintf("invalid sql type %s (%s) for foundation", value.Type().Name(), value.Kind().String()))
} }
func (f foundation) ReturningStr(tableName, key string) string { func (s foundation) ReturningStr(tableName, key string) string {
return fmt.Sprintf("RETURNING %v.%v", f.Quote(tableName), key) return fmt.Sprintf("RETURNING %v.%v", s.Quote(tableName), key)
} }
func (foundation) HasTable(scope *Scope, tableName string) bool { func (s foundation) HasTable(scope *Scope, tableName string) bool {
var count int var count int
scope.NewDB().Raw("SELECT count(*) FROM INFORMATION_SCHEMA.tables WHERE table_schema = current_schema AND table_type = 'TABLE' AND table_name = ?", tableName).Row().Scan(&count) s.RawScanInt(scope, &count, "SELECT count(*) FROM INFORMATION_SCHEMA.tables WHERE table_schema = current_schema AND table_type = 'TABLE' AND table_name = ?", tableName)
return count > 0 return count > 0
} }
func (foundation) HasColumn(scope *Scope, tableName string, columnName string) bool { func (s foundation) HasColumn(scope *Scope, tableName string, columnName string) bool {
var count int var count int
scope.NewDB().Raw("SELECT count(*) FROM INFORMATION_SCHEMA.columns WHERE table_schema = current_schema AND table_name = ? AND column_name = ?", tableName, columnName).Row().Scan(&count) s.RawScanInt(scope, &count, "SELECT count(*) FROM INFORMATION_SCHEMA.columns WHERE table_schema = current_schema AND table_name = ? AND column_name = ?", tableName, columnName)
return count > 0 return count > 0
} }
func (f foundation) RemoveIndex(scope *Scope, indexName string) { func (s foundation) RemoveIndex(scope *Scope, indexName string) {
scope.NewDB().Exec(fmt.Sprintf("DROP INDEX %v", f.Quote(indexName))) scope.NewDB().Exec(fmt.Sprintf("DROP INDEX %v", s.Quote(indexName)))
} }
func (foundation) HasIndex(scope *Scope, tableName string, indexName string) bool { func (s foundation) HasIndex(scope *Scope, tableName string, indexName string) bool {
var count int var count int
scope.NewDB().Raw("SELECT count(*) FROM INFORMATION_SCHEMA.indexes WHERE table_schema = current_schema AND table_name = ? AND index_name = ?", tableName, indexName).Row().Scan(&count) s.RawScanInt(scope, &count, "SELECT count(*) FROM INFORMATION_SCHEMA.indexes WHERE table_schema = current_schema AND table_name = ? AND index_name = ?", tableName, indexName)
return count > 0 return count > 0
} }
func (foundation) CurrentDatabase(scope *Scope) (name string) { func (s foundation) CurrentDatabase(scope *Scope) (name string) {
scope.Err(scope.NewDB().Raw("SELECT CURRENT_SCHEMA").Row().Scan(&name)) s.RawScanString(scope, &name, "SELECT CURRENT_SCHEMA")
return return
} }

View File

@ -388,7 +388,9 @@ func (s *DB) DropTableIfExists(value interface{}) *DB {
func (s *DB) HasTable(value interface{}) bool { func (s *DB) HasTable(value interface{}) bool {
scope := s.clone().NewScope(value) scope := s.clone().NewScope(value)
tableName := scope.TableName() tableName := scope.TableName()
return scope.Dialect().HasTable(scope, tableName) has := scope.Dialect().HasTable(scope, tableName)
s.err(scope.db.Error)
return has
} }
func (s *DB) AutoMigrate(values ...interface{}) *DB { func (s *DB) AutoMigrate(values ...interface{}) *DB {

View File

@ -26,25 +26,9 @@ var (
func init() { func init() {
var err error var err error
switch os.Getenv("GORM_DIALECT") {
case "mysql": if DB, err = OpenTestConnection(); err != nil {
// CREATE USER 'gorm'@'localhost' IDENTIFIED BY 'gorm'; panic(fmt.Sprintf("No error should happen when connecting to test database, but got err=%+v", err))
// CREATE DATABASE gorm;
// GRANT ALL ON gorm.* TO 'gorm'@'localhost';
fmt.Println("testing mysql...")
DB, err = gorm.Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True")
case "postgres":
fmt.Println("testing postgres...")
DB, err = gorm.Open("postgres", "user=gorm DB.name=gorm sslmode=disable")
case "foundation":
fmt.Println("testing foundation...")
DB, err = gorm.Open("foundation", "dbname=gorm port=15432 sslmode=disable")
case "mssql":
fmt.Println("testing mssql...")
DB, err = gorm.Open("mssql", "server=SERVER_HERE;database=rogue;user id=USER_HERE;password=PW_HERE;port=1433")
default:
fmt.Println("testing sqlite3...")
DB, err = gorm.Open("sqlite3", "/tmp/gorm.db")
} }
// DB.SetLogger(Logger{log.New(os.Stdout, "\r\n", 0)}) // DB.SetLogger(Logger{log.New(os.Stdout, "\r\n", 0)})
@ -52,15 +36,35 @@ func init() {
// DB.LogMode(true) // DB.LogMode(true)
DB.LogMode(false) DB.LogMode(false)
if err != nil {
panic(fmt.Sprintf("No error should happen when connect database, but got %+v", err))
}
DB.DB().SetMaxIdleConns(10) DB.DB().SetMaxIdleConns(10)
runMigration() runMigration()
} }
func OpenTestConnection() (db gorm.DB, err error) {
switch os.Getenv("GORM_DIALECT") {
case "mysql":
// CREATE USER 'gorm'@'localhost' IDENTIFIED BY 'gorm';
// CREATE DATABASE gorm;
// GRANT ALL ON gorm.* TO 'gorm'@'localhost';
fmt.Println("testing mysql...")
db, err = gorm.Open("mysql", "gorm:gorm@/gorm?charset=utf8&parseTime=True")
case "postgres":
fmt.Println("testing postgres...")
db, err = gorm.Open("postgres", "user=gorm DB.name=gorm sslmode=disable")
case "foundation":
fmt.Println("testing foundation...")
db, err = gorm.Open("foundation", "dbname=gorm port=15432 sslmode=disable")
case "mssql":
fmt.Println("testing mssql...")
db, err = gorm.Open("mssql", "server=SERVER_HERE;database=rogue;user id=USER_HERE;password=PW_HERE;port=1433")
default:
fmt.Println("testing sqlite3...")
db, err = gorm.Open("sqlite3", "/tmp/gorm.db")
}
return
}
func TestStringPrimaryKey(t *testing.T) { func TestStringPrimaryKey(t *testing.T) {
type UUIDStruct struct { type UUIDStruct struct {
ID string `gorm:"primary_key"` ID string `gorm:"primary_key"`

View File

@ -55,7 +55,7 @@ func (s mssql) HasTable(scope *Scope, tableName string) bool {
count int count int
databaseName = s.CurrentDatabase(scope) databaseName = s.CurrentDatabase(scope)
) )
scope.NewDB().Raw("SELECT count(*) FROM INFORMATION_SCHEMA.tables WHERE table_name = ? AND table_catalog = ?", tableName, databaseName).Row().Scan(&count) s.RawScanInt(scope, &count, "SELECT count(*) FROM INFORMATION_SCHEMA.tables WHERE table_name = ? AND table_catalog = ?", tableName, databaseName)
return count > 0 return count > 0
} }
@ -64,17 +64,17 @@ func (s mssql) HasColumn(scope *Scope, tableName string, columnName string) bool
count int count int
databaseName = s.CurrentDatabase(scope) databaseName = s.CurrentDatabase(scope)
) )
scope.NewDB().Raw("SELECT count(*) FROM information_schema.columns WHERE table_catalog = ? AND table_name = ? AND column_name = ?", databaseName, tableName, columnName).Row().Scan(&count) s.RawScanInt(scope, &count, "SELECT count(*) FROM information_schema.columns WHERE table_catalog = ? AND table_name = ? AND column_name = ?", databaseName, tableName, columnName)
return count > 0 return count > 0
} }
func (mssql) HasIndex(scope *Scope, tableName string, indexName string) bool { func (s mssql) HasIndex(scope *Scope, tableName string, indexName string) bool {
var count int var count int
scope.NewDB().Raw("SELECT count(*) FROM sys.indexes WHERE name=? AND object_id=OBJECT_ID(?)", indexName, tableName).Row().Scan(&count) s.RawScanInt(scope, &count, "SELECT count(*) FROM sys.indexes WHERE name=? AND object_id=OBJECT_ID(?)", indexName, tableName)
return count > 0 return count > 0
} }
func (mssql) CurrentDatabase(scope *Scope) (name string) { func (s mssql) CurrentDatabase(scope *Scope) (name string) {
scope.Err(scope.NewDB().Raw("SELECT DB_NAME() AS [Current Database]").Row().Scan(&name)) s.RawScanString(scope, &name, "SELECT DB_NAME() AS [Current Database]")
return return
} }

View File

@ -64,7 +64,7 @@ func (mysql) SelectFromDummyTable() string {
return "FROM DUAL" return "FROM DUAL"
} }
func (mysql) CurrentDatabase(scope *Scope) (name string) { func (s mysql) CurrentDatabase(scope *Scope) (name string) {
scope.Err(scope.NewDB().Raw("SELECT DATABASE()").Row().Scan(&name)) s.RawScanString(scope, &name, "SELECT DATABASE()")
return return
} }

View File

@ -63,30 +63,30 @@ func (s postgres) ReturningStr(tableName, key string) string {
return fmt.Sprintf("RETURNING %v.%v", s.Quote(tableName), key) return fmt.Sprintf("RETURNING %v.%v", s.Quote(tableName), key)
} }
func (postgres) HasTable(scope *Scope, tableName string) bool { func (s postgres) HasTable(scope *Scope, tableName string) bool {
var count int var count int
scope.NewDB().Raw("SELECT count(*) FROM INFORMATION_SCHEMA.tables WHERE table_name = ? AND table_type = 'BASE TABLE'", tableName).Row().Scan(&count) s.RawScanInt(scope, &count, "SELECT count(*) FROM INFORMATION_SCHEMA.tables WHERE table_name = ? AND table_type = 'BASE TABLE'", tableName)
return count > 0 return count > 0
} }
func (postgres) HasColumn(scope *Scope, tableName string, columnName string) bool { func (s postgres) HasColumn(scope *Scope, tableName string, columnName string) bool {
var count int var count int
scope.NewDB().Raw("SELECT count(*) FROM INFORMATION_SCHEMA.columns WHERE table_name = ? AND column_name = ?", tableName, columnName).Row().Scan(&count) s.RawScanInt(scope, &count, "SELECT count(*) FROM INFORMATION_SCHEMA.columns WHERE table_name = ? AND column_name = ?", tableName, columnName)
return count > 0 return count > 0
} }
func (postgres) RemoveIndex(scope *Scope, indexName string) { func (postgres) RemoveIndex(scope *Scope, indexName string) {
scope.NewDB().Exec(fmt.Sprintf("DROP INDEX %v", indexName)) scope.Err(scope.NewDB().Exec(fmt.Sprintf("DROP INDEX %v", indexName)).Error)
} }
func (postgres) HasIndex(scope *Scope, tableName string, indexName string) bool { func (s postgres) HasIndex(scope *Scope, tableName string, indexName string) bool {
var count int var count int
scope.NewDB().Raw("SELECT count(*) FROM pg_indexes WHERE tablename = ? AND indexname = ?", tableName, indexName).Row().Scan(&count) s.RawScanInt(scope, &count, "SELECT count(*) FROM pg_indexes WHERE tablename = ? AND indexname = ?", tableName, indexName)
return count > 0 return count > 0
} }
func (postgres) CurrentDatabase(scope *Scope) (name string) { func (s postgres) CurrentDatabase(scope *Scope) (name string) {
scope.Err(scope.NewDB().Raw("SELECT CURRENT_DATABASE()").Row().Scan(&name)) s.RawScanString(scope, &name, "SELECT CURRENT_DATABASE()")
return return
} }

View File

@ -40,26 +40,26 @@ func (sqlite3) SqlTag(value reflect.Value, size int, autoIncrease bool) string {
panic(fmt.Sprintf("invalid sql type %s (%s) for sqlite3", value.Type().Name(), value.Kind().String())) panic(fmt.Sprintf("invalid sql type %s (%s) for sqlite3", value.Type().Name(), value.Kind().String()))
} }
func (sqlite3) HasTable(scope *Scope, tableName string) bool { func (s sqlite3) HasTable(scope *Scope, tableName string) bool {
var count int var count int
scope.NewDB().Raw("SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?", tableName).Row().Scan(&count) s.RawScanInt(scope, &count, "SELECT count(*) FROM sqlite_master WHERE type='table' AND name=?", tableName)
return count > 0 return count > 0
} }
func (sqlite3) HasColumn(scope *Scope, tableName string, columnName string) bool { func (s sqlite3) HasColumn(scope *Scope, tableName string, columnName string) bool {
var count int var count int
scope.NewDB().Raw(fmt.Sprintf("SELECT count(*) FROM sqlite_master WHERE tbl_name = ? AND (sql LIKE '%%(\"%v\" %%' OR sql LIKE '%%,\"%v\" %%' OR sql LIKE '%%( %v %%' OR sql LIKE '%%, %v %%');\n", columnName, columnName, columnName, columnName), tableName).Row().Scan(&count) s.RawScanInt(scope, &count, fmt.Sprintf("SELECT count(*) FROM sqlite_master WHERE tbl_name = ? AND (sql LIKE '%%(\"%v\" %%' OR sql LIKE '%%,\"%v\" %%' OR sql LIKE '%%( %v %%' OR sql LIKE '%%, %v %%');\n", columnName, columnName, columnName, columnName), tableName)
return count > 0 return count > 0
} }
func (sqlite3) HasIndex(scope *Scope, tableName string, indexName string) bool { func (s sqlite3) HasIndex(scope *Scope, tableName string, indexName string) bool {
var count int var count int
scope.NewDB().Raw(fmt.Sprintf("SELECT count(*) FROM sqlite_master WHERE tbl_name = ? AND sql LIKE '%%INDEX %v ON%%'", indexName), tableName).Row().Scan(&count) s.RawScanInt(scope, &count, fmt.Sprintf("SELECT count(*) FROM sqlite_master WHERE tbl_name = ? AND sql LIKE '%%INDEX %v ON%%'", indexName), tableName)
return count > 0 return count > 0
} }
func (sqlite3) RemoveIndex(scope *Scope, indexName string) { func (sqlite3) RemoveIndex(scope *Scope, indexName string) {
scope.NewDB().Exec(fmt.Sprintf("DROP INDEX %v", indexName)) scope.Err(scope.NewDB().Exec(fmt.Sprintf("DROP INDEX %v", indexName)).Error)
} }
func (sqlite3) CurrentDatabase(scope *Scope) (name string) { func (sqlite3) CurrentDatabase(scope *Scope) (name string) {