I use gorm and postgresql, this is model
type Board struct {
Id uint `gorm:"primaryKey;autoIncrement;unique" json:"id"`
Owner uint `json:"owner"`
Name string `json:"name"`
Contributors []int `gorm:"type:jsonb" json:"contributors"`
GeneratedLink string `gorm:"default:''" json:"generated_link"`
Todos []TodoStructure `gorm:"type:jsonb;default:[]" json:"todos"`
}
type TodoStructure struct {
Id string
Text string
Completed bool
Important bool
}
in Todo value i specified default value as []
but when i run app i got this error
ERROR: syntax error at or near "[" (SQLSTATE 42601)
[100.528ms] [rows:0] CREATE TABLE "boards" ("id" bigserial UNIQUE,"owner" bigint,"name" text,"contributors" jsonb,"generated_link" text DEFAULT '',"todos" jsonb DEFAULT [],PRIMARY KEY ("id"))
panic: ERROR: syntax error at or near "[" (SQLSTATE 42601)
so how to specify array as default value?
try putting quotes like this gorm:"type:jsonb;default:'[]'" json:"todos"
type Board struct {
Id uint `gorm:"primaryKey;autoIncrement;unique" json:"id"`
Owner uint `json:"owner"`
Name string `json:"name"`
Contributors []int `gorm:"type:jsonb" json:"contributors"`
GeneratedLink string `gorm:"default:''" json:"generated_link"`
Todos []TodoStructure `gorm:"type:jsonb;default:'[]'" json:"todos"`
}
for more reference you can refer this link
Related
I'm working on a Gin app using Gorm ORM (I'm new to both of them). I've got the following model:
type Record struct {
Barcode string `json:"barcode" gorm:"size:48;unique;not null" sql:"index"`
Name string `json:"name" gorm:"size:160;unique;not null"`
Artist Artist `gorm:"foreignKey:ArtistID""`
ArtistId uint
Category Category `gorm:"foreignKey:CategoryID"`
CategoryId uint
NumOfRecords int `json:"num_of_records" gorm:"not null"`
OriginalReleaseDate time.Time `json:"original_release_date" gorm:"default:null"`
ReissueReleaseDate time.Time `json:"reissue_release_date" gorm:"default:null"`
SideColor string `json:"side_color" gorm:"default:null"`
BarcodeInRecord bool `json:"barcode_in_record" gorm:"default=true"`
gorm.Model
}
As you can see there are two fields with two foreign keys: Artist and Category.
Here's those models:
type Category struct {
Name string `json:"name" gorm:"size:60;unique;not null"`
Description string `json:"description" gorm:"size:120"`
Parent uint `json:"parent" gorm:"default:null"`
Active bool `json:"active" gorm:"default:true"`
gorm.Model
}
type Artist struct {
Name string `json:"name" gorm:"size:120;unique;not null"`
Type string `json:"type" gorm:"default:null"`
CountryOfOrigin string `json:"countryOfOrigin" gorm:"default:null"`
gorm.Model
}
category_id and artist_id columns are being created but they are not referencing the other tables two tables:
I've tried to define those fields using AssociationForeignKey:Refer. I also tried to change the foreign key name to simply ID since that's the name that GORM assigns to primary keys but none of those thinks have worked.
What am I missing?
IMO Gorm docs are pretty lousy. From another SO question (Gorm Golang orm associations) it is said that:
it doesn't (create FKs when migrations run). If you want Foreign Key in DB, you need explicitly write something like db.Model(&Place{}).AddForeignKey("town_id", "towns(id)", "RESTRICT", "RESTRICT") during your migrations.
This is how i am trying to retrieve data
func getBoard(c *gin.Context) {
var board models.Board
database.DB.Where("id = ?", 1).Find(&board)
c.JSON(http.StatusOK, board)
}
and in postman i get all values right but todos is null
{
"id": 1,
"owner": 20,
"name": "name",
"generated_link": "",
"todos": null
}
in logs i see this error:
sql: Scan error on column index 4, name "todos": unsupported Scan, storing driver.Value type []uint8 into type *[]models.TodoStructure
this is model:
type Board struct {
Id uint `gorm:"primaryKey;autoIncrement;unique" json:"id"`
Owner uint `json:"owner"`
Name string `json:"name"`
GeneratedLink string `gorm:"default:''" json:"generated_link"`
Todos []TodoStructure `gorm:"type:jsonb;" json:"todos"`
}
type TodoStructure struct {
Id string `json:"id"`
Text string `json:"text"`
Completed bool `json:"completed"`
Important bool `json:"important"`
}
Please help how to get rid of this error and get todos rightly.
I tried to search in google but no result.
I am using gorm and postgresql as db
I am attempting to update a document in firestore using the golang library. For some reason I am getting an error: "no field \"BirthYear\" error and I am not sure why. Birth year is definitely one of the values that I am attempting to update.
I assume that I have configured my struct incorrectly but I cannot see how. Here is my struct and my update code:
sharedstructs.Profile
type Profile struct {
UID string `json:"UID" firestore:"UID"`
ContactEmail string `json:"ContactEmail,omitempty" firestore:"ContactEmail"`
BirthMonth int64 `json:"BirthMonth,omitempty" firestore:"BirthMonth"`
BirthYear int64 `json:"BirthYear,omitempty" firestore:"BirthYear"`
Gender string `json:"Gender,omitempty" firestore:"Gender"`
Unit string `json:"Unit,omitempty" firestore:"Unit"`
CurrentStatus string `json:"CurrentStatus,omitempty" firestore:"CurrentStatus"`
Country string `json:"Country,omitempty" firestore:"Country"`
ExperienceType string `json:"ExperienceType,omitempty" firestore:"ExperienceType"`
DateJoined time.Time `json:"DateJoined,omitempty" firestore:"DateJoined"`
Abilities []Ability `json:"Abilities,omitempty" firestore:"Abilities"`
Goals []Goal `json:"Goals,omitempty" firestore:"Goals"`
Roles []Role `json:"Roles,omitempty" firestore:"Roles"`
TermsAndConditions []TermsAndConditions `json:"TermsAndConditions,omitempty" firestore:"TermsAndConditions"`
TimeZone string `json:"TimeZone,omitempty" firestore:"TimeZone"`
BaselineTests []BaselineTestResults `json:"BaselineTests,omitempty" firestore:"BaselineTests"`
UpdatedDate time.Time `json:"UpdatedDate,omitempty" firestore:"UpdatedDate"`
FirstName *string `json:"FirstName,omitempty" firestore:"FirstName"`
LastName string `json:"LastName,omitempty" firestore:"LastName"`
DisplayName string `json:"DisplayName,omitempty" firestore:"DisplayName"`
}
Update Function
func updateProfileWithSpecficValues(documentName string, values sharedstructs.Profile, overwriteValues []string) error {
ctx := context.Background()
app := firestorehelper.GetFirestoreApp()
client, err := app.Firestore(ctx)
if err != nil {
return err
}
defer client.Close()
//Set the updated date
values.UpdatedDate = time.Now()
wr, error := client.Doc(collectionName+"/"+documentName).Set(ctx, values, firestore.Merge(overwriteValues))
if error != nil {
return error
}
fmt.Println(wr.UpdateTime)
//Assume success
return nil
}
https://godoc.org/cloud.google.com/go/firestore#Merge
Merge returns a SetOption that causes only the given field paths to be
overwritten. Other fields on the existing document will be untouched.
It is an error if a provided field path does not refer to a value in the data passed to Set.
You are sending no BirthYear (default value) in values, but BirthYear is specified in overwriteValues.
As of cloud.google.com/go/firestore v1.3.0, I don't think you can accomplish an update through Set(..., valueStruct, firestore.Merge(sliceOfPaths)) when valueStruct is the complete struct you might read or write to Firestore.
I receive an error string including the 'no field "[SomeFieldName]"' string the OP references, but there is more information in this error. If my sliceOfPaths refers to the names of two elements of my struct, say an int and a time.Time, I often receive an error such as 'no field "[NameOfMyIntField] for value 2020-09-14T00:00:00Z"' or vice-versa, with it trying to update my Firestore doc's time field with the integer.
I just used Update() rather than Set(). It's a little clunkier because you have to pass Update() a specially crafted subset of your original struct (a slice of firestore.Update), but it works.
So i'm creating an API and I needed to store the price of something.
I'm using gorm and gormigrate for my database migration.
I'm just wondering what proper type should I use for storing decimals. I've red somewhere that I shouldn't use floats when storing currencies.
type MyStruct struct {
Name string `json:"name" gorm:"not null"`
Description string `json:"description" gorm:"null"`
Price <what type should be here> `json:"price"`
}
So, based on the suggestion of #ain, I used shopspring/decimal. But it's giving me an error when I do automigrate.
It turns out that I only needed to set the type to numeric using a gorm tag to make it work:
type MyStruct struct {
Name string `json:"name" gorm:"not null"`
Description string `json:"description" gorm:"null"`
Price decimal.Decimal `json:"price" gorm:"type:numeric"`
}
I have a entity EmergencyCase that has 2 embedded structs (1 array and 1 struct)
When I try to save the EmergencyCase by calling:
datastore.Put(c, key, &ec)
Everything is stored fine except the Pos field (type Position). There is no error or log entry about this. It is just not stored. Any suggestions?
Here are my 3 entities definitions:
type Position struct{
lon float32
lat float32
}
type EmergencyCase struct{
// Autogenerated id, not stored in the database.
ID string `datastore:"-"`
CreatedAt time.Time
Closed bool
ClosedByUser bool `datastore:",noindex"`
AutoClosed bool `datastore:",noindex"`
Pos Position
Events []Event
}
type Event struct{
// Autogenerated id, not stored in the datastore.
ID string `datastore:"-"`
CreatedAt time.Time
Name string `datastore:",noindex"`
}
Export the Position field names by uppercasing the first letter in the name. The datastore stores exported fields only.
type Position struct{
Lon float32
Lat float32
}
Try using appengine.GeoPoint as an altenative/optimised class