go-gorm / postgres

GORM PostgreSQL driver
MIT License
234 stars 123 forks source link

AutoMigrate always alters columns of "bigint" #123

Closed tavitar closed 2 years ago

tavitar commented 2 years ago

GORM Playground Link

https://github.com/go-gorm/playground/pull/500

Description

The problem is rather simple: every run of AutoMigrate will execute a redundant ALTER COLUMN for int types (int64).

The reason?: The GORM Postgres driver uses "bigint" as the type for go's int64. However, in postgres, bigint is not the type name internally - it's just an alias to int8:

SELECT * FROM pg_type WHERE typname IN ('int8', 'bigint');

typname
int8

In practice, this means that AutoMigrate will always detect a discrepancy ("int8" != "bigint") and run an ALTER COLUMN.

The bad: You need to disable AutoMigrate by default to avoid these redundant queries. The ugly: The ALTER COLUMN int8 to bigint actually breaks conditional indexes which depend on the column and requires VACUUM ANALYZE to fix (a Postgres issue, not a problem for here, I'll report when I have time). However, suffice to say, the redundant ALTER COLUMNs are not benign.

Happy to create a pull request.

tavitar commented 2 years ago

(updated issue description with playground PR)

Rizary commented 2 years ago

I second this. I have the following:

type AllocationEntity struct {
    ID   string     `gorm:"column:id;primaryKey"`
    Name string     `gorm:"column:name"`
    Vult VultEntity `gorm:"foreignKey:ID;references:WalletID"`
    datastore.ModelWithTS
}

type VultEntity struct {
    ID       string `gorm:"column:id;primaryKey"`
    WalletID int64  `gorm:"index:wallet_id,unique;null"`
    AllocID  string `gorm:"index:alloc_id,unique"`
    datastore.ModelWithTS
}

AutoMigrate(
    &AllocationEntity{},
    &VultEntity{},
)

The strange part is in my postgresql, ID in the allocationEntity created is BigInt not string, but in the vult, it is string.

a631807682 commented 2 years ago

related to https://github.com/go-gorm/postgres/pull/111

itsofirblink commented 2 years ago

@a631807682 Hey! Do you know when this issue will be resolved? Thanks! Have a great day!

a631807682 commented 2 years ago

@a631807682 Hey! Do you know when this issue will be resolved? Thanks! Have a great day!

I don't know, it is waiting for the maintainer review.

itsofirblink commented 2 years ago

@a631807682 Hey! Do you know when this issue will be resolved? Thanks! Have a great day!

I don't know, it is waiting for the maintainer review.

No problem, i see that it fails on tests on some driver, that might be an issue?

a631807682 commented 2 years ago

@a631807682 Hey! Do you know when this issue will be resolved? Thanks! Have a great day!

I don't know, it is waiting for the maintainer review.

No problem, i see that it fails on tests on some driver, that might be an issue?

It will fix by https://github.com/go-gorm/gorm/pull/5620