db.rs

  1mod ids;
  2mod queries;
  3mod tables;
  4#[cfg(test)]
  5pub mod tests;
  6
  7use crate::{Error, Result};
  8use anyhow::{Context as _, anyhow};
  9use collections::{BTreeMap, BTreeSet, HashMap, HashSet};
 10use dashmap::DashMap;
 11use futures::StreamExt;
 12use project_repository_statuses::StatusKind;
 13use rpc::ExtensionProvides;
 14use rpc::{
 15    ConnectionId, ExtensionMetadata,
 16    proto::{self},
 17};
 18use sea_orm::{
 19    ActiveValue, Condition, ConnectionTrait, DatabaseConnection, DatabaseTransaction,
 20    FromQueryResult, IntoActiveModel, IsolationLevel, JoinType, QueryOrder, QuerySelect, Statement,
 21    TransactionTrait,
 22    entity::prelude::*,
 23    sea_query::{Alias, Expr, OnConflict},
 24};
 25use semantic_version::SemanticVersion;
 26use serde::{Deserialize, Serialize};
 27use std::ops::RangeInclusive;
 28use std::{
 29    fmt::Write as _,
 30    future::Future,
 31    marker::PhantomData,
 32    ops::{Deref, DerefMut},
 33    rc::Rc,
 34    sync::Arc,
 35};
 36use time::PrimitiveDateTime;
 37use tokio::sync::{Mutex, OwnedMutexGuard};
 38use worktree_settings_file::LocalSettingsKind;
 39
 40#[cfg(test)]
 41pub use tests::TestDb;
 42
 43pub use ids::*;
 44pub use queries::billing_customers::{CreateBillingCustomerParams, UpdateBillingCustomerParams};
 45pub use queries::billing_subscriptions::{
 46    CreateBillingSubscriptionParams, UpdateBillingSubscriptionParams,
 47};
 48pub use queries::contributors::ContributorSelector;
 49pub use queries::processed_stripe_events::CreateProcessedStripeEventParams;
 50pub use sea_orm::ConnectOptions;
 51pub use tables::user::Model as User;
 52pub use tables::*;
 53
 54#[cfg(test)]
 55pub struct DatabaseTestOptions {
 56    pub executor: gpui::BackgroundExecutor,
 57    pub runtime: tokio::runtime::Runtime,
 58    pub query_failure_probability: parking_lot::Mutex<f64>,
 59}
 60
 61/// Database gives you a handle that lets you access the database.
 62/// It handles pooling internally.
 63pub struct Database {
 64    options: ConnectOptions,
 65    pool: DatabaseConnection,
 66    rooms: DashMap<RoomId, Arc<Mutex<()>>>,
 67    projects: DashMap<ProjectId, Arc<Mutex<()>>>,
 68    notification_kinds_by_id: HashMap<NotificationKindId, &'static str>,
 69    notification_kinds_by_name: HashMap<String, NotificationKindId>,
 70    #[cfg(test)]
 71    test_options: Option<DatabaseTestOptions>,
 72}
 73
 74// The `Database` type has so many methods that its impl blocks are split into
 75// separate files in the `queries` folder.
 76impl Database {
 77    /// Connects to the database with the given options
 78    pub async fn new(options: ConnectOptions) -> Result<Self> {
 79        sqlx::any::install_default_drivers();
 80        Ok(Self {
 81            options: options.clone(),
 82            pool: sea_orm::Database::connect(options).await?,
 83            rooms: DashMap::with_capacity(16384),
 84            projects: DashMap::with_capacity(16384),
 85            notification_kinds_by_id: HashMap::default(),
 86            notification_kinds_by_name: HashMap::default(),
 87            #[cfg(test)]
 88            test_options: None,
 89        })
 90    }
 91
 92    pub fn options(&self) -> &ConnectOptions {
 93        &self.options
 94    }
 95
 96    #[cfg(test)]
 97    pub fn reset(&self) {
 98        self.rooms.clear();
 99        self.projects.clear();
100    }
101
102    pub async fn transaction<F, Fut, T>(&self, f: F) -> Result<T>
103    where
104        F: Send + Fn(TransactionHandle) -> Fut,
105        Fut: Send + Future<Output = Result<T>>,
106    {
107        let body = async {
108            let (tx, result) = self.with_transaction(&f).await?;
109            match result {
110                Ok(result) => match tx.commit().await.map_err(Into::into) {
111                    Ok(()) => Ok(result),
112                    Err(error) => Err(error),
113                },
114                Err(error) => {
115                    tx.rollback().await?;
116                    Err(error)
117                }
118            }
119        };
120
121        self.run(body).await
122    }
123
124    /// The same as room_transaction, but if you need to only optionally return a Room.
125    async fn optional_room_transaction<F, Fut, T>(
126        &self,
127        f: F,
128    ) -> Result<Option<TransactionGuard<T>>>
129    where
130        F: Send + Fn(TransactionHandle) -> Fut,
131        Fut: Send + Future<Output = Result<Option<(RoomId, T)>>>,
132    {
133        let body = async {
134            let (tx, result) = self.with_transaction(&f).await?;
135            match result {
136                Ok(Some((room_id, data))) => {
137                    let lock = self.rooms.entry(room_id).or_default().clone();
138                    let _guard = lock.lock_owned().await;
139                    match tx.commit().await.map_err(Into::into) {
140                        Ok(()) => Ok(Some(TransactionGuard {
141                            data,
142                            _guard,
143                            _not_send: PhantomData,
144                        })),
145                        Err(error) => Err(error),
146                    }
147                }
148                Ok(None) => match tx.commit().await.map_err(Into::into) {
149                    Ok(()) => Ok(None),
150                    Err(error) => Err(error),
151                },
152                Err(error) => {
153                    tx.rollback().await?;
154                    Err(error)
155                }
156            }
157        };
158
159        self.run(body).await
160    }
161
162    async fn project_transaction<F, Fut, T>(
163        &self,
164        project_id: ProjectId,
165        f: F,
166    ) -> Result<TransactionGuard<T>>
167    where
168        F: Send + Fn(TransactionHandle) -> Fut,
169        Fut: Send + Future<Output = Result<T>>,
170    {
171        let room_id = Database::room_id_for_project(self, project_id).await?;
172        let body = async {
173            let lock = if let Some(room_id) = room_id {
174                self.rooms.entry(room_id).or_default().clone()
175            } else {
176                self.projects.entry(project_id).or_default().clone()
177            };
178            let _guard = lock.lock_owned().await;
179            let (tx, result) = self.with_transaction(&f).await?;
180            match result {
181                Ok(data) => match tx.commit().await.map_err(Into::into) {
182                    Ok(()) => Ok(TransactionGuard {
183                        data,
184                        _guard,
185                        _not_send: PhantomData,
186                    }),
187                    Err(error) => Err(error),
188                },
189                Err(error) => {
190                    tx.rollback().await?;
191                    Err(error)
192                }
193            }
194        };
195
196        self.run(body).await
197    }
198
199    /// room_transaction runs the block in a transaction. It returns a RoomGuard, that keeps
200    /// the database locked until it is dropped. This ensures that updates sent to clients are
201    /// properly serialized with respect to database changes.
202    async fn room_transaction<F, Fut, T>(
203        &self,
204        room_id: RoomId,
205        f: F,
206    ) -> Result<TransactionGuard<T>>
207    where
208        F: Send + Fn(TransactionHandle) -> Fut,
209        Fut: Send + Future<Output = Result<T>>,
210    {
211        let body = async {
212            let lock = self.rooms.entry(room_id).or_default().clone();
213            let _guard = lock.lock_owned().await;
214            let (tx, result) = self.with_transaction(&f).await?;
215            match result {
216                Ok(data) => match tx.commit().await.map_err(Into::into) {
217                    Ok(()) => Ok(TransactionGuard {
218                        data,
219                        _guard,
220                        _not_send: PhantomData,
221                    }),
222                    Err(error) => Err(error),
223                },
224                Err(error) => {
225                    tx.rollback().await?;
226                    Err(error)
227                }
228            }
229        };
230
231        self.run(body).await
232    }
233
234    async fn with_transaction<F, Fut, T>(&self, f: &F) -> Result<(DatabaseTransaction, Result<T>)>
235    where
236        F: Send + Fn(TransactionHandle) -> Fut,
237        Fut: Send + Future<Output = Result<T>>,
238    {
239        let tx = self
240            .pool
241            .begin_with_config(Some(IsolationLevel::ReadCommitted), None)
242            .await?;
243
244        let mut tx = Arc::new(Some(tx));
245        let result = f(TransactionHandle(tx.clone())).await;
246        let tx = Arc::get_mut(&mut tx)
247            .and_then(|tx| tx.take())
248            .context("couldn't complete transaction because it's still in use")?;
249
250        Ok((tx, result))
251    }
252
253    async fn run<F, T>(&self, future: F) -> Result<T>
254    where
255        F: Future<Output = Result<T>>,
256    {
257        #[cfg(test)]
258        {
259            use rand::prelude::*;
260
261            let test_options = self.test_options.as_ref().unwrap();
262            test_options.executor.simulate_random_delay().await;
263            let fail_probability = *test_options.query_failure_probability.lock();
264            if test_options.executor.rng().gen_bool(fail_probability) {
265                return Err(anyhow!("simulated query failure"))?;
266            }
267
268            test_options.runtime.block_on(future)
269        }
270
271        #[cfg(not(test))]
272        {
273            future.await
274        }
275    }
276}
277
278/// A handle to a [`DatabaseTransaction`].
279pub struct TransactionHandle(pub(crate) Arc<Option<DatabaseTransaction>>);
280
281impl Deref for TransactionHandle {
282    type Target = DatabaseTransaction;
283
284    fn deref(&self) -> &Self::Target {
285        self.0.as_ref().as_ref().unwrap()
286    }
287}
288
289/// [`TransactionGuard`] keeps a database transaction alive until it is dropped.
290/// It wraps data that depends on the state of the database and prevents an additional
291/// transaction from starting that would invalidate that data.
292pub struct TransactionGuard<T> {
293    data: T,
294    _guard: OwnedMutexGuard<()>,
295    _not_send: PhantomData<Rc<()>>,
296}
297
298impl<T> Deref for TransactionGuard<T> {
299    type Target = T;
300
301    fn deref(&self) -> &T {
302        &self.data
303    }
304}
305
306impl<T> DerefMut for TransactionGuard<T> {
307    fn deref_mut(&mut self) -> &mut T {
308        &mut self.data
309    }
310}
311
312impl<T> TransactionGuard<T> {
313    /// Returns the inner value of the guard.
314    pub fn into_inner(self) -> T {
315        self.data
316    }
317}
318
319#[derive(Clone, Debug, PartialEq, Eq)]
320pub enum Contact {
321    Accepted { user_id: UserId, busy: bool },
322    Outgoing { user_id: UserId },
323    Incoming { user_id: UserId },
324}
325
326impl Contact {
327    pub fn user_id(&self) -> UserId {
328        match self {
329            Contact::Accepted { user_id, .. } => *user_id,
330            Contact::Outgoing { user_id } => *user_id,
331            Contact::Incoming { user_id, .. } => *user_id,
332        }
333    }
334}
335
336pub type NotificationBatch = Vec<(UserId, proto::Notification)>;
337
338pub struct CreatedChannelMessage {
339    pub message_id: MessageId,
340    pub participant_connection_ids: HashSet<ConnectionId>,
341    pub notifications: NotificationBatch,
342}
343
344pub struct UpdatedChannelMessage {
345    pub message_id: MessageId,
346    pub participant_connection_ids: Vec<ConnectionId>,
347    pub notifications: NotificationBatch,
348    pub reply_to_message_id: Option<MessageId>,
349    pub timestamp: PrimitiveDateTime,
350    pub deleted_mention_notification_ids: Vec<NotificationId>,
351    pub updated_mention_notifications: Vec<rpc::proto::Notification>,
352}
353
354#[derive(Clone, Debug, PartialEq, Eq, FromQueryResult, Serialize, Deserialize)]
355pub struct Invite {
356    pub email_address: String,
357    pub email_confirmation_code: String,
358}
359
360#[derive(Clone, Debug, Deserialize)]
361pub struct NewSignup {
362    pub email_address: String,
363    pub platform_mac: bool,
364    pub platform_windows: bool,
365    pub platform_linux: bool,
366    pub editor_features: Vec<String>,
367    pub programming_languages: Vec<String>,
368    pub device_id: Option<String>,
369    pub added_to_mailing_list: bool,
370    pub created_at: Option<DateTime>,
371}
372
373#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, FromQueryResult)]
374pub struct WaitlistSummary {
375    pub count: i64,
376    pub linux_count: i64,
377    pub mac_count: i64,
378    pub windows_count: i64,
379    pub unknown_count: i64,
380}
381
382/// The parameters to create a new user.
383#[derive(Debug, Serialize, Deserialize)]
384pub struct NewUserParams {
385    pub github_login: String,
386    pub github_user_id: i32,
387}
388
389/// The result of creating a new user.
390#[derive(Debug)]
391pub struct NewUserResult {
392    pub user_id: UserId,
393    pub metrics_id: String,
394    pub inviting_user_id: Option<UserId>,
395    pub signup_device_id: Option<String>,
396}
397
398/// The result of updating a channel membership.
399#[derive(Debug)]
400pub struct MembershipUpdated {
401    pub channel_id: ChannelId,
402    pub new_channels: ChannelsForUser,
403    pub removed_channels: Vec<ChannelId>,
404}
405
406/// The result of setting a member's role.
407#[derive(Debug)]
408
409pub enum SetMemberRoleResult {
410    InviteUpdated(Channel),
411    MembershipUpdated(MembershipUpdated),
412}
413
414/// The result of inviting a member to a channel.
415#[derive(Debug)]
416pub struct InviteMemberResult {
417    pub channel: Channel,
418    pub notifications: NotificationBatch,
419}
420
421#[derive(Debug)]
422pub struct RespondToChannelInvite {
423    pub membership_update: Option<MembershipUpdated>,
424    pub notifications: NotificationBatch,
425}
426
427#[derive(Debug)]
428pub struct RemoveChannelMemberResult {
429    pub membership_update: MembershipUpdated,
430    pub notification_id: Option<NotificationId>,
431}
432
433#[derive(Debug, PartialEq, Eq, Hash)]
434pub struct Channel {
435    pub id: ChannelId,
436    pub name: String,
437    pub visibility: ChannelVisibility,
438    /// parent_path is the channel ids from the root to this one (not including this one)
439    pub parent_path: Vec<ChannelId>,
440    pub channel_order: i32,
441}
442
443impl Channel {
444    pub fn from_model(value: channel::Model) -> Self {
445        Channel {
446            id: value.id,
447            visibility: value.visibility,
448            name: value.clone().name,
449            parent_path: value.ancestors().collect(),
450            channel_order: value.channel_order,
451        }
452    }
453
454    pub fn to_proto(&self) -> proto::Channel {
455        proto::Channel {
456            id: self.id.to_proto(),
457            name: self.name.clone(),
458            visibility: self.visibility.into(),
459            parent_path: self.parent_path.iter().map(|c| c.to_proto()).collect(),
460            channel_order: self.channel_order,
461        }
462    }
463
464    pub fn root_id(&self) -> ChannelId {
465        self.parent_path.first().copied().unwrap_or(self.id)
466    }
467}
468
469#[derive(Debug, PartialEq, Eq, Hash)]
470pub struct ChannelMember {
471    pub role: ChannelRole,
472    pub user_id: UserId,
473    pub kind: proto::channel_member::Kind,
474}
475
476impl ChannelMember {
477    pub fn to_proto(&self) -> proto::ChannelMember {
478        proto::ChannelMember {
479            role: self.role.into(),
480            user_id: self.user_id.to_proto(),
481            kind: self.kind.into(),
482        }
483    }
484}
485
486#[derive(Debug, PartialEq)]
487pub struct ChannelsForUser {
488    pub channels: Vec<Channel>,
489    pub channel_memberships: Vec<channel_member::Model>,
490    pub channel_participants: HashMap<ChannelId, Vec<UserId>>,
491    pub invited_channels: Vec<Channel>,
492
493    pub observed_buffer_versions: Vec<proto::ChannelBufferVersion>,
494    pub observed_channel_messages: Vec<proto::ChannelMessageId>,
495    pub latest_buffer_versions: Vec<proto::ChannelBufferVersion>,
496    pub latest_channel_messages: Vec<proto::ChannelMessageId>,
497}
498
499#[derive(Debug)]
500pub struct RejoinedChannelBuffer {
501    pub buffer: proto::RejoinedChannelBuffer,
502    pub old_connection_id: ConnectionId,
503}
504
505#[derive(Clone)]
506pub struct JoinRoom {
507    pub room: proto::Room,
508    pub channel: Option<channel::Model>,
509}
510
511pub struct RejoinedRoom {
512    pub room: proto::Room,
513    pub rejoined_projects: Vec<RejoinedProject>,
514    pub reshared_projects: Vec<ResharedProject>,
515    pub channel: Option<channel::Model>,
516}
517
518pub struct ResharedProject {
519    pub id: ProjectId,
520    pub old_connection_id: ConnectionId,
521    pub collaborators: Vec<ProjectCollaborator>,
522    pub worktrees: Vec<proto::WorktreeMetadata>,
523}
524
525pub struct RejoinedProject {
526    pub id: ProjectId,
527    pub old_connection_id: ConnectionId,
528    pub collaborators: Vec<ProjectCollaborator>,
529    pub worktrees: Vec<RejoinedWorktree>,
530    pub updated_repositories: Vec<proto::UpdateRepository>,
531    pub removed_repositories: Vec<u64>,
532    pub language_servers: Vec<LanguageServer>,
533}
534
535impl RejoinedProject {
536    pub fn to_proto(&self) -> proto::RejoinedProject {
537        let (language_servers, language_server_capabilities) = self
538            .language_servers
539            .clone()
540            .into_iter()
541            .map(|server| (server.server, server.capabilities))
542            .unzip();
543        proto::RejoinedProject {
544            id: self.id.to_proto(),
545            worktrees: self
546                .worktrees
547                .iter()
548                .map(|worktree| proto::WorktreeMetadata {
549                    id: worktree.id,
550                    root_name: worktree.root_name.clone(),
551                    visible: worktree.visible,
552                    abs_path: worktree.abs_path.clone(),
553                })
554                .collect(),
555            collaborators: self
556                .collaborators
557                .iter()
558                .map(|collaborator| collaborator.to_proto())
559                .collect(),
560            language_servers,
561            language_server_capabilities,
562        }
563    }
564}
565
566#[derive(Debug)]
567pub struct RejoinedWorktree {
568    pub id: u64,
569    pub abs_path: String,
570    pub root_name: String,
571    pub visible: bool,
572    pub updated_entries: Vec<proto::Entry>,
573    pub removed_entries: Vec<u64>,
574    pub updated_repositories: Vec<proto::RepositoryEntry>,
575    pub removed_repositories: Vec<u64>,
576    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
577    pub settings_files: Vec<WorktreeSettingsFile>,
578    pub scan_id: u64,
579    pub completed_scan_id: u64,
580}
581
582pub struct LeftRoom {
583    pub room: proto::Room,
584    pub channel: Option<channel::Model>,
585    pub left_projects: HashMap<ProjectId, LeftProject>,
586    pub canceled_calls_to_user_ids: Vec<UserId>,
587    pub deleted: bool,
588}
589
590pub struct RefreshedRoom {
591    pub room: proto::Room,
592    pub channel: Option<channel::Model>,
593    pub stale_participant_user_ids: Vec<UserId>,
594    pub canceled_calls_to_user_ids: Vec<UserId>,
595}
596
597pub struct RefreshedChannelBuffer {
598    pub connection_ids: Vec<ConnectionId>,
599    pub collaborators: Vec<proto::Collaborator>,
600}
601
602pub struct Project {
603    pub id: ProjectId,
604    pub role: ChannelRole,
605    pub collaborators: Vec<ProjectCollaborator>,
606    pub worktrees: BTreeMap<u64, Worktree>,
607    pub repositories: Vec<proto::UpdateRepository>,
608    pub language_servers: Vec<LanguageServer>,
609}
610
611pub struct ProjectCollaborator {
612    pub connection_id: ConnectionId,
613    pub user_id: UserId,
614    pub replica_id: ReplicaId,
615    pub is_host: bool,
616    pub committer_name: Option<String>,
617    pub committer_email: Option<String>,
618}
619
620impl ProjectCollaborator {
621    pub fn to_proto(&self) -> proto::Collaborator {
622        proto::Collaborator {
623            peer_id: Some(self.connection_id.into()),
624            replica_id: self.replica_id.0 as u32,
625            user_id: self.user_id.to_proto(),
626            is_host: self.is_host,
627            committer_name: self.committer_name.clone(),
628            committer_email: self.committer_email.clone(),
629        }
630    }
631}
632
633#[derive(Debug, Clone)]
634pub struct LanguageServer {
635    pub server: proto::LanguageServer,
636    pub capabilities: String,
637}
638
639#[derive(Debug)]
640pub struct LeftProject {
641    pub id: ProjectId,
642    pub should_unshare: bool,
643    pub connection_ids: Vec<ConnectionId>,
644}
645
646pub struct Worktree {
647    pub id: u64,
648    pub abs_path: String,
649    pub root_name: String,
650    pub visible: bool,
651    pub entries: Vec<proto::Entry>,
652    pub legacy_repository_entries: BTreeMap<u64, proto::RepositoryEntry>,
653    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
654    pub settings_files: Vec<WorktreeSettingsFile>,
655    pub scan_id: u64,
656    pub completed_scan_id: u64,
657}
658
659#[derive(Debug)]
660pub struct WorktreeSettingsFile {
661    pub path: String,
662    pub content: String,
663    pub kind: LocalSettingsKind,
664}
665
666pub struct NewExtensionVersion {
667    pub name: String,
668    pub version: semver::Version,
669    pub description: String,
670    pub authors: Vec<String>,
671    pub repository: String,
672    pub schema_version: i32,
673    pub wasm_api_version: Option<String>,
674    pub provides: BTreeSet<ExtensionProvides>,
675    pub published_at: PrimitiveDateTime,
676}
677
678pub struct ExtensionVersionConstraints {
679    pub schema_versions: RangeInclusive<i32>,
680    pub wasm_api_versions: RangeInclusive<SemanticVersion>,
681}
682
683impl LocalSettingsKind {
684    pub fn from_proto(proto_kind: proto::LocalSettingsKind) -> Self {
685        match proto_kind {
686            proto::LocalSettingsKind::Settings => Self::Settings,
687            proto::LocalSettingsKind::Tasks => Self::Tasks,
688            proto::LocalSettingsKind::Editorconfig => Self::Editorconfig,
689            proto::LocalSettingsKind::Debug => Self::Debug,
690        }
691    }
692
693    pub fn to_proto(&self) -> proto::LocalSettingsKind {
694        match self {
695            Self::Settings => proto::LocalSettingsKind::Settings,
696            Self::Tasks => proto::LocalSettingsKind::Tasks,
697            Self::Editorconfig => proto::LocalSettingsKind::Editorconfig,
698            Self::Debug => proto::LocalSettingsKind::Debug,
699        }
700    }
701}
702
703fn db_status_to_proto(
704    entry: project_repository_statuses::Model,
705) -> anyhow::Result<proto::StatusEntry> {
706    use proto::git_file_status::{Tracked, Unmerged, Variant};
707
708    let (simple_status, variant) =
709        match (entry.status_kind, entry.first_status, entry.second_status) {
710            (StatusKind::Untracked, None, None) => (
711                proto::GitStatus::Added as i32,
712                Variant::Untracked(Default::default()),
713            ),
714            (StatusKind::Ignored, None, None) => (
715                proto::GitStatus::Added as i32,
716                Variant::Ignored(Default::default()),
717            ),
718            (StatusKind::Unmerged, Some(first_head), Some(second_head)) => (
719                proto::GitStatus::Conflict as i32,
720                Variant::Unmerged(Unmerged {
721                    first_head,
722                    second_head,
723                }),
724            ),
725            (StatusKind::Tracked, Some(index_status), Some(worktree_status)) => {
726                let simple_status = if worktree_status != proto::GitStatus::Unmodified as i32 {
727                    worktree_status
728                } else if index_status != proto::GitStatus::Unmodified as i32 {
729                    index_status
730                } else {
731                    proto::GitStatus::Unmodified as i32
732                };
733                (
734                    simple_status,
735                    Variant::Tracked(Tracked {
736                        index_status,
737                        worktree_status,
738                    }),
739                )
740            }
741            _ => {
742                anyhow::bail!("Unexpected combination of status fields: {entry:?}");
743            }
744        };
745    Ok(proto::StatusEntry {
746        repo_path: entry.repo_path,
747        simple_status,
748        status: Some(proto::GitFileStatus {
749            variant: Some(variant),
750        }),
751    })
752}
753
754fn proto_status_to_db(
755    status_entry: proto::StatusEntry,
756) -> (String, StatusKind, Option<i32>, Option<i32>) {
757    use proto::git_file_status::{Tracked, Unmerged, Variant};
758
759    let (status_kind, first_status, second_status) = status_entry
760        .status
761        .clone()
762        .and_then(|status| status.variant)
763        .map_or(
764            (StatusKind::Untracked, None, None),
765            |variant| match variant {
766                Variant::Untracked(_) => (StatusKind::Untracked, None, None),
767                Variant::Ignored(_) => (StatusKind::Ignored, None, None),
768                Variant::Unmerged(Unmerged {
769                    first_head,
770                    second_head,
771                }) => (StatusKind::Unmerged, Some(first_head), Some(second_head)),
772                Variant::Tracked(Tracked {
773                    index_status,
774                    worktree_status,
775                }) => (
776                    StatusKind::Tracked,
777                    Some(index_status),
778                    Some(worktree_status),
779                ),
780            },
781        );
782    (
783        status_entry.repo_path,
784        status_kind,
785        first_status,
786        second_status,
787    )
788}