GORM FirstOrCreate never updates boolean fields - go

In my model I have fields like this:
HidePricingFromProfile bool `json:"hidePricingFromProfile"`
When I update the model in DB:
store.storage.DB.
Where("artist_account_id = ?", m.ArtistAccountID).
Assign(model).
FirstOrCreate(m).
Error
It updates boolean fields only to true values.
this field is defined in DB like this:
hide_pricing_from_profile boolean default false not null

From doc
NOTE all fields having a zero value, like 0, '', false or other zero
values, won’t be saved into the database but will use its default
value
The zero value of bool is false that's why it not updated. You need to use pointer of bool which zero value is nil then false value will be updated in the database.
HidePricingFromProfile *bool `json:"hidePricingFromProfile"`

Related

Graphql set where parameter of type array to optional

I have this query
query restrictionsTrav($match: String, $offset: Int, $stateIds: [Int!]) {
destinations_for_travel(limit: 100, offset: $offset, where: {city_name: {name: {_ilike: $match}, province_name: {state_Name: {id: {_in: $stateIds}}}}}) {
is_Travel_Allowed
city_status {
name
status
}
city_name{
name
province_name{
name
key
state_Name{
name
long_name
key
}
}
}
updated_at
}
}
Basically, when I query it on Hasura, I have the following query variables: match, offset, and stateIds.
What I want to happen is that even if I leave stateIds empty, I will still see results that match city_name which is represented by the variable match. I tried removing the ! from stateIds but I get an error:
Variable "$stateIds" of type "[Int]" used in position expecting type "[Int!]"
Is there a way wherein I can make the stateIds optional? With the query above, nothing displays if there are no values inside the array stateIds.
to make it optional you can pass a default value like so $stateIds: [Int!] = []

Save is trying to update created_at column

We are updating our project from v1 to v2.
When we try to update a row by providing only changed fields as a struct, it tries to set created_at column and returns an error. This was working back in v1. According to documentation, during update operations, fields with default values are ignored.
err := r.writeDB.Save(&Record{
Model: Model{
ID: 1,
},
Name: "AB",
}).Error
if err != nil {
return err
}
Generates the following SQL statement
[3.171ms] [rows:0] UPDATE `records` SET `created_at`='0000-00-00 00:00:00',`updated_at`='2020-11-12 15:38:36.285',`name`='AB' WHERE `id` = 1
Returns following error
Error 1292: Incorrect datetime value: '0000-00-00' for column
'created_at' at row 1
With these entities
type Model struct {
ID int `gorm:"primary_key,type:INT;not null;AUTO_INCREMENT"`
CreatedAt time.Time `gorm:"type:TIMESTAMP(6)"`
UpdatedAt time.Time `gorm:"type:TIMESTAMP(6)"`
}
type Record struct {
Model
Name string
Details string
}
There is DB.Omit which allows ignoring a column when executing an update query. But this requires a lot of refactoring in the codebase. Does the behavior changed or is there something missing?
This might help you. Change the structure field (or add to replace default gorm.Model field) like this:
CreatedAt time.Time `gorm:"<-:create"` // allow read and create, but don't update
This tag helps to save created data from update.
In Gorm v2 Save(..) writes all fields to the database. As the CreatedAt field is the zero value, this is written to the database.
For you code to work, you can use a map:
err := r.writeDB.Model(&Record{Model:Model{ID:1}}).Update("name","AB").Error
Another option is to not fill in the Record struct, but just point to the table and use a Where clause:
err := r.writeDB.Model(&Record{}).Where("id = ?", 1).Update("name","AB").Error
If you have multiple updates you can use Updates(...) with a map, see here: https://gorm.io/docs/update.html
I was able to work around this problem using Omit() before save. Like this:
result := r.db.Omit("created_at").Save(item)
It omits the CreatedAt from the resulting update query, and updates everything else.

How do you explicitly find a record where a field is NULL?

From the documentation:
When query with struct, GORM will only query with those fields has non-zero value, that means if your field’s value is 0, '', false or other zero values, it won’t be used to build query conditions.
Here is an example of what I am trying to do :
type Dog struct {
ID uuid.UUID
OwnerID *uuid.UUID
}
The owner ID pointer may be nil.
db.Where("owner_id", nil).Find(&dogs)
But that returns all dogs (I expected this from the doc). I tried doing:
db.Where("owner_id", "NULL").Find(&dogs)
But that returns an empty list.
Is there a way to explicitly search for a NULL value field?
According to the docs, this should work:
db.Where("owner_id IS NULL").Find(&dogs)
Yeah, if you want to get the data with the value is null. You only have some choices.
use map interface
use struct with conditions
db.Where("owner_id IS NULL").Find(&dogs)
// or you can also try different way of writing
db.Find(&dogs, "owner_id IS NULL")
You were close in your original attempt. You can also achieve your desired result by writing the query as below.
db.Where("owner_id = ?", "NULL").Find(&dogs)

Filter a Laravel collection by date

In the code given below $allZip["assigned_date"] has value 2016-07-27 18:12:26. When I try to compare it with the created_at field which is a timestamp field as well, the result is an empty collection.
$filtered_datas = $datas->filter(function ($data) use($allZip) {
return $data->zip == $allZip["zip"] && $data->created_at < $allZip["assigned_date"];
});
There is data in database with zip field matching value from $allZip["zip"] and created_at field with value 2016-07-19 18:12:26. So it should return one item in the collection but returns an empty collection instead. Why?
Make sure that all your dates is DateTime or Carbon instances, not strings. Otherwise, comparison operator shouldn't working as you expected.

Windows Phone - SqlCeException column type double

I have a base entity and 3 inherited sub-entities, called NoteItem, ImageItem and MapItem. The base entity class is marked with the [InheritanceMapping] attribute and has a Discriminator column. Everything works fine, except the third MapItem entity, which contains 4 columns of type double and bool.
For example, if I insert the a NoteItem entity it will throw an exception:
SqlCeException - Column Pitch can not contain NULL values
Pitch is column with double type. Only if I extend the [Column] attribute of each double and bool column with the CanBeNull = true addition, then it works.
It seems to me that there's a problem with double and bool values, because a column with type string must not explicitly contain the CanBeNull addition.
Is this a known problem or am I wrong?
there's a problem with double and bool values
AFAIK the behavior is by design.
a column with type string must not explicitly contain the CanBeNull addition
A string CLR value can be null, thus without [Column( CanBeNull = false )] attribute specified, the entity framework generates column that can be null. OTOH, bool and double values can't be null, if you want to allow nulls, you must specify [Column( CanBeNull = true )]
If you don't want to decorate your double and bool properties/fields with [Column] attributes, you could e.g. define them as double? and bool?, respectively.

Resources