go-gorm / playground

GORM Playground (Please Create PR for this project to report issues)
MIT License
89 stars 681 forks source link

test case where Model() is not replacing the old value within a transaction #739

Open alkuma opened 4 months ago

alkuma commented 4 months ago

…action

Explain your user case and expected results

I am attempting to modify two tables within a transaction. However the second table insert within the transaction thows an error which implies that gorm is still keeping the old table name in its state despite calling Model() with the new model the second time.

This finally leads me to an error

ERROR: column "audit_id" of relation "department" does not exist (SQLSTATE 42703)
[0.610ms] [rows:0] INSERT INTO "department" ("audit_id","audit_desc") VALUES ('3bae3e28-2c6d-4ad4-853d-3191200245cf','created department e11e53d3-d3f5-48fe-a72d-5897845fe968')

whereas this query should have been

INSERT INTO "audit" ("audit_id","audit_desc")
VALUES
(
  '3bae3e28-2c6d-4ad4-853d-3191200245cf',
  'created department e11e53d3-d3f5-48fe-a72d-5897845fe968'
)

There are many other errors in my use case but dropping the individual items one by one, this is the first one.

xuyang2 commented 2 months ago

It seems stmt.Table="department" is accidentally cached here

https://github.com/go-gorm/gorm/blob/9d370bcb3ec9055b6292da5211f4eaee2458f520/statement.go#L492

after stmt.Schema, err = schema.ParseWithSpecialTableName(...): err == nil stmt.Table == "department"

so the if block with stmt.Table = stmt.Schema.Table is skipped, and stmt.Table remains "department"

1720620430563

I think this can be fixed by change if stmt.Schema, err = schema.ParseWithSpecialTableName(value, stmt.DB.cacheStore, stmt.DB.NamingStrategy, specialTableName); err == nil && stmt.Table == "" { to if stmt.Schema, err = schema.ParseWithSpecialTableName(value, stmt.DB.cacheStore, stmt.DB.NamingStrategy, specialTableName); err == nil {

@jinzhu what do you think?