knex increment upsert - increment if record creation fails - sql

I want to try and create a new record, but if that fails, simply update (increment) a value in that record
await databaseService.knex('myTable')
.insert({
id: id1,
value: 0
})
.onConflict(['id1'])
.increment({
value: 1
});
Unfortunately it seems you cannot chain .increment after onConflict. I am wondering if there is a way I can do this with knex or do I need to drop into raw SQL?
Thanks

With on conflict for update part merge should be used https://knexjs.org/#Builder-merge
something like this might work:
await databaseService.knex('myTable')
.insert({
id: id1,
value: 0
})
.onConflict(['id'])
.merge({
value: knex.raw("?? + ?", ["value", 1])
});
https://runkit.com/embed/krdgetjij9xh

Related

Typeorm respository find where with select columns

I am trying to implement single query with a where clause and select columns:
Main Query in SQL form:
SELECT name from users WHERE flag = 1;
Now what I have tried so far is:
userRepository.find({
where: {
flag: 1
},
select: {
name: true
}
})
My query works fine if I don't add select option, but with select provided it gives me error.
Any idea what I am doing wrong here?
Try to select like this
userRepository.find({
where: {
flag: 1
},
select: ['name','id']
})

TypeORM relationquerybuilder of remove with Not(IsNull()) not removing anything

Good day everyone,
I ran into a strange problem with typeORM. I have a many-to-many relation on Offer with User named pending, which creates a table offer_pending_user that looks like:
userId
offerId
0
1
1
0
I basically want to completely clear this table. I tried to achieve this by using the RelationQueryBuilder like follows:
await Offer.createQueryBuilder()
.relation("pending")
.of({ id: Not(IsNull()) }) //offer id
.remove({ id: Not(IsNull()) }); //user id
For some reason. It does not clear the offer_pending_user table at all. The query that it is executing looks like:
DELETE FROM "offer_pending_user" WHERE ("offerId" = ? AND "userId" = ?) -- PARAMETERS:
[{
"_type":"not",
"_value": {
"_type":"isNull",
"_useParameter":false,
"_multipleParameters":false
},
"_useParameter":true,
"_multipleParameters":false
},{
"_type":"not",
"_value": {
"_type":"isNull",
"_useParameter":false,
"_multipleParameters":false
},
"_useParameter":true,
"_multipleParameters":false
}]
I would like to use this RelationQueryBuilder, and would like to know what I'm missing here.

Sequlize Query get last added value

I am using Sequlize. I have a table status_config in this table I have a column create_time as timestamp( 2021-06-02 12:04:52.293977). Now I need to query on this table and get the latest value created on this table.
status_config.findOne({ where: created_time **need to implement here to get last added value})
We can use order by [['createdAt', 'desc']]
let last_status_config = await status_config.findOne({
order:[['createdAt', 'desc']]
});
console.log(JSON.parse(JSON.stringify(last_status_config)))
Output
{ id: 19, name: 'test_last', password: null, confirmation: null }

How to make complex nested where conditions with typeORM?

