3

i have an issue with the generated columns value with GORM.

My struct
type Product struct { gorm.Model Name string `json:"name" gorm:"not null"` Quantity uint `json:"quantity" gorm:"not null"` Price float64 `json:"price" gorm:"not null"` Gain float64 `json:"gain" gorm:"not null"` Total float64 `json:"total" gorm:"->;type:GENERATED ALWAYS AS (quantity*price);"` // generated total price TotalGain float64 `json:"total_gain" gorm:"->;type:GENERATED ALWAYS AS (quantity*gain);"` // generated total gain ProcessID uint // one-to-many } 
auto migration
 err = database.AutoMigrate(&models.Process{}, &models.Product{}) if err != nil { return err } 

This is the error

cannot INSERT into generated column "total" [0.021ms] [rows:0] INSERT INTO `products__temp`(`id`,`created_at`,`updated_at`,`deleted_at`,`name`,`quantity`,`price`,`gain`,`total`,`total_gain`,`process_id`) SELECT `id`,`created_at`,`updated_at`,`deleted_at`,`name`,`quantity`,`price`,`gain`,`total`,`total_gain`,`process_id` FROM `products` 

It seems like GORM has created a temporary table "products__temp" a clone of "products" table. So as we can know we cannot insert or edit the generated columns!

Note: i'm working wih SQLite

11
  • if you want to write then you check field-level permissions Commented Aug 9, 2022 at 15:25
  • No, this error is refer to the database it self, The rule of SQL said you cannot insert data into generated columns! You can try it without GORM. As i said the problem is when the GORM temporary table "products__temp" is created Commented Aug 9, 2022 at 16:27
  • Perhaps the tag -:migration should be added to the generated fields. But I do not know if these fields will be created when creating the table. gorm.io/docs/models.html#field_permission Commented Aug 9, 2022 at 17:22
  • i already tried the "-:migration" tag, it gives me the same problem! Commented Aug 9, 2022 at 21:32
  • 1
    @zakariachahboun please add the steps in your question how you are adding the records. Commented Aug 10, 2022 at 4:33

1 Answer 1

2

This issue is fixed by my pull request

https://github.com/go-gorm/sqlite/pull/109

the pull is accepted 👌🏻

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.