go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
37.02k stars 3.94k forks source link

Statement.table has a BUG. #7280

Open YuzuWiki opened 1 week ago

YuzuWiki commented 1 week ago

GORM Playground Link

Description

Statement.table. If it exists and is an unexpected value, it may cause the query to not meet expectations.

func (stmt *Statement) ParseWithSpecialTableName(value interface{}, specialTableName string) (err error) {
    if stmt.Schema, err = schema.ParseWithSpecialTableName(value, stmt.DB.cacheStore, stmt.DB.NamingStrategy, specialTableName); err == nil && stmt.Table == "" {
        if tables := strings.Split(stmt.Schema.Table, "."); len(tables) == 2 {
            stmt.TableExpr = &clause.Expr{SQL: stmt.Quote(stmt.Schema.Table)}
            stmt.Table = tables[1]
            return
        }

        stmt.Table = stmt.Schema.Table
    }
    return err
}

Example:

use SQL

type OtherTable struct { Name string }

var retSQL OtherTable db.Raw(SELECT name FROM xxx JOIN ..... LIMIT 1;).Scan(&retSQL )


some time, db.statement.table  will  be set to **other_table**.  now, db looks like this

db: { Statement: { Table: "other_table", Model: nil, ........ } }

now,If we continue to execute 

type User struct { ...... }

func (u User ) TableName() string { return "user" }

var u User db.Model(User{}).Where("id =?", uid).Find(&u)


maybe, we will get the following results
SELECT * FROM `database`.other_table WHERE id = ? limit 1;

but our expected result is
SELECT * FROM `database`.user WHERE id = ?;


<!-- Your use case -->
github-actions[bot] commented 1 week ago

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.ioSearch Before Asking

github-actions[bot] commented 1 week ago

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.ioSearch Before Asking