database_rev.rs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. use crate::DatabaseBlockRevision;
  2. use bytes::Bytes;
  3. use indexmap::IndexMap;
  4. use nanoid::nanoid;
  5. use serde::{Deserialize, Serialize};
  6. use std::sync::Arc;
  7. pub fn gen_database_id() -> String {
  8. // nanoid calculator https://zelark.github.io/nano-id-cc/
  9. format!("d:{}", nanoid!(10))
  10. }
  11. pub fn gen_block_id() -> String {
  12. format!("b:{}", nanoid!(10))
  13. }
  14. pub fn gen_field_id() -> String {
  15. nanoid!(6)
  16. }
  17. #[derive(Debug, Clone, Default, Serialize, Deserialize)]
  18. pub struct DatabaseRevision {
  19. #[serde(rename = "grid_id")]
  20. pub database_id: String,
  21. pub fields: Vec<Arc<FieldRevision>>,
  22. pub blocks: Vec<Arc<DatabaseBlockMetaRevision>>,
  23. }
  24. impl DatabaseRevision {
  25. pub fn new(database_id: &str) -> Self {
  26. Self {
  27. database_id: database_id.to_owned(),
  28. fields: vec![],
  29. blocks: vec![],
  30. }
  31. }
  32. pub fn from_build_context(
  33. database_id: &str,
  34. field_revs: Vec<Arc<FieldRevision>>,
  35. block_metas: Vec<DatabaseBlockMetaRevision>,
  36. ) -> Self {
  37. Self {
  38. database_id: database_id.to_owned(),
  39. fields: field_revs,
  40. blocks: block_metas.into_iter().map(Arc::new).collect(),
  41. }
  42. }
  43. }
  44. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
  45. pub struct DatabaseBlockMetaRevision {
  46. pub block_id: String,
  47. pub start_row_index: i32,
  48. pub row_count: i32,
  49. }
  50. impl DatabaseBlockMetaRevision {
  51. pub fn len(&self) -> i32 {
  52. self.row_count
  53. }
  54. pub fn is_empty(&self) -> bool {
  55. self.row_count == 0
  56. }
  57. }
  58. impl DatabaseBlockMetaRevision {
  59. pub fn new() -> Self {
  60. DatabaseBlockMetaRevision {
  61. block_id: gen_block_id(),
  62. ..Default::default()
  63. }
  64. }
  65. }
  66. pub struct DatabaseBlockMetaRevisionChangeset {
  67. pub block_id: String,
  68. pub start_row_index: Option<i32>,
  69. pub row_count: Option<i32>,
  70. }
  71. impl DatabaseBlockMetaRevisionChangeset {
  72. pub fn from_row_count(block_id: String, row_count: i32) -> Self {
  73. Self {
  74. block_id,
  75. start_row_index: None,
  76. row_count: Some(row_count),
  77. }
  78. }
  79. }
  80. #[derive(Debug, Clone, Default, Serialize, Deserialize, Eq, PartialEq)]
  81. pub struct FieldRevision {
  82. pub id: String,
  83. pub name: String,
  84. pub desc: String,
  85. #[serde(rename = "field_type")]
  86. pub ty: FieldTypeRevision,
  87. pub frozen: bool,
  88. pub visibility: bool,
  89. pub width: i32,
  90. /// type_options contains key/value pairs
  91. /// key: id of the FieldType
  92. /// value: type-option data that can be parsed into specified TypeOptionStruct.
  93. ///
  94. /// For example, CheckboxTypeOption, MultiSelectTypeOption etc.
  95. #[serde(with = "indexmap::serde_seq")]
  96. pub type_options: IndexMap<String, String>,
  97. #[serde(default = "DEFAULT_IS_PRIMARY_VALUE")]
  98. pub is_primary: bool,
  99. }
  100. impl AsRef<FieldRevision> for FieldRevision {
  101. fn as_ref(&self) -> &FieldRevision {
  102. self
  103. }
  104. }
  105. const DEFAULT_IS_PRIMARY_VALUE: fn() -> bool = || false;
  106. impl FieldRevision {
  107. pub fn new<T: Into<FieldTypeRevision>>(
  108. name: &str,
  109. desc: &str,
  110. field_type: T,
  111. width: i32,
  112. is_primary: bool,
  113. ) -> Self {
  114. Self {
  115. id: gen_field_id(),
  116. name: name.to_string(),
  117. desc: desc.to_string(),
  118. ty: field_type.into(),
  119. frozen: false,
  120. visibility: true,
  121. width,
  122. type_options: Default::default(),
  123. is_primary,
  124. }
  125. }
  126. pub fn insert_type_option<T>(&mut self, type_option: &T)
  127. where
  128. T: TypeOptionDataSerializer + ?Sized,
  129. {
  130. let id = self.ty.to_string();
  131. self.type_options.insert(id, type_option.json_str());
  132. }
  133. pub fn get_type_option<T: TypeOptionDataDeserializer>(
  134. &self,
  135. field_type_rev: FieldTypeRevision,
  136. ) -> Option<T> {
  137. let id = field_type_rev.to_string();
  138. self.type_options.get(&id).map(|s| T::from_json_str(s))
  139. }
  140. pub fn insert_type_option_str(&mut self, field_type: &FieldTypeRevision, json_str: String) {
  141. let id = field_type.to_string();
  142. self.type_options.insert(id, json_str);
  143. }
  144. pub fn get_type_option_str<T: Into<FieldTypeRevision>>(&self, field_type: T) -> Option<&str> {
  145. let field_type_rev = field_type.into();
  146. let id = field_type_rev.to_string();
  147. self.type_options.get(&id).map(|s| s.as_str())
  148. }
  149. }
  150. /// The macro [impl_type_option] will implement the [TypeOptionDataSerializer] for the type that
  151. /// supports the serde trait and the TryInto<Bytes> trait.
  152. pub trait TypeOptionDataSerializer {
  153. fn json_str(&self) -> String;
  154. fn protobuf_bytes(&self) -> Bytes;
  155. }
  156. /// The macro [impl_type_option] will implement the [TypeOptionDataDeserializer] for the type that
  157. /// supports the serde trait and the TryFrom<Bytes> trait.
  158. pub trait TypeOptionDataDeserializer {
  159. fn from_json_str(s: &str) -> Self;
  160. fn from_protobuf_bytes(bytes: Bytes) -> Self;
  161. }
  162. #[derive(Clone, Default, Deserialize, Serialize)]
  163. pub struct BuildDatabaseContext {
  164. pub field_revs: Vec<Arc<FieldRevision>>,
  165. pub block_metas: Vec<DatabaseBlockMetaRevision>,
  166. pub blocks: Vec<DatabaseBlockRevision>,
  167. // String in JSON format. It can be deserialized into [GridViewRevision]
  168. pub database_view_data: String,
  169. }
  170. impl BuildDatabaseContext {
  171. pub fn new() -> Self {
  172. Self::default()
  173. }
  174. }
  175. impl std::convert::From<BuildDatabaseContext> for Bytes {
  176. fn from(ctx: BuildDatabaseContext) -> Self {
  177. let bytes = serde_json::to_vec(&ctx).unwrap_or_else(|_| vec![]);
  178. Bytes::from(bytes)
  179. }
  180. }
  181. impl std::convert::TryFrom<Bytes> for BuildDatabaseContext {
  182. type Error = serde_json::Error;
  183. fn try_from(bytes: Bytes) -> Result<Self, Self::Error> {
  184. let ctx: BuildDatabaseContext = serde_json::from_slice(&bytes)?;
  185. Ok(ctx)
  186. }
  187. }
  188. pub type FieldTypeRevision = u8;