1use anyhow::Context as _;
2use collections::HashSet;
3use util::ResultExt;
4
5use super::*;
6
7impl Database {
8 /// Returns the count of all projects, excluding ones marked as admin.
9 pub async fn project_count_excluding_admins(&self) -> Result<usize> {
10 #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
11 enum QueryAs {
12 Count,
13 }
14
15 self.transaction(|tx| async move {
16 Ok(project::Entity::find()
17 .select_only()
18 .column_as(project::Column::Id.count(), QueryAs::Count)
19 .inner_join(user::Entity)
20 .filter(user::Column::Admin.eq(false))
21 .into_values::<_, QueryAs>()
22 .one(&*tx)
23 .await?
24 .unwrap_or(0i64) as usize)
25 })
26 .await
27 }
28
29 /// Shares a project with the given room.
30 pub async fn share_project(
31 &self,
32 room_id: RoomId,
33 connection: ConnectionId,
34 worktrees: &[proto::WorktreeMetadata],
35 is_ssh_project: bool,
36 ) -> Result<TransactionGuard<(ProjectId, proto::Room)>> {
37 self.room_transaction(room_id, |tx| async move {
38 let participant = room_participant::Entity::find()
39 .filter(
40 Condition::all()
41 .add(
42 room_participant::Column::AnsweringConnectionId
43 .eq(connection.id as i32),
44 )
45 .add(
46 room_participant::Column::AnsweringConnectionServerId
47 .eq(connection.owner_id as i32),
48 ),
49 )
50 .one(&*tx)
51 .await?
52 .context("could not find participant")?;
53 if participant.room_id != room_id {
54 return Err(anyhow!("shared project on unexpected room"))?;
55 }
56 if !participant
57 .role
58 .unwrap_or(ChannelRole::Member)
59 .can_edit_projects()
60 {
61 return Err(anyhow!("guests cannot share projects"))?;
62 }
63
64 let project = project::ActiveModel {
65 room_id: ActiveValue::set(Some(participant.room_id)),
66 host_user_id: ActiveValue::set(Some(participant.user_id)),
67 host_connection_id: ActiveValue::set(Some(connection.id as i32)),
68 host_connection_server_id: ActiveValue::set(Some(ServerId(
69 connection.owner_id as i32,
70 ))),
71 id: ActiveValue::NotSet,
72 }
73 .insert(&*tx)
74 .await?;
75
76 if !worktrees.is_empty() {
77 worktree::Entity::insert_many(worktrees.iter().map(|worktree| {
78 worktree::ActiveModel {
79 id: ActiveValue::set(worktree.id as i64),
80 project_id: ActiveValue::set(project.id),
81 abs_path: ActiveValue::set(worktree.abs_path.clone()),
82 root_name: ActiveValue::set(worktree.root_name.clone()),
83 visible: ActiveValue::set(worktree.visible),
84 scan_id: ActiveValue::set(0),
85 completed_scan_id: ActiveValue::set(0),
86 }
87 }))
88 .exec(&*tx)
89 .await?;
90 }
91
92 let replica_id = if is_ssh_project { 1 } else { 0 };
93
94 project_collaborator::ActiveModel {
95 project_id: ActiveValue::set(project.id),
96 connection_id: ActiveValue::set(connection.id as i32),
97 connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
98 user_id: ActiveValue::set(participant.user_id),
99 replica_id: ActiveValue::set(ReplicaId(replica_id)),
100 is_host: ActiveValue::set(true),
101 id: ActiveValue::NotSet,
102 committer_name: ActiveValue::Set(None),
103 committer_email: ActiveValue::Set(None),
104 }
105 .insert(&*tx)
106 .await?;
107
108 let room = self.get_room(room_id, &tx).await?;
109 Ok((project.id, room))
110 })
111 .await
112 }
113
114 pub async fn delete_project(&self, project_id: ProjectId) -> Result<()> {
115 self.transaction(|tx| async move {
116 project::Entity::delete_by_id(project_id).exec(&*tx).await?;
117 Ok(())
118 })
119 .await
120 }
121
122 /// Unshares the given project.
123 pub async fn unshare_project(
124 &self,
125 project_id: ProjectId,
126 connection: ConnectionId,
127 ) -> Result<TransactionGuard<(bool, Option<proto::Room>, Vec<ConnectionId>)>> {
128 self.project_transaction(project_id, |tx| async move {
129 let guest_connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
130 let project = project::Entity::find_by_id(project_id)
131 .one(&*tx)
132 .await?
133 .context("project not found")?;
134 let room = if let Some(room_id) = project.room_id {
135 Some(self.get_room(room_id, &tx).await?)
136 } else {
137 None
138 };
139 if project.host_connection()? == connection {
140 return Ok((true, room, guest_connection_ids));
141 }
142 Err(anyhow!("cannot unshare a project hosted by another user"))?
143 })
144 .await
145 }
146
147 /// Updates the worktrees associated with the given project.
148 pub async fn update_project(
149 &self,
150 project_id: ProjectId,
151 connection: ConnectionId,
152 worktrees: &[proto::WorktreeMetadata],
153 ) -> Result<TransactionGuard<(Option<proto::Room>, Vec<ConnectionId>)>> {
154 self.project_transaction(project_id, |tx| async move {
155 let project = project::Entity::find_by_id(project_id)
156 .filter(
157 Condition::all()
158 .add(project::Column::HostConnectionId.eq(connection.id as i32))
159 .add(
160 project::Column::HostConnectionServerId.eq(connection.owner_id as i32),
161 ),
162 )
163 .one(&*tx)
164 .await?
165 .context("no such project")?;
166
167 self.update_project_worktrees(project.id, worktrees, &tx)
168 .await?;
169
170 let guest_connection_ids = self.project_guest_connection_ids(project.id, &tx).await?;
171
172 let room = if let Some(room_id) = project.room_id {
173 Some(self.get_room(room_id, &tx).await?)
174 } else {
175 None
176 };
177
178 Ok((room, guest_connection_ids))
179 })
180 .await
181 }
182
183 pub(in crate::db) async fn update_project_worktrees(
184 &self,
185 project_id: ProjectId,
186 worktrees: &[proto::WorktreeMetadata],
187 tx: &DatabaseTransaction,
188 ) -> Result<()> {
189 if !worktrees.is_empty() {
190 worktree::Entity::insert_many(worktrees.iter().map(|worktree| worktree::ActiveModel {
191 id: ActiveValue::set(worktree.id as i64),
192 project_id: ActiveValue::set(project_id),
193 abs_path: ActiveValue::set(worktree.abs_path.clone()),
194 root_name: ActiveValue::set(worktree.root_name.clone()),
195 visible: ActiveValue::set(worktree.visible),
196 scan_id: ActiveValue::set(0),
197 completed_scan_id: ActiveValue::set(0),
198 }))
199 .on_conflict(
200 OnConflict::columns([worktree::Column::ProjectId, worktree::Column::Id])
201 .update_column(worktree::Column::RootName)
202 .to_owned(),
203 )
204 .exec(tx)
205 .await?;
206 }
207
208 worktree::Entity::delete_many()
209 .filter(worktree::Column::ProjectId.eq(project_id).and(
210 worktree::Column::Id.is_not_in(worktrees.iter().map(|worktree| worktree.id as i64)),
211 ))
212 .exec(tx)
213 .await?;
214
215 Ok(())
216 }
217
218 pub async fn update_worktree(
219 &self,
220 update: &proto::UpdateWorktree,
221 connection: ConnectionId,
222 ) -> Result<TransactionGuard<Vec<ConnectionId>>> {
223 if update.removed_entries.len() > proto::MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE
224 || update.updated_entries.len() > proto::MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE
225 {
226 return Err(anyhow!(
227 "invalid worktree update. removed entries: {}, updated entries: {}",
228 update.removed_entries.len(),
229 update.updated_entries.len()
230 ))?;
231 }
232
233 let project_id = ProjectId::from_proto(update.project_id);
234 let worktree_id = update.worktree_id as i64;
235 self.project_transaction(project_id, |tx| async move {
236 // Ensure the update comes from the host.
237 let _project = project::Entity::find_by_id(project_id)
238 .filter(
239 Condition::all()
240 .add(project::Column::HostConnectionId.eq(connection.id as i32))
241 .add(
242 project::Column::HostConnectionServerId.eq(connection.owner_id as i32),
243 ),
244 )
245 .one(&*tx)
246 .await?
247 .with_context(|| format!("no such project: {project_id}"))?;
248
249 // Update metadata.
250 worktree::Entity::update(worktree::ActiveModel {
251 id: ActiveValue::set(worktree_id),
252 project_id: ActiveValue::set(project_id),
253 root_name: ActiveValue::set(update.root_name.clone()),
254 scan_id: ActiveValue::set(update.scan_id as i64),
255 completed_scan_id: if update.is_last_update {
256 ActiveValue::set(update.scan_id as i64)
257 } else {
258 ActiveValue::default()
259 },
260 abs_path: ActiveValue::set(update.abs_path.clone()),
261 ..Default::default()
262 })
263 .exec(&*tx)
264 .await?;
265
266 if !update.updated_entries.is_empty() {
267 worktree_entry::Entity::insert_many(update.updated_entries.iter().map(|entry| {
268 let mtime = entry.mtime.clone().unwrap_or_default();
269 worktree_entry::ActiveModel {
270 project_id: ActiveValue::set(project_id),
271 worktree_id: ActiveValue::set(worktree_id),
272 id: ActiveValue::set(entry.id as i64),
273 is_dir: ActiveValue::set(entry.is_dir),
274 path: ActiveValue::set(entry.path.clone()),
275 inode: ActiveValue::set(entry.inode as i64),
276 mtime_seconds: ActiveValue::set(mtime.seconds as i64),
277 mtime_nanos: ActiveValue::set(mtime.nanos as i32),
278 canonical_path: ActiveValue::set(entry.canonical_path.clone()),
279 is_ignored: ActiveValue::set(entry.is_ignored),
280 git_status: ActiveValue::set(None),
281 is_external: ActiveValue::set(entry.is_external),
282 is_deleted: ActiveValue::set(false),
283 scan_id: ActiveValue::set(update.scan_id as i64),
284 is_fifo: ActiveValue::set(entry.is_fifo),
285 }
286 }))
287 .on_conflict(
288 OnConflict::columns([
289 worktree_entry::Column::ProjectId,
290 worktree_entry::Column::WorktreeId,
291 worktree_entry::Column::Id,
292 ])
293 .update_columns([
294 worktree_entry::Column::IsDir,
295 worktree_entry::Column::Path,
296 worktree_entry::Column::Inode,
297 worktree_entry::Column::MtimeSeconds,
298 worktree_entry::Column::MtimeNanos,
299 worktree_entry::Column::CanonicalPath,
300 worktree_entry::Column::IsIgnored,
301 worktree_entry::Column::ScanId,
302 ])
303 .to_owned(),
304 )
305 .exec(&*tx)
306 .await?;
307 }
308
309 if !update.removed_entries.is_empty() {
310 worktree_entry::Entity::update_many()
311 .filter(
312 worktree_entry::Column::ProjectId
313 .eq(project_id)
314 .and(worktree_entry::Column::WorktreeId.eq(worktree_id))
315 .and(
316 worktree_entry::Column::Id
317 .is_in(update.removed_entries.iter().map(|id| *id as i64)),
318 ),
319 )
320 .set(worktree_entry::ActiveModel {
321 is_deleted: ActiveValue::Set(true),
322 scan_id: ActiveValue::Set(update.scan_id as i64),
323 ..Default::default()
324 })
325 .exec(&*tx)
326 .await?;
327 }
328
329 // Backward-compatibility for old Zed clients.
330 //
331 // Remove this block when Zed 1.80 stable has been out for a week.
332 {
333 if !update.updated_repositories.is_empty() {
334 project_repository::Entity::insert_many(
335 update.updated_repositories.iter().map(|repository| {
336 project_repository::ActiveModel {
337 project_id: ActiveValue::set(project_id),
338 legacy_worktree_id: ActiveValue::set(Some(worktree_id)),
339 id: ActiveValue::set(repository.repository_id as i64),
340 scan_id: ActiveValue::set(update.scan_id as i64),
341 is_deleted: ActiveValue::set(false),
342 branch_summary: ActiveValue::Set(
343 repository
344 .branch_summary
345 .as_ref()
346 .map(|summary| serde_json::to_string(summary).unwrap()),
347 ),
348 current_merge_conflicts: ActiveValue::Set(Some(
349 serde_json::to_string(&repository.current_merge_conflicts)
350 .unwrap(),
351 )),
352 // Old clients do not use abs path, entry ids, head_commit_details, or merge_message.
353 abs_path: ActiveValue::set(String::new()),
354 entry_ids: ActiveValue::set("[]".into()),
355 head_commit_details: ActiveValue::set(None),
356 merge_message: ActiveValue::set(None),
357 }
358 }),
359 )
360 .on_conflict(
361 OnConflict::columns([
362 project_repository::Column::ProjectId,
363 project_repository::Column::Id,
364 ])
365 .update_columns([
366 project_repository::Column::ScanId,
367 project_repository::Column::BranchSummary,
368 project_repository::Column::CurrentMergeConflicts,
369 ])
370 .to_owned(),
371 )
372 .exec(&*tx)
373 .await?;
374
375 let has_any_statuses = update
376 .updated_repositories
377 .iter()
378 .any(|repository| !repository.updated_statuses.is_empty());
379
380 if has_any_statuses {
381 project_repository_statuses::Entity::insert_many(
382 update.updated_repositories.iter().flat_map(
383 |repository: &proto::RepositoryEntry| {
384 repository.updated_statuses.iter().map(|status_entry| {
385 let (repo_path, status_kind, first_status, second_status) =
386 proto_status_to_db(status_entry.clone());
387 project_repository_statuses::ActiveModel {
388 project_id: ActiveValue::set(project_id),
389 repository_id: ActiveValue::set(
390 repository.repository_id as i64,
391 ),
392 scan_id: ActiveValue::set(update.scan_id as i64),
393 is_deleted: ActiveValue::set(false),
394 repo_path: ActiveValue::set(repo_path),
395 status: ActiveValue::set(0),
396 status_kind: ActiveValue::set(status_kind),
397 first_status: ActiveValue::set(first_status),
398 second_status: ActiveValue::set(second_status),
399 }
400 })
401 },
402 ),
403 )
404 .on_conflict(
405 OnConflict::columns([
406 project_repository_statuses::Column::ProjectId,
407 project_repository_statuses::Column::RepositoryId,
408 project_repository_statuses::Column::RepoPath,
409 ])
410 .update_columns([
411 project_repository_statuses::Column::ScanId,
412 project_repository_statuses::Column::StatusKind,
413 project_repository_statuses::Column::FirstStatus,
414 project_repository_statuses::Column::SecondStatus,
415 ])
416 .to_owned(),
417 )
418 .exec(&*tx)
419 .await?;
420 }
421
422 for repo in &update.updated_repositories {
423 if !repo.removed_statuses.is_empty() {
424 project_repository_statuses::Entity::update_many()
425 .filter(
426 project_repository_statuses::Column::ProjectId
427 .eq(project_id)
428 .and(
429 project_repository_statuses::Column::RepositoryId
430 .eq(repo.repository_id),
431 )
432 .and(
433 project_repository_statuses::Column::RepoPath
434 .is_in(repo.removed_statuses.iter()),
435 ),
436 )
437 .set(project_repository_statuses::ActiveModel {
438 is_deleted: ActiveValue::Set(true),
439 scan_id: ActiveValue::Set(update.scan_id as i64),
440 ..Default::default()
441 })
442 .exec(&*tx)
443 .await?;
444 }
445 }
446 }
447
448 if !update.removed_repositories.is_empty() {
449 project_repository::Entity::update_many()
450 .filter(
451 project_repository::Column::ProjectId
452 .eq(project_id)
453 .and(project_repository::Column::LegacyWorktreeId.eq(worktree_id))
454 .and(project_repository::Column::Id.is_in(
455 update.removed_repositories.iter().map(|id| *id as i64),
456 )),
457 )
458 .set(project_repository::ActiveModel {
459 is_deleted: ActiveValue::Set(true),
460 scan_id: ActiveValue::Set(update.scan_id as i64),
461 ..Default::default()
462 })
463 .exec(&*tx)
464 .await?;
465 }
466 }
467
468 let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
469 Ok(connection_ids)
470 })
471 .await
472 }
473
474 pub async fn update_repository(
475 &self,
476 update: &proto::UpdateRepository,
477 _connection: ConnectionId,
478 ) -> Result<TransactionGuard<Vec<ConnectionId>>> {
479 let project_id = ProjectId::from_proto(update.project_id);
480 let repository_id = update.id as i64;
481 self.project_transaction(project_id, |tx| async move {
482 project_repository::Entity::insert(project_repository::ActiveModel {
483 project_id: ActiveValue::set(project_id),
484 id: ActiveValue::set(repository_id),
485 legacy_worktree_id: ActiveValue::set(None),
486 abs_path: ActiveValue::set(update.abs_path.clone()),
487 entry_ids: ActiveValue::Set(serde_json::to_string(&update.entry_ids).unwrap()),
488 scan_id: ActiveValue::set(update.scan_id as i64),
489 is_deleted: ActiveValue::set(false),
490 branch_summary: ActiveValue::Set(
491 update
492 .branch_summary
493 .as_ref()
494 .map(|summary| serde_json::to_string(summary).unwrap()),
495 ),
496 head_commit_details: ActiveValue::Set(
497 update
498 .head_commit_details
499 .as_ref()
500 .map(|details| serde_json::to_string(details).unwrap()),
501 ),
502 current_merge_conflicts: ActiveValue::Set(Some(
503 serde_json::to_string(&update.current_merge_conflicts).unwrap(),
504 )),
505 merge_message: ActiveValue::set(update.merge_message.clone()),
506 })
507 .on_conflict(
508 OnConflict::columns([
509 project_repository::Column::ProjectId,
510 project_repository::Column::Id,
511 ])
512 .update_columns([
513 project_repository::Column::ScanId,
514 project_repository::Column::BranchSummary,
515 project_repository::Column::EntryIds,
516 project_repository::Column::AbsPath,
517 project_repository::Column::CurrentMergeConflicts,
518 project_repository::Column::HeadCommitDetails,
519 project_repository::Column::MergeMessage,
520 ])
521 .to_owned(),
522 )
523 .exec(&*tx)
524 .await?;
525
526 let has_any_statuses = !update.updated_statuses.is_empty();
527
528 if has_any_statuses {
529 project_repository_statuses::Entity::insert_many(
530 update.updated_statuses.iter().map(|status_entry| {
531 let (repo_path, status_kind, first_status, second_status) =
532 proto_status_to_db(status_entry.clone());
533 project_repository_statuses::ActiveModel {
534 project_id: ActiveValue::set(project_id),
535 repository_id: ActiveValue::set(repository_id),
536 scan_id: ActiveValue::set(update.scan_id as i64),
537 is_deleted: ActiveValue::set(false),
538 repo_path: ActiveValue::set(repo_path),
539 status: ActiveValue::set(0),
540 status_kind: ActiveValue::set(status_kind),
541 first_status: ActiveValue::set(first_status),
542 second_status: ActiveValue::set(second_status),
543 }
544 }),
545 )
546 .on_conflict(
547 OnConflict::columns([
548 project_repository_statuses::Column::ProjectId,
549 project_repository_statuses::Column::RepositoryId,
550 project_repository_statuses::Column::RepoPath,
551 ])
552 .update_columns([
553 project_repository_statuses::Column::ScanId,
554 project_repository_statuses::Column::StatusKind,
555 project_repository_statuses::Column::FirstStatus,
556 project_repository_statuses::Column::SecondStatus,
557 ])
558 .to_owned(),
559 )
560 .exec(&*tx)
561 .await?;
562 }
563
564 let has_any_removed_statuses = !update.removed_statuses.is_empty();
565
566 if has_any_removed_statuses {
567 project_repository_statuses::Entity::update_many()
568 .filter(
569 project_repository_statuses::Column::ProjectId
570 .eq(project_id)
571 .and(
572 project_repository_statuses::Column::RepositoryId.eq(repository_id),
573 )
574 .and(
575 project_repository_statuses::Column::RepoPath
576 .is_in(update.removed_statuses.iter()),
577 ),
578 )
579 .set(project_repository_statuses::ActiveModel {
580 is_deleted: ActiveValue::Set(true),
581 scan_id: ActiveValue::Set(update.scan_id as i64),
582 ..Default::default()
583 })
584 .exec(&*tx)
585 .await?;
586 }
587
588 let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
589 Ok(connection_ids)
590 })
591 .await
592 }
593
594 pub async fn remove_repository(
595 &self,
596 remove: &proto::RemoveRepository,
597 _connection: ConnectionId,
598 ) -> Result<TransactionGuard<Vec<ConnectionId>>> {
599 let project_id = ProjectId::from_proto(remove.project_id);
600 let repository_id = remove.id as i64;
601 self.project_transaction(project_id, |tx| async move {
602 project_repository::Entity::update_many()
603 .filter(
604 project_repository::Column::ProjectId
605 .eq(project_id)
606 .and(project_repository::Column::Id.eq(repository_id)),
607 )
608 .set(project_repository::ActiveModel {
609 is_deleted: ActiveValue::Set(true),
610 // scan_id: ActiveValue::Set(update.scan_id as i64),
611 ..Default::default()
612 })
613 .exec(&*tx)
614 .await?;
615
616 let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
617 Ok(connection_ids)
618 })
619 .await
620 }
621
622 /// Updates the diagnostic summary for the given connection.
623 pub async fn update_diagnostic_summary(
624 &self,
625 update: &proto::UpdateDiagnosticSummary,
626 connection: ConnectionId,
627 ) -> Result<TransactionGuard<Vec<ConnectionId>>> {
628 let project_id = ProjectId::from_proto(update.project_id);
629 let worktree_id = update.worktree_id as i64;
630 self.project_transaction(project_id, |tx| async move {
631 let summary = update.summary.as_ref().context("invalid summary")?;
632
633 // Ensure the update comes from the host.
634 let project = project::Entity::find_by_id(project_id)
635 .one(&*tx)
636 .await?
637 .context("no such project")?;
638 if project.host_connection()? != connection {
639 return Err(anyhow!("can't update a project hosted by someone else"))?;
640 }
641
642 // Update summary.
643 worktree_diagnostic_summary::Entity::insert(worktree_diagnostic_summary::ActiveModel {
644 project_id: ActiveValue::set(project_id),
645 worktree_id: ActiveValue::set(worktree_id),
646 path: ActiveValue::set(summary.path.clone()),
647 language_server_id: ActiveValue::set(summary.language_server_id as i64),
648 error_count: ActiveValue::set(summary.error_count as i32),
649 warning_count: ActiveValue::set(summary.warning_count as i32),
650 })
651 .on_conflict(
652 OnConflict::columns([
653 worktree_diagnostic_summary::Column::ProjectId,
654 worktree_diagnostic_summary::Column::WorktreeId,
655 worktree_diagnostic_summary::Column::Path,
656 ])
657 .update_columns([
658 worktree_diagnostic_summary::Column::LanguageServerId,
659 worktree_diagnostic_summary::Column::ErrorCount,
660 worktree_diagnostic_summary::Column::WarningCount,
661 ])
662 .to_owned(),
663 )
664 .exec(&*tx)
665 .await?;
666
667 let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
668 Ok(connection_ids)
669 })
670 .await
671 }
672
673 /// Starts the language server for the given connection.
674 pub async fn start_language_server(
675 &self,
676 update: &proto::StartLanguageServer,
677 connection: ConnectionId,
678 ) -> Result<TransactionGuard<Vec<ConnectionId>>> {
679 let project_id = ProjectId::from_proto(update.project_id);
680 self.project_transaction(project_id, |tx| async move {
681 let server = update.server.as_ref().context("invalid language server")?;
682
683 // Ensure the update comes from the host.
684 let project = project::Entity::find_by_id(project_id)
685 .one(&*tx)
686 .await?
687 .context("no such project")?;
688 if project.host_connection()? != connection {
689 return Err(anyhow!("can't update a project hosted by someone else"))?;
690 }
691
692 // Add the newly-started language server.
693 language_server::Entity::insert(language_server::ActiveModel {
694 project_id: ActiveValue::set(project_id),
695 id: ActiveValue::set(server.id as i64),
696 name: ActiveValue::set(server.name.clone()),
697 capabilities: ActiveValue::set(update.capabilities.clone()),
698 })
699 .on_conflict(
700 OnConflict::columns([
701 language_server::Column::ProjectId,
702 language_server::Column::Id,
703 ])
704 .update_columns([
705 language_server::Column::Name,
706 language_server::Column::Capabilities,
707 ])
708 .to_owned(),
709 )
710 .exec(&*tx)
711 .await?;
712
713 let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
714 Ok(connection_ids)
715 })
716 .await
717 }
718
719 /// Updates the worktree settings for the given connection.
720 pub async fn update_worktree_settings(
721 &self,
722 update: &proto::UpdateWorktreeSettings,
723 connection: ConnectionId,
724 ) -> Result<TransactionGuard<Vec<ConnectionId>>> {
725 let project_id = ProjectId::from_proto(update.project_id);
726 let kind = match update.kind {
727 Some(kind) => proto::LocalSettingsKind::from_i32(kind)
728 .with_context(|| format!("unknown worktree settings kind: {kind}"))?,
729 None => proto::LocalSettingsKind::Settings,
730 };
731 let kind = LocalSettingsKind::from_proto(kind);
732 self.project_transaction(project_id, |tx| async move {
733 // Ensure the update comes from the host.
734 let project = project::Entity::find_by_id(project_id)
735 .one(&*tx)
736 .await?
737 .context("no such project")?;
738 if project.host_connection()? != connection {
739 return Err(anyhow!("can't update a project hosted by someone else"))?;
740 }
741
742 if let Some(content) = &update.content {
743 worktree_settings_file::Entity::insert(worktree_settings_file::ActiveModel {
744 project_id: ActiveValue::Set(project_id),
745 worktree_id: ActiveValue::Set(update.worktree_id as i64),
746 path: ActiveValue::Set(update.path.clone()),
747 content: ActiveValue::Set(content.clone()),
748 kind: ActiveValue::Set(kind),
749 })
750 .on_conflict(
751 OnConflict::columns([
752 worktree_settings_file::Column::ProjectId,
753 worktree_settings_file::Column::WorktreeId,
754 worktree_settings_file::Column::Path,
755 ])
756 .update_column(worktree_settings_file::Column::Content)
757 .to_owned(),
758 )
759 .exec(&*tx)
760 .await?;
761 } else {
762 worktree_settings_file::Entity::delete(worktree_settings_file::ActiveModel {
763 project_id: ActiveValue::Set(project_id),
764 worktree_id: ActiveValue::Set(update.worktree_id as i64),
765 path: ActiveValue::Set(update.path.clone()),
766 ..Default::default()
767 })
768 .exec(&*tx)
769 .await?;
770 }
771
772 let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
773 Ok(connection_ids)
774 })
775 .await
776 }
777
778 pub async fn get_project(&self, id: ProjectId) -> Result<project::Model> {
779 self.transaction(|tx| async move {
780 Ok(project::Entity::find_by_id(id)
781 .one(&*tx)
782 .await?
783 .context("no such project")?)
784 })
785 .await
786 }
787
788 /// Adds the given connection to the specified project
789 /// in the current room.
790 pub async fn join_project(
791 &self,
792 project_id: ProjectId,
793 connection: ConnectionId,
794 user_id: UserId,
795 committer_name: Option<String>,
796 committer_email: Option<String>,
797 ) -> Result<TransactionGuard<(Project, ReplicaId)>> {
798 self.project_transaction(project_id, move |tx| {
799 let committer_name = committer_name.clone();
800 let committer_email = committer_email.clone();
801 async move {
802 let (project, role) = self
803 .access_project(project_id, connection, Capability::ReadOnly, &tx)
804 .await?;
805 self.join_project_internal(
806 project,
807 user_id,
808 committer_name,
809 committer_email,
810 connection,
811 role,
812 &tx,
813 )
814 .await
815 }
816 })
817 .await
818 }
819
820 async fn join_project_internal(
821 &self,
822 project: project::Model,
823 user_id: UserId,
824 committer_name: Option<String>,
825 committer_email: Option<String>,
826 connection: ConnectionId,
827 role: ChannelRole,
828 tx: &DatabaseTransaction,
829 ) -> Result<(Project, ReplicaId)> {
830 let mut collaborators = project
831 .find_related(project_collaborator::Entity)
832 .all(tx)
833 .await?;
834 let replica_ids = collaborators
835 .iter()
836 .map(|c| c.replica_id)
837 .collect::<HashSet<_>>();
838 let mut replica_id = ReplicaId(1);
839 while replica_ids.contains(&replica_id) {
840 replica_id.0 += 1;
841 }
842 let new_collaborator = project_collaborator::ActiveModel {
843 project_id: ActiveValue::set(project.id),
844 connection_id: ActiveValue::set(connection.id as i32),
845 connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
846 user_id: ActiveValue::set(user_id),
847 replica_id: ActiveValue::set(replica_id),
848 is_host: ActiveValue::set(false),
849 id: ActiveValue::NotSet,
850 committer_name: ActiveValue::set(committer_name),
851 committer_email: ActiveValue::set(committer_email),
852 }
853 .insert(tx)
854 .await?;
855 collaborators.push(new_collaborator);
856
857 let db_worktrees = project.find_related(worktree::Entity).all(tx).await?;
858 let mut worktrees = db_worktrees
859 .into_iter()
860 .map(|db_worktree| {
861 (
862 db_worktree.id as u64,
863 Worktree {
864 id: db_worktree.id as u64,
865 abs_path: db_worktree.abs_path,
866 root_name: db_worktree.root_name,
867 visible: db_worktree.visible,
868 entries: Default::default(),
869 diagnostic_summaries: Default::default(),
870 settings_files: Default::default(),
871 scan_id: db_worktree.scan_id as u64,
872 completed_scan_id: db_worktree.completed_scan_id as u64,
873 legacy_repository_entries: Default::default(),
874 },
875 )
876 })
877 .collect::<BTreeMap<_, _>>();
878
879 // Populate worktree entries.
880 {
881 let mut db_entries = worktree_entry::Entity::find()
882 .filter(
883 Condition::all()
884 .add(worktree_entry::Column::ProjectId.eq(project.id))
885 .add(worktree_entry::Column::IsDeleted.eq(false)),
886 )
887 .stream(tx)
888 .await?;
889 while let Some(db_entry) = db_entries.next().await {
890 let db_entry = db_entry?;
891 if let Some(worktree) = worktrees.get_mut(&(db_entry.worktree_id as u64)) {
892 worktree.entries.push(proto::Entry {
893 id: db_entry.id as u64,
894 is_dir: db_entry.is_dir,
895 path: db_entry.path,
896 inode: db_entry.inode as u64,
897 mtime: Some(proto::Timestamp {
898 seconds: db_entry.mtime_seconds as u64,
899 nanos: db_entry.mtime_nanos as u32,
900 }),
901 canonical_path: db_entry.canonical_path,
902 is_ignored: db_entry.is_ignored,
903 is_external: db_entry.is_external,
904 // This is only used in the summarization backlog, so if it's None,
905 // that just means we won't be able to detect when to resummarize
906 // based on total number of backlogged bytes - instead, we'd go
907 // on number of files only. That shouldn't be a huge deal in practice.
908 size: None,
909 is_fifo: db_entry.is_fifo,
910 });
911 }
912 }
913 }
914
915 // Populate repository entries.
916 let mut repositories = Vec::new();
917 {
918 let db_repository_entries = project_repository::Entity::find()
919 .filter(
920 Condition::all()
921 .add(project_repository::Column::ProjectId.eq(project.id))
922 .add(project_repository::Column::IsDeleted.eq(false)),
923 )
924 .all(tx)
925 .await?;
926 for db_repository_entry in db_repository_entries {
927 let mut repository_statuses = project_repository_statuses::Entity::find()
928 .filter(
929 Condition::all()
930 .add(project_repository_statuses::Column::ProjectId.eq(project.id))
931 .add(
932 project_repository_statuses::Column::RepositoryId
933 .eq(db_repository_entry.id),
934 )
935 .add(project_repository_statuses::Column::IsDeleted.eq(false)),
936 )
937 .stream(tx)
938 .await?;
939 let mut updated_statuses = Vec::new();
940 while let Some(status_entry) = repository_statuses.next().await {
941 let status_entry = status_entry?;
942 updated_statuses.push(db_status_to_proto(status_entry)?);
943 }
944
945 let current_merge_conflicts = db_repository_entry
946 .current_merge_conflicts
947 .as_ref()
948 .map(|conflicts| serde_json::from_str(conflicts))
949 .transpose()?
950 .unwrap_or_default();
951
952 let branch_summary = db_repository_entry
953 .branch_summary
954 .as_ref()
955 .map(|branch_summary| serde_json::from_str(branch_summary))
956 .transpose()?
957 .unwrap_or_default();
958
959 let head_commit_details = db_repository_entry
960 .head_commit_details
961 .as_ref()
962 .map(|head_commit_details| serde_json::from_str(head_commit_details))
963 .transpose()?
964 .unwrap_or_default();
965
966 let entry_ids = serde_json::from_str(&db_repository_entry.entry_ids)
967 .context("failed to deserialize repository's entry ids")?;
968
969 if let Some(worktree_id) = db_repository_entry.legacy_worktree_id {
970 if let Some(worktree) = worktrees.get_mut(&(worktree_id as u64)) {
971 worktree.legacy_repository_entries.insert(
972 db_repository_entry.id as u64,
973 proto::RepositoryEntry {
974 repository_id: db_repository_entry.id as u64,
975 updated_statuses,
976 removed_statuses: Vec::new(),
977 current_merge_conflicts,
978 branch_summary,
979 },
980 );
981 }
982 } else {
983 repositories.push(proto::UpdateRepository {
984 project_id: db_repository_entry.project_id.0 as u64,
985 id: db_repository_entry.id as u64,
986 abs_path: db_repository_entry.abs_path,
987 entry_ids,
988 updated_statuses,
989 removed_statuses: Vec::new(),
990 current_merge_conflicts,
991 branch_summary,
992 head_commit_details,
993 scan_id: db_repository_entry.scan_id as u64,
994 is_last_update: true,
995 merge_message: db_repository_entry.merge_message,
996 });
997 }
998 }
999 }
1000
1001 // Populate worktree diagnostic summaries.
1002 {
1003 let mut db_summaries = worktree_diagnostic_summary::Entity::find()
1004 .filter(worktree_diagnostic_summary::Column::ProjectId.eq(project.id))
1005 .stream(tx)
1006 .await?;
1007 while let Some(db_summary) = db_summaries.next().await {
1008 let db_summary = db_summary?;
1009 if let Some(worktree) = worktrees.get_mut(&(db_summary.worktree_id as u64)) {
1010 worktree
1011 .diagnostic_summaries
1012 .push(proto::DiagnosticSummary {
1013 path: db_summary.path,
1014 language_server_id: db_summary.language_server_id as u64,
1015 error_count: db_summary.error_count as u32,
1016 warning_count: db_summary.warning_count as u32,
1017 });
1018 }
1019 }
1020 }
1021
1022 // Populate worktree settings files
1023 {
1024 let mut db_settings_files = worktree_settings_file::Entity::find()
1025 .filter(worktree_settings_file::Column::ProjectId.eq(project.id))
1026 .stream(tx)
1027 .await?;
1028 while let Some(db_settings_file) = db_settings_files.next().await {
1029 let db_settings_file = db_settings_file?;
1030 if let Some(worktree) = worktrees.get_mut(&(db_settings_file.worktree_id as u64)) {
1031 worktree.settings_files.push(WorktreeSettingsFile {
1032 path: db_settings_file.path,
1033 content: db_settings_file.content,
1034 kind: db_settings_file.kind,
1035 });
1036 }
1037 }
1038 }
1039
1040 // Populate language servers.
1041 let language_servers = project
1042 .find_related(language_server::Entity)
1043 .all(tx)
1044 .await?;
1045
1046 let project = Project {
1047 id: project.id,
1048 role,
1049 collaborators: collaborators
1050 .into_iter()
1051 .map(|collaborator| ProjectCollaborator {
1052 connection_id: collaborator.connection(),
1053 user_id: collaborator.user_id,
1054 replica_id: collaborator.replica_id,
1055 is_host: collaborator.is_host,
1056 committer_name: collaborator.committer_name,
1057 committer_email: collaborator.committer_email,
1058 })
1059 .collect(),
1060 worktrees,
1061 repositories,
1062 language_servers: language_servers
1063 .into_iter()
1064 .map(|language_server| LanguageServer {
1065 server: proto::LanguageServer {
1066 id: language_server.id as u64,
1067 name: language_server.name,
1068 worktree_id: None,
1069 },
1070 capabilities: language_server.capabilities,
1071 })
1072 .collect(),
1073 };
1074 Ok((project, replica_id as ReplicaId))
1075 }
1076
1077 /// Removes the given connection from the specified project.
1078 pub async fn leave_project(
1079 &self,
1080 project_id: ProjectId,
1081 connection: ConnectionId,
1082 ) -> Result<TransactionGuard<(Option<proto::Room>, LeftProject)>> {
1083 self.project_transaction(project_id, |tx| async move {
1084 let result = project_collaborator::Entity::delete_many()
1085 .filter(
1086 Condition::all()
1087 .add(project_collaborator::Column::ProjectId.eq(project_id))
1088 .add(project_collaborator::Column::ConnectionId.eq(connection.id as i32))
1089 .add(
1090 project_collaborator::Column::ConnectionServerId
1091 .eq(connection.owner_id as i32),
1092 ),
1093 )
1094 .exec(&*tx)
1095 .await?;
1096 if result.rows_affected == 0 {
1097 Err(anyhow!("not a collaborator on this project"))?;
1098 }
1099
1100 let project = project::Entity::find_by_id(project_id)
1101 .one(&*tx)
1102 .await?
1103 .context("no such project")?;
1104 let collaborators = project
1105 .find_related(project_collaborator::Entity)
1106 .all(&*tx)
1107 .await?;
1108 let connection_ids: Vec<ConnectionId> = collaborators
1109 .into_iter()
1110 .map(|collaborator| collaborator.connection())
1111 .collect();
1112
1113 follower::Entity::delete_many()
1114 .filter(
1115 Condition::any()
1116 .add(
1117 Condition::all()
1118 .add(follower::Column::ProjectId.eq(Some(project_id)))
1119 .add(
1120 follower::Column::LeaderConnectionServerId
1121 .eq(connection.owner_id),
1122 )
1123 .add(follower::Column::LeaderConnectionId.eq(connection.id)),
1124 )
1125 .add(
1126 Condition::all()
1127 .add(follower::Column::ProjectId.eq(Some(project_id)))
1128 .add(
1129 follower::Column::FollowerConnectionServerId
1130 .eq(connection.owner_id),
1131 )
1132 .add(follower::Column::FollowerConnectionId.eq(connection.id)),
1133 ),
1134 )
1135 .exec(&*tx)
1136 .await?;
1137
1138 let room = if let Some(room_id) = project.room_id {
1139 Some(self.get_room(room_id, &tx).await?)
1140 } else {
1141 None
1142 };
1143
1144 let left_project = LeftProject {
1145 id: project_id,
1146 should_unshare: connection == project.host_connection()?,
1147 connection_ids,
1148 };
1149 Ok((room, left_project))
1150 })
1151 .await
1152 }
1153
1154 pub async fn check_user_is_project_host(
1155 &self,
1156 project_id: ProjectId,
1157 connection_id: ConnectionId,
1158 ) -> Result<()> {
1159 self.project_transaction(project_id, |tx| async move {
1160 project::Entity::find()
1161 .filter(
1162 Condition::all()
1163 .add(project::Column::Id.eq(project_id))
1164 .add(project::Column::HostConnectionId.eq(Some(connection_id.id as i32)))
1165 .add(
1166 project::Column::HostConnectionServerId
1167 .eq(Some(connection_id.owner_id as i32)),
1168 ),
1169 )
1170 .one(&*tx)
1171 .await?
1172 .context("failed to read project host")?;
1173
1174 Ok(())
1175 })
1176 .await
1177 .map(|guard| guard.into_inner())
1178 }
1179
1180 /// Returns the current project if the given user is authorized to access it with the specified capability.
1181 pub async fn access_project(
1182 &self,
1183 project_id: ProjectId,
1184 connection_id: ConnectionId,
1185 capability: Capability,
1186 tx: &DatabaseTransaction,
1187 ) -> Result<(project::Model, ChannelRole)> {
1188 let project = project::Entity::find_by_id(project_id)
1189 .one(tx)
1190 .await?
1191 .context("no such project")?;
1192
1193 let role_from_room = if let Some(room_id) = project.room_id {
1194 room_participant::Entity::find()
1195 .filter(room_participant::Column::RoomId.eq(room_id))
1196 .filter(room_participant::Column::AnsweringConnectionId.eq(connection_id.id))
1197 .one(tx)
1198 .await?
1199 .and_then(|participant| participant.role)
1200 } else {
1201 None
1202 };
1203
1204 let role = role_from_room.unwrap_or(ChannelRole::Banned);
1205
1206 match capability {
1207 Capability::ReadWrite => {
1208 if !role.can_edit_projects() {
1209 return Err(anyhow!("not authorized to edit projects"))?;
1210 }
1211 }
1212 Capability::ReadOnly => {
1213 if !role.can_read_projects() {
1214 return Err(anyhow!("not authorized to read projects"))?;
1215 }
1216 }
1217 }
1218
1219 Ok((project, role))
1220 }
1221
1222 /// Returns the host connection for a read-only request to join a shared project.
1223 pub async fn host_for_read_only_project_request(
1224 &self,
1225 project_id: ProjectId,
1226 connection_id: ConnectionId,
1227 ) -> Result<ConnectionId> {
1228 self.project_transaction(project_id, |tx| async move {
1229 let (project, _) = self
1230 .access_project(project_id, connection_id, Capability::ReadOnly, &tx)
1231 .await?;
1232 project.host_connection()
1233 })
1234 .await
1235 .map(|guard| guard.into_inner())
1236 }
1237
1238 /// Returns the host connection for a request to join a shared project.
1239 pub async fn host_for_mutating_project_request(
1240 &self,
1241 project_id: ProjectId,
1242 connection_id: ConnectionId,
1243 ) -> Result<ConnectionId> {
1244 self.project_transaction(project_id, |tx| async move {
1245 let (project, _) = self
1246 .access_project(project_id, connection_id, Capability::ReadWrite, &tx)
1247 .await?;
1248 project.host_connection()
1249 })
1250 .await
1251 .map(|guard| guard.into_inner())
1252 }
1253
1254 pub async fn connections_for_buffer_update(
1255 &self,
1256 project_id: ProjectId,
1257 connection_id: ConnectionId,
1258 capability: Capability,
1259 ) -> Result<TransactionGuard<(ConnectionId, Vec<ConnectionId>)>> {
1260 self.project_transaction(project_id, |tx| async move {
1261 // Authorize
1262 let (project, _) = self
1263 .access_project(project_id, connection_id, capability, &tx)
1264 .await?;
1265
1266 let host_connection_id = project.host_connection()?;
1267
1268 let collaborators = project_collaborator::Entity::find()
1269 .filter(project_collaborator::Column::ProjectId.eq(project_id))
1270 .all(&*tx)
1271 .await?;
1272
1273 let guest_connection_ids = collaborators
1274 .into_iter()
1275 .filter_map(|collaborator| {
1276 if collaborator.is_host {
1277 None
1278 } else {
1279 Some(collaborator.connection())
1280 }
1281 })
1282 .collect();
1283
1284 Ok((host_connection_id, guest_connection_ids))
1285 })
1286 .await
1287 }
1288
1289 /// Returns the connection IDs in the given project.
1290 ///
1291 /// The provided `connection_id` must also be a collaborator in the project,
1292 /// otherwise an error will be returned.
1293 pub async fn project_connection_ids(
1294 &self,
1295 project_id: ProjectId,
1296 connection_id: ConnectionId,
1297 exclude_dev_server: bool,
1298 ) -> Result<TransactionGuard<HashSet<ConnectionId>>> {
1299 self.project_transaction(project_id, |tx| async move {
1300 self.internal_project_connection_ids(project_id, connection_id, exclude_dev_server, &tx)
1301 .await
1302 })
1303 .await
1304 }
1305
1306 async fn internal_project_connection_ids(
1307 &self,
1308 project_id: ProjectId,
1309 connection_id: ConnectionId,
1310 exclude_dev_server: bool,
1311 tx: &DatabaseTransaction,
1312 ) -> Result<HashSet<ConnectionId>> {
1313 let project = project::Entity::find_by_id(project_id)
1314 .one(tx)
1315 .await?
1316 .context("no such project")?;
1317
1318 let mut collaborators = project_collaborator::Entity::find()
1319 .filter(project_collaborator::Column::ProjectId.eq(project_id))
1320 .stream(tx)
1321 .await?;
1322
1323 let mut connection_ids = HashSet::default();
1324 if let Some(host_connection) = project.host_connection().log_err()
1325 && !exclude_dev_server
1326 {
1327 connection_ids.insert(host_connection);
1328 }
1329
1330 while let Some(collaborator) = collaborators.next().await {
1331 let collaborator = collaborator?;
1332 connection_ids.insert(collaborator.connection());
1333 }
1334
1335 if connection_ids.contains(&connection_id)
1336 || Some(connection_id) == project.host_connection().ok()
1337 {
1338 Ok(connection_ids)
1339 } else {
1340 Err(anyhow!(
1341 "can only send project updates to a project you're in"
1342 ))?
1343 }
1344 }
1345
1346 async fn project_guest_connection_ids(
1347 &self,
1348 project_id: ProjectId,
1349 tx: &DatabaseTransaction,
1350 ) -> Result<Vec<ConnectionId>> {
1351 let mut collaborators = project_collaborator::Entity::find()
1352 .filter(
1353 project_collaborator::Column::ProjectId
1354 .eq(project_id)
1355 .and(project_collaborator::Column::IsHost.eq(false)),
1356 )
1357 .stream(tx)
1358 .await?;
1359
1360 let mut guest_connection_ids = Vec::new();
1361 while let Some(collaborator) = collaborators.next().await {
1362 let collaborator = collaborator?;
1363 guest_connection_ids.push(collaborator.connection());
1364 }
1365 Ok(guest_connection_ids)
1366 }
1367
1368 /// Returns the [`RoomId`] for the given project.
1369 pub async fn room_id_for_project(&self, project_id: ProjectId) -> Result<Option<RoomId>> {
1370 self.transaction(|tx| async move {
1371 Ok(project::Entity::find_by_id(project_id)
1372 .one(&*tx)
1373 .await?
1374 .and_then(|project| project.room_id))
1375 })
1376 .await
1377 }
1378
1379 pub async fn check_room_participants(
1380 &self,
1381 room_id: RoomId,
1382 leader_id: ConnectionId,
1383 follower_id: ConnectionId,
1384 ) -> Result<()> {
1385 self.transaction(|tx| async move {
1386 use room_participant::Column;
1387
1388 let count = room_participant::Entity::find()
1389 .filter(
1390 Condition::all().add(Column::RoomId.eq(room_id)).add(
1391 Condition::any()
1392 .add(Column::AnsweringConnectionId.eq(leader_id.id as i32).and(
1393 Column::AnsweringConnectionServerId.eq(leader_id.owner_id as i32),
1394 ))
1395 .add(Column::AnsweringConnectionId.eq(follower_id.id as i32).and(
1396 Column::AnsweringConnectionServerId.eq(follower_id.owner_id as i32),
1397 )),
1398 ),
1399 )
1400 .count(&*tx)
1401 .await?;
1402
1403 if count < 2 {
1404 Err(anyhow!("not room participants"))?;
1405 }
1406
1407 Ok(())
1408 })
1409 .await
1410 }
1411
1412 /// Adds the given follower connection as a follower of the given leader connection.
1413 pub async fn follow(
1414 &self,
1415 room_id: RoomId,
1416 project_id: ProjectId,
1417 leader_connection: ConnectionId,
1418 follower_connection: ConnectionId,
1419 ) -> Result<TransactionGuard<proto::Room>> {
1420 self.room_transaction(room_id, |tx| async move {
1421 follower::ActiveModel {
1422 room_id: ActiveValue::set(room_id),
1423 project_id: ActiveValue::set(project_id),
1424 leader_connection_server_id: ActiveValue::set(ServerId(
1425 leader_connection.owner_id as i32,
1426 )),
1427 leader_connection_id: ActiveValue::set(leader_connection.id as i32),
1428 follower_connection_server_id: ActiveValue::set(ServerId(
1429 follower_connection.owner_id as i32,
1430 )),
1431 follower_connection_id: ActiveValue::set(follower_connection.id as i32),
1432 ..Default::default()
1433 }
1434 .insert(&*tx)
1435 .await?;
1436
1437 let room = self.get_room(room_id, &tx).await?;
1438 Ok(room)
1439 })
1440 .await
1441 }
1442
1443 /// Removes the given follower connection as a follower of the given leader connection.
1444 pub async fn unfollow(
1445 &self,
1446 room_id: RoomId,
1447 project_id: ProjectId,
1448 leader_connection: ConnectionId,
1449 follower_connection: ConnectionId,
1450 ) -> Result<TransactionGuard<proto::Room>> {
1451 self.room_transaction(room_id, |tx| async move {
1452 follower::Entity::delete_many()
1453 .filter(
1454 Condition::all()
1455 .add(follower::Column::RoomId.eq(room_id))
1456 .add(follower::Column::ProjectId.eq(project_id))
1457 .add(
1458 follower::Column::LeaderConnectionServerId
1459 .eq(leader_connection.owner_id),
1460 )
1461 .add(follower::Column::LeaderConnectionId.eq(leader_connection.id))
1462 .add(
1463 follower::Column::FollowerConnectionServerId
1464 .eq(follower_connection.owner_id),
1465 )
1466 .add(follower::Column::FollowerConnectionId.eq(follower_connection.id)),
1467 )
1468 .exec(&*tx)
1469 .await?;
1470
1471 let room = self.get_room(room_id, &tx).await?;
1472 Ok(room)
1473 })
1474 .await
1475 }
1476}