I pull data from API. The pull results in struct arrays, each containing 100 elements. The code I use to insert them into DB is:
func (ACUpdater) InsertToTable(rawData *models.Contacts, table *gorm.DB) {
for i := 0; i < len(rawData.Results); i++ {
temp := models.ACQ_report{
ID : "", //to be created later by hashing below data fields
RecordID: rawData.Results[i].ID,
FirstName: rawData.Results[i].Properties.Firstname,
LastName: rawData.Results[i].Properties.Lastname,
Email: rawData.Results[i].Properties.Email,
PhoneNumber: rawData.Results[i].Properties.Phone,
ContactOwner: rawData.Results[i].Properties.HubspotOwnerID,
CompanyName: rawData.Results[i].Properties.Company,
}
temp.ID = hashContactRecord(&temp)
table.Create(&temp)
fmt.Println(&temp)
fmt.Println(i)
}
}
I used the hash of data fields as primary key for the table, so that in case any of those data field changes, the hash also changes. That way, I can append to the existing table the changed record without worrying about duplicate primary keys.
The issue is, the above function totally "gives up" INSERTING after 1 duplicate primary key error from GORM. If the first record to be inserted into database is a duplicate, then tx.Created(&temp) will still run, but it did not insert the changed records. As if tx.Create() gives up after the first duplicate primary key error.
How to fix this behavior?