gen icon indicating copy to clipboard operation
gen copied to clipboard

[Bug] query.Use(db) + t.Table() + query.Use(db) = wrong table name in future query

Open jiekun opened this issue 3 years ago • 0 comments

Hi developers. We spotted a potential bug when using gen and gorm, which may result in generating wrong table name.

Description

By calling t.Table()... and execution, table name will be cached in schema.go#L258.

It's still safe to use the current *Query. But when the user calls query.Use() again, UseModel() will be called as well and finally lead to the call of schema.ParseWithSpecialTableName() and then use the cached table name as the default table name.

Now it becomes danger for use to use CRUD API since calls without specificing table name will use the default table name, which is wrong.

Example and behaviour

query.Use(db)

// I want to query a user data
xxx.Table("user_table_00000000").Find()  // SELECT * FROM user_table_00000000 ...

// Use again
query.Use(db)

// I want to query a user data again but from user_table not user_table_0000xxxx
xxx.Find()  // SELECT * FROM user_table_00000000 ...

// the expected query for last line is: SELECT * FROM user_table ......

Key code block

https://github.com/go-gorm/gorm/blob/490625981a1c3474eeca7f2e4fde791cd94c84fa/schema/schema.go#L258

https://github.com/go-gorm/gorm/blob/490625981a1c3474eeca7f2e4fde791cd94c84fa/schema/schema.go#L150

https://github.com/go-gorm/gen/blob/d1e5812551ab7a9bbafc9b7dfd9c60bafcba3c94/internal/template/query.go#L23

Proposal

for https://github.com/go-gorm/gen/blob/d1e5812551ab7a9bbafc9b7dfd9c60bafcba3c94/internal/template/query.go#L23 should we cache the Use result for user input ?

var (
	useMap = sync.Map{}
)

func Use(db *gorm.DB) *Query {
	q, _ := useMap.LoadOrStore(db, &Query{
		db:                      db,
		UserTab:  newUserTab(db),
	})
	return q.(*Query)
}

jiekun avatar Sep 21 '22 12:09 jiekun