How to insert data into postgres using []struct{} using gorm? - database

I have code like this:
func o(){
var obj []struct {
Field1 string `json:"field1"`
Field2 string `json:"field2"`
Field3 string `json:"field3"`
}
}
I want to insert this []struct into database using another concurrent function which is being declared outside of this function.
how do I insert this type of data using gorm?

Related

Fetching a struct and other data in one query

I have the following table schema:
user
-----
id uuid
name string
user_model
------
id uuid
user_id uuid
model_id uuid
role int
model
_____
id uuid
name string
model_no string
I have the following code which fetches the data from the "model" table.
underlyingModel = &model{}
var model IModel
model = underlyingModel
role := 0
db.Table("model").Joins('INNER JOIN user_model ON user.id = user_model.uuid')
.Joins('INNER JOIN model ON user.id = model_id').Find(&model);
In my actual code, the model can be many different struct types with different fields, they're all behind the IModel interface.
What I want to do is to fetch that extra role field from the user_model in one query. Something like .Find(&model, &role).
Is it possible using Gorm?
One possible solution is to create an anonymous struct to put the results in, with a combination of the Select() method.
var selectModel struct {
ID string //I'm assuming uuid matches the string
Name string
ModelNo string
Role int
}
db.Table("model").
Joins("INNER JOIN user_model ON user.id = user_model.uuid").
Joins("INNER JOIN model ON user.id = model_id").
Select("model.id, model.name, model.model_no, user_model.role").
Find(&selectModel);
Basically, you create an anonymous struct with selectModel variable, containing all the fields you want to return. Then, you need to do a select statement because you need some fields that are not part of the model table.
Here you can find more info on Smart Select Fields in form.
EDIT:
Based on additional info from the comments, there is a solution that might work.
Your IModel interface could have two methods in its signature, one to extract a string for the SELECT part of the SQL query, and the other one to get a pointer of the selectModel that you would use in the Find method.
type IModel interface {
SelectFields() string
GetSelectModel() interface{}
}
The implementation would go something like this:
func (m *model) SelectFields() string {
return "model.id, model.name, model.model_no, user_model.role"
}
func (m *model) GetSelectModel() interface{} {
return &m.selectModel
}
type model struct {
selectModel
ID uint64
Age int
}
type selectModel struct {
Name string
Email string
}
Then, your query could look something like this:
var m IModel
m = model{}
db.Table("model").
Joins("INNER JOIN user_model ON user.id = user_model.uuid").
Joins("INNER JOIN model ON user.id = model_id").
Select(m.GetSelectFields()).
Find(m.GetSelectModel());

How to use not contains in Sequelize query

I am using Sequelize query for postgrsql db.
I have one field in table, that's type is JSONB. I would like to get data from table like not contain particular value from that field.
For example:
I have field 'field1' JSONB type.
field1 :[8,10,23] values
No need to fetch particular row, if the field1 have value 8. Those rows don't have field1 with 8 i need to fetch those rows.
{
[Op.not]:{
field1:
{
[Op.contains]: [8]
}
}
}
I tried above query but its not getting.
Try this:
{
field1:
{
[Op.not]:{
[Op.contains]: [8]
}
}
}

Using go-pg to retrieve virtual columns from Postgres

I'm using go-pg (https://github.com/go-pg/pg) and this code:
type Book struct {
id int
name string
}
var books []Book
err := db.Model(&books).Select()
and everything works good but I need to add a "virtual" column like this:
concat ('info:', 'id:', id, '...') AS info
and I tried to use:
query.ColumnExpr("concat ('info:', 'id:', id, '...') AS info")
but:
go-pg complains with: error="pg: can't find column=info in model=Book (try discard_unknown_columns)"
go-pg doesn't include anymore columns id and name in query: concat... ONLY!
I can understand that because now go-pg doesn't know how to bind data, but I really need that string which I can retrieve from DB only.
Is there a way?
Can I use a custom type like this below?
type CustomBook struct {
Info string
Book
}
Does this make sense?
this approach could work for you:
type Book struct {
ID int
Name string
Info string `pg:"-"`
}
...
db.Model(&books).ColumnExpr("book.*").ColumnExpr("CONCAT('id:', id, 'name:', name) AS info").Select()
pg:"-" ignores the struct field and it is not created nor it produces any errors
this ignored column is documented here: https://pg.uptrace.dev/models/
another approach, depending on your requirements could be like this:
var r []struct {
Name string
Info string
}
db.Model((*Book)(nil)).Column("name").ColumnExpr("CONCAT('id:', id, 'name:', name) AS info").Select(&r)
this second one is documented here: https://pg.uptrace.dev/queries/

How to insert key value object into lua table inside redis

local users = {}
table.insert(users, {['uid']= 'xxx'})
How to insert object into table in Lua script. When I try to insert, Lua returns empty array, with empty array inside "[[]]".
table.insert(users, 'xxx')
When I insert string, it is properly returned. "['xxx']"
I'm running Lua inside redis. In node.
JavaScript example would be:
const arr = []
arr.push({uid: 'xxx'})
try this method to get element : users[1].uid or users[1].['uid']
local users = {}
table.insert(users, { ['uid'] = 'xxx'})
table.insert(users, { uid = 'yyy'})
print(users[1].uid)
print(users[2].uid)
output:
xxx
yyy

How to concatenate the elements of int array to string in Hive

I'm trying to concatenate the element of int array to one string in hive.
The function concat_ws works only for string arrays, so I tried cast(my_int_array as string) but it's not working.
Any suggestion?
Try to transform using /bin/cat:
from mytable select transform(my_int_array) using '/bin/cat' as (my_int_array);
Second option is to alter table and replace delimiters:
1) ALTER TABLE mytable CHANGE COLUMN my_int_array = my_int_array_string string;
2) SELECT REPLACE(my_int_array_string, '\002', ', ') FROM mytable;
It seems that the easiest way is to write a custom UDF to perform this specific task:
public class ConcatIntArray extends UDF {
public String evaluate(ArrayList<Integer> in, final String delimiter){
return in.stream().map(u-> String.valueOf(u)).collect(Collectors.joining(delimiter));
}
}

Resources