How to specify unique together index in gorm? - postgresql

type ABC struct {
ID uint
Abc int `gorm:"unidqueIndex;
Bcd string
}
I want Field Abc and Bcd to be unique together
{Abc: 1, Bcd: "hello"} {Abc: 1, Bcd: "hi"} should be valid but
{Abc: 1, Bcd: "hello"} {Abc: 1, Bcd: "hello"} should be invalid

Give both fields the same index name.
type ABC struct {
ID uint
Abc int `gorm:"uniqueIndex:abc_bcd_uniq"`
Bcd string `gorm:"uniqueIndex:abc_bcd_uniq"`
}
See composite indexes in the GORM docs.

Related

How to extract json string value in scala

So i have a json file in which i have schema like this:
{
"Field": "{\"key1\":\"Value1\",\"key2\":\"Value2\"}
}
I want to extract value of key1 & key2 which is Value1 & Value2

How to create a Hash in Neo4j from given string?

I do the following
CREATE (p:person { FirstName:"M", LastName: "H" , Language: "en", hash: apoc.util.sha512('1234567','salt')});
Error:
Function call does not provide the required number of arguments: expected 1 got 2.
Function apoc.util.sha512 has signature: apoc.util.sha512(values :: LIST? OF ANY?) :: STRING?
meaning that it expects 1 argument of type LIST? OF ANY?
Description: apoc.util.sha512([values]) | computes the sha512 of the concatenation of all string values of the list (line 2, column 73 (offset: 73))
"CREATE (p:person { FirstName:"M", LastName: "H" , Language: "en", hash: apoc.util.sha512('1234567','salt')});"
what is a Type of List argument?
thanks rob
Have it - i used []
CREATE (p:person { FirstName:"M", LastName: "H" , Language: "de", hash: apoc.util.sha512(["1234567","salt"])});

Convert JSON.RawMessage to JSON

I am using gqlgen, sqlx and pgx. And I'm trying to use a custom scalar for sqlx's types.JSONText.
I have this attributes jsonb field in items table.
-- migrations/001_up.sql
CREATE TABLE IF NOT EXISTS items (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
quantity INT NOT NULL,
attributes JSONB
);
I have these model structs:
// graph/model/item.go
type Item struct {
ID string `json:"id,omitempty" db:"id,omitempty"`
Quantity int `json:"quantity" db:"quantity"`
Attributes *Attributes `json:"attributes,omitempty" db:"attributes,omitempty"`
}
type Attributes types.JSONText
I have this graphql schema:
// graph/schema.graphql
type Item {
id: ID!
quantity: Int!
attributes: Attributes
}
scalar Attributes
I can successfully inserted into database, but got error at retrieving.
| id | quantity | attributes |
|---------------|----------|------------------------------------|
| 031e1489-... | 100 | {"size": "medium", "color": "red"} |
This is the log I got from db query:
>> items.Db: &{
031e1489-02c9-46d3-924d-6a2edf1ca3ba // id
100 // quantity
0xc000430600 // attributes
}
I tried to marshal attributes scalar:
// graph/model/item.go
...
func (a *Attributes) MarshalGQL(w io.Writer) {
b, _ := json.Marshal(a)
w.Write(b)
}
// Unmarshal here
...
Add custom scalar type in gqlgen.yml:
...
Attributes:
model:
- github.com/my-api/graph/model.Attributes
But I got the string instead of json:
{
"data": {
"item": {
"id": "031e1489-02c9-46d3-924d-6a2edf1ca3ba",
"quantity": 100,
"attributes": "eyJjb2xvciI6ICJyZWQifQ==",
}
}
}
The desired output is:
{
"data": {
"item": {
"id": "031e1489-02c9-46d3-924d-6a2edf1ca3ba",
"quantity": 100,
"attributes": {
"size": "medium",
"color": "red",
}
}
}
}
What I am doing wrong?
Here are my attempts:
If I removed pointer from Attributes in Item struct, gqlgen throws error:
go generate ./...
go: finding module for package github.com/my-api/graph/generated
generating core failed: type.gotpl: template: type.gotpl:49:28: executing "type.gotpl" at <$type.Elem.GO>: nil pointer evaluating *config.TypeReference.GOexit status 1
graph/resolver.go:3: running "go": exit status 1
make: *** [Makefile:2: gengql] Error 1
This returns the desired result, but I don't know how to use it with real data:
func (a *Attributes) MarshalGQL(w io.Writer) {
raw := json.RawMessage(`{"foo":"bar"}`)
j, _ := json.Marshal(&raw)
s := string(j)
w.Write([]byte(s))
}
Query result:
{
"data": {
"item": {
"id": "031e1489-02c9-46d3-924d-6a2edf1ca3ba",
"quantity": 100,
"attributes": {
"foo": "bar"
}
}
}
}
Attributes is defined using types.JSONText which is defined using json.RawMessage which is defined using []byte. This means that the underlying type of all 4 types, including []byte, is []byte, which in turn means that all of the 4 types can be converted to []byte.
Hence it should be enough to do this:
func (a *Attributes) MarshalGQL(w io.Writer) {
w.Write([]byte(*a))
}

postgres, go-gorm - can't preload data

I am trying to preload some data when querying for a row on my postgresql with gorm
I have the following types defined in go with a belongs to association:
type MyObject struct {
ID uint `grom:"column:id" json:"id"`
Name string `gorm:"column:name" json:"name"`
OwnerID uint `gorm:"column:owner_id" json:"owner_id"`
Owner Owner `json:"owner"`
...
}
type Owner struct {
ID uint `gorm:"column:id" json:"id"`
Name string `gorm:"column:name" json:"name"`
Config json.RawMessage `gorm:"column:config" sql:"type:json" json:"config"`
Components []uint8 `gorm:"column:components;type:integer[]" json:"components"`
}
and the tables in the postgres db with a row as follows
my_schema.my_object
id | name | owner_id | ...
----|-----------|-----------|-----
0 | testobj | 0 | ...
my_schema.owner
id | name | config | components
----|-----------|-----------|-----------
0 | testowner | <jsonb> | {0,1,2,3}
I am running the following query with gorm:
object := &models.MyObject{}
result := ls.Table("my_schema.my_object").
Preload("Owner").
Where("id = ?", "0").
First(object)
but as a result, in object i get the following struct:
{"id": 0, "name": "testobj", "owner_id":0, "owner": {"id": 0, "name": "", "config": nil, "components": nil}}
I get no errors or warnings of any kind
the foreignkey relation was specified in the database creation sql script
I was able to achieve what I wanted by implementing the TableName() method for each of my models as such:
type MyObject struct {
ID uint `grom:"column:id" json:"id"`
OwnerID uint `gorm:"column:owner_id" json:"owner_id"`
Owner Owner `json:"owner"`
...
}
func (MyObject) TableName() {
return "my_schema.my_object"
}
type Owner struct {
ID uint `gorm:"column:id" json:"id"`
...
}
func (Owner) TableName() {
return "my_schema.owner"
}
Then, I can then use it in a query like the following:
myObject := &models.MyObject{}
result := ls.Model(myObject).
Where("id = ?", id). //assume any valid value for id
First(myObject).
Related(&myObject.Owner)
return myObject, processResult(result)
in the end, when making a request for MyObject to my server I get all the data of the related Owner object in the database:
$ curl "http://localhost:8080/api/objetcs/related/1" | jq // passing 1 as object id value in url params
{
"id": "1", // taken from UrlParam
"name": "testobj",
"owner": {
"id": "1", // using foreign key owner_id
"name": "testowner",
"config": configJson // json object taken from row in my_schema.owner table in the DB
}
}
}

Cannot save structure into mongodb with golang (only empty records created)

I have the following structure
type Result struct {
nid string
timestamp int64
hexhash string
addr string
}
which I want to save into mongodb:
I create it
r := Result{hex_id, int64(msg.timestamp.Unix()), hexhash, msg.addr.String()}
And test if it is created correctly:
fmt.Println(r)
Which gives me result I'm expecting:
{b8da3f19d1318af6879976c1eea66c78c48e1144 1421417252
65072917F19D7F4C4B54C9C66A3EB31F77012981 127.0.0.1:65290}
Then I save it into mongo:
h.c.Insert(r)
But in mongo i see only empty records:
db.data.find()
{ "_id" : ObjectId("54b91a268da6c829a412cd4d") }
The h in the code above defined as
type Handler struct {
storage map[string]Message
new_msg chan Message
new_inp chan Input
c *mgo.Collection
}
and
h.c = session.DB(DATABASE).C(COLLECTION)
The fileds of your record need to be public for other packages (like the MongoDB wrapper) to see them. Rename the fields like this:
type Result struct {
Nid string
Timestamp int64
Hexhash string
Addr string
}