Ignored database name with table name.
Closed this issue · 1 comments
Description
In the below program, for User
struct configured table name as test.user
using the TableName. However, when I run the DropTable query on User struct, I am getting error Error 1046 (3D000): No database selected
. Drop query logged as DROP TABLE IF EXISTS user CASCADE
. As you can see, the database name is missing with table name 'user' in the query which is configured in the TableName. Same issue with AlterColumn, RenameColumn, and RenameIndex.
Program
package main
import (
"fmt"
"time"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// Tabler interface for overriding table name.
type Tabler interface {
TableName() string
}
type User struct {
ID uint // Standard field for the primary key
Name string // A regular string field
}
// TableName overrides the table name.
func (User) TableName() string {
return "test.user"
}
func main() {
dsn := "<user>:<password>@tcp(127.0.0.1:3306)/?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
err = db.Migrator().CreateTable(&User{})
if err != nil {
fmt.Print(err)
return
}
fmt.Println("Created the User table")
err = db.Migrator().DropTable(&User{})
if err != nil {
fmt.Print(err)
return
}
fmt.Println("Dropped the User table")
}
Output
% go run droptable/main.go
Created the User table
2024/04/27 02:11:34 /Users/mkchevuri/myprojects/testnotebook/droptable/main.go:42 Error 1046 (3D000): No database selected
[0.269ms] [rows:0] DROP TABLE IF EXISTS `user` CASCADE
Error 1046 (3D000): No database selected%
Solution
In DropTable, for getting the table name, we are using clause.Table{Name: stmt.Table})
. stmt.Table
returns table name without database. Instead of stmt.Table
, if we use the Migrator.CurrentTable
which returns a clause with database name + table name (Which configured through TableName function).
Line 298 in 9d1b8d6
Thank you for your PR.