elm - updating a record within a record - updates

What is the correct/best way to update a record within a record?
The following attempt:
type alias Model =
{ pageView : PageView
, landingPageModel : Dict
}
--update
update : Action -> Model -> Model
update action model =
case action of
ChangePage pView ->
{ model | pageView = pView }
PostCode pCode ->
let
lPModel =
model.landingPageModel
newlPModel =
{ lPModel | postCode = pCode }
in
{ model | landingPageModel = newlPModel }
gave this error:
The type annotation for `update` does not match its definition.
19│ update : Action -> Model -> Model
^^^^^^^^^^^^^^^^^^^^^^^^
The type annotation is saying:
Action
-> { ..., landingPageModel : Dict }
-> { ..., landingPageModel : Dict }
But I am inferring that the definition has this type:
Action
-> { ..., landingPageModel : { a | postCode : String } }
-> { ..., landingPageModel : { a | postCode : String } }
This is somewhat surprising - isn't a literal Dict update of type Dict?

I simply needed to expand the Model definition :
type alias Model =
{ pageView : PageView
, landingPageModel : { postCode : String }
}
Also, as per halfzebra's comment, Dict's have no relevance here - just records.

Related

How can I get result as struct? (gorm)

My Category Entity is
type Category struct {
CategorySeq uint `json:"categorySeq" gorm:"primaryKey; column:category_seq"`
CategoryName string `json:"categoryName" gorm:"column:category_name"`
CategoryParentSeq uint `json:"-" gorm:"column:category_parent_seq"`
CategoryLevel int `json:"-" gorm:"column:category_level"`
}
The result struct as I want get data as
type ProductCategory struct {
Category1 Category `json:"category1" gorm:"embedded"`
Category2 Category `json:"category2" gorm:"embedded"`
Category3 Category `json:"category3" gorm:"embedded"`
}
And my database data is
table : category
category_seq | category_nanme | category_parent_seq
1 first 0
2 second 1
3 third 2
table : product
product_seq | category_seq
1 1
The result I want unmarshal Json as
"category": {
"category1": {
"categorySeq": 0,
"categoryName": ""
},
"category2": {
"categorySeq": 0,
"categoryName": ""
},
"category3": {
"categorySeq": 0,
"categoryName": ""
}
},
But I don't know how to get category result considering with parent_seq
so I try to use sql query like this
First I tried to select result as this struct
type CategoryRes struct {
CategorySeq1 uint `json:"categorySeq1,omitempty" gorm:"-"`
CategoryName1 string `json:"categoryName1,omitempty" gorm:"-"`
CategorySeq2 uint `json:"categorySeq2,omitempty" gorm:"-"`
CategoryName2 string `json:"categoryName2,omitempty" gorm:"-"`
CategorySeq3 uint `json:"categorySeq3,omitempty" gorm:"-"`
CategoryName3 string `json:"categoryName3,omitempty" gorm:"-"`
}
and use this orm query to get result as CategoryRes struct
func GetProductCategory(productSeq uint) *products.CategoryRes {
categoryRes := new(products.CategoryRes)
err := orm.GetData().
Model(&products.Category{}).
Select(
`category.category_seq AS CategorySeq3, category.category_name AS CategoryName3,
c2.category_seq AS CategorySeq2, c2.category_name AS CategoryName2,
c3.category_seq AS CategorySeq1, c3.category_name AS CategoryName1`,
).
Joins("LEFT JOIN product p ON p.product_category = category.category_seq").
Joins("LEFT JOIN category c2 ON category.category_parent_seq = c2.category_seq").
Joins("LEFT JOIN category c3 ON c2.category_parent_seq = c3.category_seq").
Where("p.product_seq = ?", productSeq).
Find(&categoryRes).Error
print(categoryRes)
if err != nil {
print("error category")
}
return categoryRes
}
but it is not mapping any fields...
I don't know why
If you give me hint It will very helpful to me.

GoLang How to load nested objects using GORM

Hi let's say that I have 3 Structs in the following format
type Employee struct {
Id int
Name string
CompanyId int `gorm:"column:companyId"`
Company Company `gorm:"foreignKey:CompanyId"`
}
type Company struct {
Id int
CompanyName string
OwnerId `gorm:"column:owner"`
Owner Owner `gorm:"foreignKey:OwnerId"`
}
type Owner struct {
Id int
Name string
Age int
Email string
}
func (E Employee) GetAllEmployees() ([]Employee, error) {
Employees := []Employee
db.Preload("Company").Find(&Employees)
}
// -- -- There response will be like
[
{
id: 1
name: "codernadir"
company: {
id: 5
company_name: "Company"
owner: {
id 0
Name ""
Age 0
Email ""
}
}
}
]
here I'm getting Owner values with the default values.
the given examples are for describing what I'm trying to reach.
I need a way how to load the Owner struct with its values when I load the Employees?
any suggestions will be appreciated and thanks in advance
You can use the gorm:"embedded" tag:
type Employee struct {
Id int
Name string
CompanyId int `gorm:"column:companyId"`
Company Company `gorm:"embedded"`
}
type Company struct {
Id int
CompanyName string
OwnerId `gorm:"column:owner"`
Owner Owner `gorm:"embedded"`
}
type Owner struct {
Id int
Name string
Age int
Email string
}
this is what I found as a solution to load the nested objects from embedded structs
db.Preload("Company").Preload("Company.Owner").Find(&Employees)

How to update values for all rows having null value | Prisma | Type script | MySQL

