As a beginner, I want to know what I've did wrong in my code, I asked chatgpt, but it's not giving me good info. any help is appreciated.
web-1 | 2024/03/31 14:26:43 /usr/src/app/handlers/ads.go:59 ERROR: column "country" is of type text[] but expression is of type record (SQLSTATE 42804)
web-1 | [0.248ms] [rows:0] INSERT INTO "conditions" ("created_at","updated_at","deleted_at","ad_id","age_start","age_end","gender","country","platform") VALUES ('2024-03-31 14:26:43.751','2024-03-31 14:26:43.751',NULL,5,20,30,('M'),('TW','JP'),('android','ios')) ON CONFLICT ("id") DO UPDATE SET "ad_id"="excluded"."ad_id" RETURNING "id"
package models
import (
"time"
"gorm.io/gorm"
)
type AD struct {
gorm.Model
Title string `json:"title" gorm:"type:text"`
StartAt time.Time `json:"startAt" gorm:"type:timestamp"`
EndAt time.Time `json:"endAt" gorm:"type:timestamp"`
IsActive bool `gorm:"default:False;type:boolean"`
Conditions []Conditions `json:"conditions"`
}
type Conditions struct {
gorm.Model
ADID uint
AgeStart int `json:"ageStart" gorm:"default:0;type:integer"`
AgeEnd int `json:"ageEnd" gorm:"default:100;type:integer"`
Gender []string `json:"gender" gorm:"type:text[]"`
Country []string `json:"country" gorm:"type:text[]"`
Platform []string `json:"platform" gorm:"type:text[]"`
}
func CreateAd(c *fiber.Ctx) error {
ad := new(models.AD)
if err := c.BodyParser(ad); err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": err.Error(),
})
}
if IsAdAlive(*ad) {
ad.IsActive = true
} else {
ad.IsActive = false
}
fmt.Println(ad)
database.DB.Db.Model(models.AD{}).Create(&ad)
return c.Status(200).JSON(ad)
}
I asked chatGPT, it said this:
Review GORM Documentation: Ensure that you're using GORM's features correctly for handling arrays. GORM should abstract away the need to manually format arrays for PostgreSQL. If there's a discrepancy in how GORM expects arrays to be formatted versus what your PostgreSQL version expects, this could lead to issues. Checking the latest GORM documentation for array support or any open issues related to array handling could provide insights or solutions.
but I can't find those.
change to pq.StringArray
type, also include "github.com/lib/pq"
type Conditions struct {
gorm.Model
ADID uint
AgeStart int `json:"ageStart" gorm:"default:0;type:integer"`
AgeEnd int `json:"ageEnd" gorm:"default:100;type:integer"`
Gender pq.StringArray `json:"gender" gorm:"type:text[]"`
Country pq.StringArray `json:"country" gorm:"type:text[]"`
Platform pq.StringArray `json:"platform" gorm:"type:text[]"`
}