database.rs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. use crate::entities::{SignInResponse, SignUpResponse, UpdateUserProfileParams, UserProfilePB};
  2. use flowy_database::ConnectionPool;
  3. use flowy_database::{schema::user_table, DBConnection, Database};
  4. use flowy_error::{ErrorCode, FlowyError};
  5. use lazy_static::lazy_static;
  6. use parking_lot::RwLock;
  7. use std::{collections::HashMap, sync::Arc, time::Duration};
  8. lazy_static! {
  9. static ref DB: RwLock<Option<Database>> = RwLock::new(None);
  10. }
  11. pub struct UserDB {
  12. db_dir: String,
  13. }
  14. impl UserDB {
  15. pub fn new(db_dir: &str) -> Self {
  16. Self {
  17. db_dir: db_dir.to_owned(),
  18. }
  19. }
  20. fn open_user_db_if_need(&self, user_id: &str) -> Result<Arc<ConnectionPool>, FlowyError> {
  21. if user_id.is_empty() {
  22. return Err(ErrorCode::UserIdIsEmpty.into());
  23. }
  24. if let Some(database) = DB_MAP.read().get(user_id) {
  25. return Ok(database.get_pool());
  26. }
  27. let mut write_guard = DB_MAP.write();
  28. // The Write guard acquire exclusive access that will guarantee the user db only initialize once.
  29. match write_guard.get(user_id) {
  30. None => {}
  31. Some(database) => return Ok(database.get_pool()),
  32. }
  33. tracing::trace!("open user db {}", user_id);
  34. let dir = format!("{}/{}", self.db_dir, user_id);
  35. let db = flowy_database::init(&dir).map_err(|e| {
  36. log::error!("open user: {} db failed, {:?}", user_id, e);
  37. FlowyError::internal().context(e)
  38. })?;
  39. let pool = db.get_pool();
  40. write_guard.insert(user_id.to_owned(), db);
  41. drop(write_guard);
  42. Ok(pool)
  43. }
  44. pub(crate) fn close_user_db(&self, user_id: &str) -> Result<(), FlowyError> {
  45. match DB_MAP.try_write_for(Duration::from_millis(300)) {
  46. None => Err(FlowyError::internal().context("Acquire write lock to close user db failed")),
  47. Some(mut write_guard) => {
  48. write_guard.remove(user_id);
  49. Ok(())
  50. }
  51. }
  52. }
  53. pub(crate) fn get_connection(&self, user_id: &str) -> Result<DBConnection, FlowyError> {
  54. let conn = self.get_pool(user_id)?.get()?;
  55. Ok(conn)
  56. }
  57. pub(crate) fn get_pool(&self, user_id: &str) -> Result<Arc<ConnectionPool>, FlowyError> {
  58. let pool = self.open_user_db_if_need(user_id)?;
  59. Ok(pool)
  60. }
  61. }
  62. lazy_static! {
  63. static ref DB_MAP: RwLock<HashMap<String, Database>> = RwLock::new(HashMap::new());
  64. }
  65. #[derive(Clone, Default, Queryable, Identifiable, Insertable)]
  66. #[table_name = "user_table"]
  67. pub struct UserTable {
  68. pub(crate) id: String,
  69. pub(crate) name: String,
  70. pub(crate) token: String,
  71. pub(crate) email: String,
  72. pub(crate) workspace: String, // deprecated
  73. }
  74. impl UserTable {
  75. pub fn new(id: String, name: String, email: String, token: String) -> Self {
  76. Self {
  77. id,
  78. name,
  79. email,
  80. token,
  81. workspace: "".to_owned(),
  82. }
  83. }
  84. pub fn set_workspace(mut self, workspace: String) -> Self {
  85. self.workspace = workspace;
  86. self
  87. }
  88. }
  89. impl std::convert::From<SignUpResponse> for UserTable {
  90. fn from(resp: SignUpResponse) -> Self {
  91. UserTable::new(resp.user_id, resp.name, resp.email, resp.token)
  92. }
  93. }
  94. impl std::convert::From<SignInResponse> for UserTable {
  95. fn from(resp: SignInResponse) -> Self {
  96. UserTable::new(resp.user_id, resp.name, resp.email, resp.token)
  97. }
  98. }
  99. impl std::convert::From<UserTable> for UserProfilePB {
  100. fn from(table: UserTable) -> Self {
  101. UserProfilePB {
  102. id: table.id,
  103. email: table.email,
  104. name: table.name,
  105. token: table.token,
  106. }
  107. }
  108. }
  109. #[derive(AsChangeset, Identifiable, Default, Debug)]
  110. #[table_name = "user_table"]
  111. pub struct UserTableChangeset {
  112. pub id: String,
  113. pub workspace: Option<String>, // deprecated
  114. pub name: Option<String>,
  115. pub email: Option<String>,
  116. }
  117. impl UserTableChangeset {
  118. pub fn new(params: UpdateUserProfileParams) -> Self {
  119. UserTableChangeset {
  120. id: params.id,
  121. workspace: None,
  122. name: params.name,
  123. email: params.email,
  124. }
  125. }
  126. }