I have prisma schema like below
model t1 {
id Int #id #default(autoincrement())
title String
previousNodeId Int? #unique
}
and I wanted to update title of rows who have null values in previousNodeId
I have written query
await prisma.t1.update({
where: { previousNodeId: null },
data: {
title:"update title"
}
});
but I am not able to update it.
Getting error Type 'null' is not assignable to type 'number | undefined'.
The expected type comes from property 'previousNodeId' which is declared here on type 'T1WhereUniqueInput'
I am able to get all rows using findMany.
await prisma.t1.findMany({
where: { previousNodeId: null },
});
Result of findMany
[
{
id: 3,
title: 'demo t1 1',
previousNodeId: null
}
]

How to decode a JSON array into Elm list of custom types

I want to decode a JSON array of payload objects into List Payload where each Payload is a custom type:
type Payload
= PayloadP1 P1
| PayloadP2 P2
After decoding PayloadP1 and PayloadP2 using decoders below how do I decode Payload?
type alias P1 =
{ id : Int
, st : String
}
type alias P2 =
{ id : Int
, s1 : String
, s2 : String
}
type Payload
= PayloadP1 P1
| PayloadP2 P2
type alias PayloadQueue = List Payload
decodeP1 : Jd.Decoder P1
decodeP1 =
Jd.map2 P1
(Jd.field "id" Jd.int)
(Jd.field "st" Jd.string)
decodeP2 : Jd.Decoder P2
decodeP2 =
Jd.map3 P2
(Jd.field "id" Jd.int)
(Jd.field "p1" Jd.string)
(Jd.field "p2" Jd.string)
decodePayload =
Jd.field ".type" Jd.string
|> Jd.andThen decodePayload_
{-
decodePayload_ : String -> Jd.Decoder Payload
decodePayload_ ptype =
case ptype of
"P1" -> decodeP1
"P2" -> decodeP2
-}
json_str = """[
{".type" : "P1", "id" : 1, "st" : "st"},
{".type" : "P2", "id" : 2, "p1" : "p1", "p2" : "p2"},
]"""
You need to wrap P1 and P2 in PayloadP1 and PayloadP2 respectively in order to return a common type from each branch, which you can do using map. Then you also need to account for the possibility that the type field is neither P1 or P2. In that case you can either provide a default or return an error using fail. I've done the latter below.
decodePayload_ : String -> Jd.Decoder Payload
decodePayload_ ptype =
case ptype of
"P1" -> decodeP1 |> Jd.map PayloadP1
"P2" -> decodeP2 |> Jd.map PayloadP2
_ -> Jd.fail "invalid type"

Scala : How to do GroupBy sum for String values?

I have RDD[Row] :
|---itemId----|----Country-------|---Type----------|
| 11 | US | Movie |
| 11 | US | TV |
| 101 | France | Movie |
How to do GroupBy itemId so that I can save the result as List of json where each row is separate json object(each row in RDD) :
{"itemId" : 11,
"Country": {"US" :2 },"Type": {"Movie" :1 , "TV" : 1} },
{"itemId" : 101,
"Country": {"France" :1 },"Type": {"Movie" :1} }
RDD :
I tried :
import com.mapping.data.model.MappingUtils
import com.mapping.data.model.CountryInfo
val mappingPath = "s3://.../"
val input = sc.textFile(mappingPath)
The input is list of jsons where each line is json which I am mapping to the POJO class CountryInfo using MappingUtils which takes care of JSON parsing and conversion:
val MappingsList = input.map(x=> {
val countryInfo = MappingUtils.getCountryInfoString(x);
(countryInfo.getItemId(), countryInfo)
}).collectAsMap
MappingsList: scala.collection.Map[String,com.mapping.data.model.CountryInfo]
def showCountryInfo(x: Option[CountryInfo]) = x match {
case Some(s) => s
}
val events = sqlContext.sql( "select itemId EventList")
val itemList = events.map(row => {
val itemId = row.getAs[String](1);
val çountryInfo = showTitleInfo(MappingsList.get(itemId));
val country = if (countryInfo.getCountry() == 'unknown)' "US" else countryInfo.getCountry()
val type = countryInfo.getType()
Row(itemId, country, type)
})
Can some one let me know how can I achieve this ?
Thank You!
I can't afford the extra time to complete this, but can give you a start.
The idea is that you aggregate the RDD[Row] down into a single Map that represents your JSON structure. Aggregation is a fold that requires two function parameters:
seqOp How to fold a collection of elements into the target type
combOp How to merge two of the target types.
The tricky part comes in combOp while merging, as you need to accumulate the counts of values seen in the seqOp. I have left this as an exercise, as I have a plane to catch! Hopefully someone else can fill in the gaps if you have trouble.
case class Row(id: Int, country: String, tpe: String)
def foo: Unit = {
val rows: RDD[Row] = ???
def seqOp(acc: Map[Int, (Map[String, Int], Map[String, Int])], r: Row) = {
acc.get(r.id) match {
case None => acc.updated(r.id, (Map(r.country, 1), Map(r.tpe, 1)))
case Some((countries, types)) =>
val countries_ = countries.updated(r.country, countries.getOrElse(r.country, 0) + 1)
val types_ = types.updated(r.tpe, types.getOrElse(r.tpe, 0) + 1)
acc.updated(r.id, (countries_, types_))
}
}
val z = Map.empty[Int, (Map[String, Int], Map[String, Int])]
def combOp(l: Map[Int, (Map[String, Int], Map[String, Int])], r: Map[Int, (Map[String, Int], Map[String, Int])]) = {
l.foldLeft(z) { case (acc, (id, (countries, types))) =>
r.get(id) match {
case None => acc.updated(id, (countries, types))
case Some(otherCountries, otherTypes) =>
// todo - continue by merging countries with otherCountries
// and types with otherTypes, then update acc
}
}
}
val summaryMap = rows.aggregate(z) { seqOp, combOp }