I am having multiple nested where conditions and want to generate them without too much code duplication with typeORM.
The SQL where condition should be something like this:
WHERE "Table"."id" = $1
AND
"Table"."notAvailable" IS NULL
AND
(
"Table"."date" > $2
OR
(
"Table"."date" = $2
AND
"Table"."myId" > $3
)
)
AND
(
"Table"."created" = $2
OR
"Table"."updated" = $4
)
AND
(
"Table"."text" ilike '%search%'
OR
"Table"."name" ilike '%search%'
)
But with the FindConditions it seems not to be possible to make them nested and so I have to use all possible combinations of AND in an FindConditions array. And it isn't possible to split it to .where() and .andWhere() cause andWhere can't use an Object Literal.
Is there another possibility to achieve this query with typeORM without using Raw SQL?
When using the queryBuilder I would recommend using Brackets
as stated in the Typeorm doc: https://typeorm.io/#/select-query-builder/adding-where-expression
You could do something like:
createQueryBuilder("user")
.where("user.registered = :registered", { registered: true })
.andWhere(new Brackets(qb => {
qb.where("user.firstName = :firstName", { firstName: "Timber" })
.orWhere("user.lastName = :lastName", { lastName: "Saw" })
}))
that will result with:
SELECT ...
FROM users user
WHERE user.registered = true
AND (user.firstName = 'Timber' OR user.lastName = 'Saw')
I think you are mixing 2 ways of retrieving entities from TypeORM, find from the repository and the query builder. The FindConditions are used in the find function. The andWhere function is use by the query builder. When building more complex queries it is generally better/easier to use the query builder.
Query builder
When using the query build you got much more freedom to make sure the query is what you need it to be. With the where you are free to add any SQL as you please:
const desiredEntity = await connection
.getRepository(User)
.createQueryBuilder("user")
.where("user.id = :id", { id: 1 })
.andWhere("user.date > :date OR (user.date = :date AND user.myId = :myId)",
{
date: specificCreatedAtDate,
myId: mysteryId,
})
.getOne();
Note that depending on your used database the actual SQL that you use here needs to be compatible. With that could also come a possible draw back of using this method. You will tie your project to a specific database. Make sure to read up about the aliases for tables you can set if you are using relations this would be handy.
Repository
You already saw that this is much less comfortable. This is because the find function or more specific the findOptions are using objects to build the where clause. This makes is harder to implement a proper interface to implement nested AND and OR clauses side by side. There for (I assume) they have chosen to split AND and OR clauses. This makes the interface much more declarative and means the you have to pull your OR clauses to the top:
const desiredEntity = await repository.find({
where: [{
id: id,
notAvailable: Not(IsNull()),
date: MoreThan(date)
},{
id: id,
notAvailable: Not(IsNull()),
date: date
myId: myId
}]
})
I cannot imagin looking a the size of the desired query that this code would be very performant.
Alternatively you could use the Raw find helper. This would require you to rewrite your clause per field, since you will only get access to the one alias at a time. You could guess the column names or aliases but this would be very poor practice and very unstable since you cannot directly control this easily.
if you want to nest andWhere statements if a condition is meet here is an example:
async getTasks(filterDto: GetTasksFilterDto, user: User): Promise<Task[]> {
const { status, search } = filterDto;
/* create a query using the query builder */
// task is what refer to the Task entity
const query = this.createQueryBuilder('task');
// only get the tasks that belong to the user
query.where('task.userId = :userId', { userId: user.id });
/* if status is defined then add a where clause to the query */
if (status) {
// :<variable-name> is a placeholder for the second object key value pair
query.andWhere('task.status = :status', { status });
}
/* if search is defined then add a where clause to the query */
if (search) {
query.andWhere(
/*
LIKE: find a similar match (doesn't have to be exact)
- https://www.w3schools.com/sql/sql_like.asp
Lower is a sql method
- https://www.w3schools.com/sql/func_sqlserver_lower.asp
* bug: search by pass where userId; fix: () whole addWhere statement
because andWhere stiches the where class together, add () to make andWhere with or and like into a single where statement
*/
'(LOWER(task.title) LIKE LOWER(:search) OR LOWER(task.description) LIKE LOWER(:search))',
// :search is like a param variable, and the search object is the key value pair. Both have to match
{ search: `%${search}%` },
);
}
/* execute the query
- getMany means that you are expecting an array of results
*/
let tasks;
try {
tasks = await query.getMany();
} catch (error) {
this.logger.error(
`Failed to get tasks for user "${
user.username
}", Filters: ${JSON.stringify(filterDto)}`,
error.stack,
);
throw new InternalServerErrorException();
}
return tasks;
}
I have a list of
{
date: specificCreatedAtDate,
userId: mysteryId
}
My solution is
.andWhere(
new Brackets((qb) => {
qb.where(
'userTable.date = :date0 AND userTable.type = :userId0',
{
date0: dates[0].date,
userId0: dates[0].type,
}
);
for (let i = 1; i < dates.length; i++) {
qb.orWhere(
`userTable.date = :date${i} AND userTable.userId = :userId${i}`,
{
[`date${i}`]: dates[i].date,
[`userId${i}`]: dates[i].userId,
}
);
}
})
)
That will produce something similar
const userEntity = await repository.find({
where: [{
userId: id0,
date: date0
},{
id: id1,
userId: date1
}
....
]
})

knex insert multiple rows

I have a problem inserting many rows into postgres db with knex.
I have dynamic number of rows needed to be inserted. The result i expect is:
insert row four times (four is for an example. I dont know exact number of inserts as it comes dynamically from frontend):
field_id will be diffrent in every row: (1,2,3,4) - i have array of these ID's
id_of_product will be always the same
value will be always diffrent: (req.body[id] that comes from Frontend) - ID in brackets is same value as the field_id from an
array
How i can achieve that? I tried looping it with forEach, but it's async operation so i can't use .then() as it will be called four times
Here's what i tried. i dont know how to set field_id and req.body to take it dynamically.
fields = [1,2,3,4]
Expected result:
knex creates 4 inserts as follows:
field_id: 1,
product_id: some static id
value: frontValue[1]
ETC
knex('metadata').insert(
[{ field_id: fields,
product_id: product_id,
value: req.body[fields]
}]
)
If I understand correctly you want to insert 4 records to your metadata table:
{ field_id: 1, product_id: X, value: req.body[1] },
{ field_id: 2, product_id: X, value: req.body[2] },
{ field_id: 3, product_id: X, value: req.body[3] },
{ field_id: 4, product_id: X, value: req.body[4] }
To insert multiple records in the same statement they each need to be separate elements in the array that you supply to Knex (check out the insert docs for additional examples):
const product_id = X;
const fieldsToInsert = fields.map(field =>
({ field_id: field, product_id, value: req.body[field] }));
return knex('metadata').insert(fieldsToInsert)
.then(() => { /* handle success */ })
.catch(() => { /* handle failure */});