You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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).
Description
In the below program, for
User
struct configured table name astest.user
using the TableName. However, when I run the DropTable query on User struct, I am getting errorError 1046 (3D000): No database selected
. Drop query logged asDROP 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
Output
Solution
In DropTable, for getting the table name, we are using
clause.Table{Name: stmt.Table})
.stmt.Table
returns table name without database. Instead ofstmt.Table
, if we use theMigrator.CurrentTable
which returns a clause with database name + table name (Which configured through TableName function).mysql/migrator.go
Line 298 in 9d1b8d6
The text was updated successfully, but these errors were encountered: