Sequelize bulk update with inner join - postgresql

I am currently working with Sequelize and can not figure out how to update bulk when im associating two tables together. I have the follow:
Tables:
members
user_id
channel_id
all
activities
user_id
channel_id
I am trying to update members.all when the user_ids match, members.channel_id is 2 and activities.channel_id is not 2.
Here is working Postgresql:
UPDATE members AS m
SET "all" = true
FROM activities AS a
WHERE m.user_id = a.user_id
AND m.channel_id = 2
AND a.current_channel != 2;
Is this possible to do is sequelize? How do include a.current_channel != 2 into my current update?
Member.update(
{ all: true },
{ where: { channel_id: channelId } },
)
When I try to add an include it does not work.

I think you can't do something like that using Sequelize update method. I would use the include option in a findAll method, but as far as I can see on the documentation, there is no include option for the update method.
You could use a raw query to use directly the query.
sequelize.query("UPDATE members AS m SET "all" = true FROM activities AS a WHERE m.user_id = a.user_id AND m.channel_id = 2 AND a.current_channel != 2").spread((results, metadata) => {
// Results will be an empty array and metadata will contain the number of affected rows.
});

Generally, i use this hack
models.findAll({
where: {
// which models to update
}
}).then(targets => {
models.target.update({
// your updates
},{
where : {
target_primary_key: targets.map(t => t.primary_key)
}
})
})

Related

Update a collection in Mongo based on antothe collection with a "join"

I using Mongo version 4.2
I need to update a field in one collection as based on a field from another collection, according to a joining condiiton between the to collection.
In a regualr SQL, the update would be:
UPDATE col1, col2
SET col2.entityId = col1.Entity_ID
WHERE col1.id = col2.id
and col2.type='DEVICE';
I tried a method offered in one answer, but that does not seem to work, or I did not understand it correctly:
db.col1.find().forEach(function (doc1) {
var doc2 = db.col2.findOne({ id: doc1.id },{type:"DEVICE"});
if (doc2 != null) {
doc1.Entity_ID=doc2.entityId;
db.coll01.save(doc1);
}
});
Any ideas?
Thanks,
Tamar

Prisma: Finding items where two fields have the same value

I would like to find items in a Prisma db where the values for two columns are the same. The use case is to compare the 'created_at' and 'updated_at' fields to find items that have never been updated after their initial creation. In raw SQL I would do something like:
select updated_at,
cast(sign(sum(case when updated_at = created_at then
1
else
0
end)) as int) as never_modified
from tab
group by updated_at
Is it possible to achieve this in Prisma?
You would need to use Raw Queries to compare time values from the same table.
Here's an example of how you could achieve this, assuming a PostgreSQL database for the following query.
import { PrismaClient } from '#prisma/client'
const prisma = new PrismaClient()
async function initiateDatesComparisonRawQuery() {
const response =
await prisma.$queryRaw`SELECT * FROM "public"."Project" WHERE "created_at" = "updated_at";`;
console.log(response);
}
await initiateDatesComparisonRawQuery();
you can use the preview feature fieldReference of prisma.
schema.prisma
generator client {
provider = "prisma-client-js"
previewFeatures = ["fieldReference"]
}
your code
prisma.project.findMany({
where: { created_at: prisma.project.fields.updated_at }
})

TypeORM / Postgres - Include all in relation where at least one meets requirement

I am very new to SQL/TypeORM in general and I'm currently facing a problem where I want to load match participants related to a match where at least one participant has a passed userId. The query could be thought of as "Load all my matches with my opponents". I have three tables:
public.match << OneToMany >> public.match_participant << ManyToOne >> public.user
So far I have gone about doing:
select * from public.match m
left join public.match_participant mp on mp."matchId" = m.id
left join public.user u on u.id = mp."userId"
where u.id = 3
and in typeORM
repository
.createQueryBuilder('match')
.leftJoinAndSelect('match.participants', 'participants')
.leftJoinAndSelect('participants.user', 'user')
.where('user.id=:id')
.setParameter('id', 1)
.getMany();
Which of course loads all matches, participants and users for that particular userId but other participants are not included. I believe something like a "subquery" could be of use but I can't seem to figure it out.
Any help is greatly appreciated!
Thanks in advance.
After a bunch of trial and error I learned how to convert a pure query to the builder. The solution was the following:
matchRepository
.createQueryBuilder('match')
.innerJoin(
query => {
return query
.from(MatchParticipant, 'p')
.select('p."matchId"')
.where('p."userId" = :id');
},
'selfMatch',
'"selfMatch"."matchId" = match.id',
)
.leftJoinAndSelect('match.participants', 'participants')
.leftJoinAndSelect('participants.user', 'user')
.setParameter('id', id)
.getMany();
I don't think you even need the query builder for this.
#Entity()
class Match {
#OneToMany(...)
participants: MatchParticipant[];
}
#Entity()
class MatchParticipant {
#ManyToOne(...)
match: Match;
#ManyToOne(...)
participant: Participant;
}
#Entity()
class User {
#OneToMany(...)
matches: MatchParticipant[];
}
// ...
repository.manager.find(MatchParticipant, { where: { match: { participants: { participant: { id } } } } });

.Include in following query does not include really

var diaryEntries = (from entry in repository.GetQuery<OnlineDiary.Internal.Model.DiaryEntry>()
.Include("DiaryEntryGradeChangeLog")
.Include("DiaryEntryAction")
join diary in repository.GetQuery<OnlineDiary.Internal.Model.OnlineDiary>()
on entry.DiaryId equals diary.Id
group entry
by diary
into diaryEntriesGroup
select new { Diary = diaryEntriesGroup.Key,
DiaryEntry = diaryEntriesGroup.OrderByDescending(diaryEntry => diaryEntry.DateModified).FirstOrDefault(),
});
This query does not include "DiaryEntryGradeChangeLog" and "DiaryEntryAction" navigation properties, what is wrong in this query?
I have removed join from the query and corrected as per below, and still it populates nothing
var diaryEntries = from entry in repository.GetQuery<OnlineDiary.Internal.Model.DiaryEntry>()
.Include("DiaryEntryGradeChangeLog").Include("DiaryEntryAction")
.Where(e => 1 == 1)
group entry
by entry.OnlineDiary
into diaryEntryGroups
select
new { DiaryEntry = diaryEntryGroups.OrderByDescending(diaryEntry => diaryEntry.DateModified).FirstOrDefault() };
It will not. Include works only if the shape of the query does not change (by design). If you use this query it will work because the shape of the query is still same (OnlineDiary.Internal.Model.DiaryEntry):
var diaryEntries = (from entry in repository.GetQuery<OnlineDiary.Internal.Model.DiaryEntry>()
.Include("DiaryEntryGradeChangeLog")
.Include("DiaryEntryAction");
But once you use manual join, grouping or projection (select new { }) you have changed the shape of the query and all Include calls are skipped.
Edit:
You must use something like this (untested) to get related data:
var diaryEntries = from entry in repository.GetQuery<OnlineDiary.Internal.Model.DiaryEntry>()
group entry by entry.OnlineDiary into diaryEntryGroups
let data = diaryEntryGroups.OrderByDescending(diaryEntry => diaryEntry.DateModified).FirstOrDefault()
select new {
DiaryEntry = data,
GradeChangeLog = data.DiaryEntryGradeChangeLog,
Action = data.DiaryEntryAction
};
or any similar query where you manually populate property for relation in projection to anonymous or unmapped type.

EF Left joining a table on two properties combined with a case statement

I'm trying to write a query for a database that will left join a table to a look up table and the results will be returned based on a case statement.
In normal SQL the query would look like this:
SELECT chis_id, chis_detail, cilt.mhcatID, cilt.mhtID, 'TheFileName' =
CASE
WHEN cilt.mhcatID IS NOT NULL AND cilt.mhtID IS NOT NULL THEN chis_linked_filename
END
FROM chis
LEFT JOIN cilt on cilt.mhcatID = chis.mhcat_id AND cilt.mhtID = chis.mht_id
WHERE cch_id = 50
chis is the table being queried, cilt is a look-up table and does not contain any foreign key relationships to chis as a result (chis has existing FK's to mht and mhcat tables by the mhtID and mhcatID respectively).
The query will be used to return a list of history updates for a record. If the join to the cilt lookup table is successful this means that the caller of the query will have permission to view the filename of any associated files for the history updates.
Whilst during my research I've found various posts on here relating on how to do case statements and left joins in Linq to Entity queries, I've not been able to work out how to join on two different fields. Is this possible?
You need to join on an anonymous type with matching field names like so:
var query = from x in context.Table1
join y in context.Table2
on new { x.Field1, x.Field2 } equals new { y.Field1, y.Field2 }
select {...};
A full working example using the an extra from instead of a join would look something like this:
var query = from chis in context.Chis
from clit in context.Clit
.Where(x => x.mhcatID = chis.mhcat_id)
.Where(x => x.mhtID = chis.mht_id)
.DefaultIfEmpty()
select new
{
chis.id,
chis.detail,
cilt.mhcatID,
cilt.mhtID,
TheFileName = (cilt.mhcatID != null && cilt.mhtID != null) ? chis.linked_filename : null
};
Based on what Aducci suggested, I used a group join and DefaultIsEmpty() to get the results I wanted. For some reason, I couldn't get DefaultIfEmpty() didn't work correctly on its own and the resulting SQL employed an inner join instead of a left.
Here's the final code I used to get the left join working:
var query = (from chis in context.chis
join cilt in context.cilts on new { MHT = chis.mht_id, MHTCAT = chis.mhcat_id } equals new { MHT = cilt.mhtID, MHTCAT = cilt.mhcatID } into tempCilts
from tempCilt in tempCilts.DefaultIfEmpty()
where chis.cch_id == 50
select new {
chisID = chis.chis_id,
detail = chis.chis_detail,
filename = chis.chis_linked_filename,
TheFileName = (tempCilt.mhcatID != null && tempCilt.mhtID != null ? chis.chis_linked_filename : null),
mhtID = chis.mht_id,
mhtcatID = chis.mhcat_id
}).ToList();