Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignored database name with table name. #152

Open
murali-chevuri opened this issue Apr 28, 2024 · 0 comments
Open

Ignored database name with table name. #152

murali-chevuri opened this issue Apr 28, 2024 · 0 comments
Assignees

Comments

@murali-chevuri
Copy link

murali-chevuri commented Apr 28, 2024

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).

return tx.Exec("DROP TABLE IF EXISTS ? CASCADE", clause.Table{Name: stmt.Table}).Error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants