native_db_32bit/transaction/rw_transaction.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
use crate::db_type::{Input, Result};
use crate::transaction::internal::rw_transaction::InternalRwTransaction;
use crate::transaction::query::RwDrain;
use crate::transaction::query::RwGet;
use crate::transaction::query::RwLen;
use crate::transaction::query::RwScan;
use crate::watch;
use crate::watch::Event;
use std::cell::RefCell;
use std::fmt::Debug;
use std::sync::{Arc, RwLock};
pub struct RwTransaction<'db> {
pub(crate) watcher: &'db Arc<RwLock<watch::Watchers>>,
pub(crate) batch: RefCell<watch::Batch>,
pub(crate) internal: InternalRwTransaction<'db>,
}
impl<'db> RwTransaction<'db> {
/// Get a value from the database.
///
/// Same as [`RTransaction::get()`](struct.RTransaction.html#method.get).
pub fn get<'txn>(&'txn self) -> RwGet<'db, 'txn> {
RwGet {
internal: &self.internal,
}
}
/// Get values from the database.
///
/// Same as [`RTransaction::scan()`](struct.RTransaction.html#method.scan).
pub fn scan<'txn>(&'txn self) -> RwScan<'db, 'txn> {
RwScan {
internal: &self.internal,
}
}
/// Get the number of values in the database.
///
/// Same as [`RTransaction::len()`](struct.RTransaction.html#method.len).
pub fn len<'txn>(&'txn self) -> RwLen<'db, 'txn> {
RwLen {
internal: &self.internal,
}
}
/// Get all values from the database.
///
/// Same as [`RTransaction::drain()`](struct.RTransaction.html#method.drain).
pub fn drain<'txn>(&'txn self) -> RwDrain<'db, 'txn> {
RwDrain {
internal: &self.internal,
}
}
}
impl<'db, 'txn> RwTransaction<'db> {
/// Commit the transaction.
/// All changes will be applied to the database. If the commit fails, the transaction will be aborted. The
/// database will be unchanged.
///
/// # Example
/// ```rust
/// use native_db::*;
///
/// fn main() -> Result<(), db_type::Error> {
/// let mut builder = DatabaseBuilder::new();
/// let db = builder.create_in_memory()?;
///
/// // Open a read transaction
/// let rw = db.rw_transaction()?;
/// // Do some stuff..
/// rw.commit()?;
///
/// Ok(())
/// }
/// ```
pub fn commit(self) -> Result<()> {
self.internal.commit()?;
// Send batch to watchers after commit succeeds
let batch = self.batch.into_inner();
watch::push_batch(Arc::clone(&self.watcher), batch)?;
Ok(())
}
}
impl<'db, 'txn> RwTransaction<'db> {
/// Insert a value into the database.
///
/// # Example
/// ```rust
/// use native_db::*;
/// use native_model::{native_model, Model};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize)]
/// #[native_model(id=1, version=1)]
/// #[native_db]
/// struct Data {
/// #[primary_key]
/// id: u64,
/// }
///
/// fn main() -> Result<(), db_type::Error> {
/// let mut builder = DatabaseBuilder::new();
/// builder.define::<Data>()?;
/// let db = builder.create_in_memory()?;
///
/// // Open a read transaction
/// let rw = db.rw_transaction()?;
///
/// // Insert a value
/// rw.insert(Data { id: 1 })?;
///
/// // /!\ Don't forget to commit the transaction
/// rw.commit()?;
///
/// Ok(())
/// }
/// ```
pub fn insert<T: Input>(&self, item: T) -> Result<()> {
let (watcher_request, binary_value) = self
.internal
.concrete_insert(T::native_db_model(), item.to_item())?;
let event = Event::new_insert(binary_value);
self.batch.borrow_mut().add(watcher_request, event);
Ok(())
}
/// Remove a value from the database.
///
/// # Example
/// ```rust
/// use native_db::*;
/// use native_model::{native_model, Model};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize)]
/// #[native_model(id=1, version=1)]
/// #[native_db]
/// struct Data {
/// #[primary_key]
/// id: u64,
/// }
///
/// fn main() -> Result<(), db_type::Error> {
/// let mut builder = DatabaseBuilder::new();
/// builder.define::<Data>()?;
/// let db = builder.create_in_memory()?;
///
/// // Open a read transaction
/// let rw = db.rw_transaction()?;
///
/// // Remove a value
/// let old_value = rw.remove(Data { id: 1 })?;
///
/// // /!\ Don't forget to commit the transaction
/// rw.commit()?;
///
/// Ok(())
/// }
/// ```
pub fn remove<T: Input>(&self, item: T) -> Result<T> {
let (watcher_request, binary_value) = self
.internal
.concrete_remove(T::native_db_model(), item.to_item())?;
let event = Event::new_delete(binary_value.clone());
self.batch.borrow_mut().add(watcher_request, event);
Ok(binary_value.inner())
}
/// Update a value in the database.
///
/// That allow to update all keys (primary and secondary) of the value.
///
/// # Example
/// ```rust
/// use native_db::*;
/// use native_model::{native_model, Model};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize)]
/// #[native_model(id=1, version=1)]
/// #[native_db]
/// struct Data {
/// #[primary_key]
/// id: u64,
/// }
///
/// fn main() -> Result<(), db_type::Error> {
/// let mut builder = DatabaseBuilder::new();
/// builder.define::<Data>()?;
/// let db = builder.create_in_memory()?;
///
/// // Open a read transaction
/// let rw = db.rw_transaction()?;
///
/// // Remove a value
/// rw.update(Data { id: 1 }, Data { id: 2 })?;
///
/// // /!\ Don't forget to commit the transaction
/// rw.commit()?;
///
/// Ok(())
/// }
/// ```
pub fn update<T: Input>(&self, old_item: T, updated_item: T) -> Result<()> {
let (watcher_request, old_binary_value, new_binary_value) = self.internal.concrete_update(
T::native_db_model(),
old_item.to_item(),
updated_item.to_item(),
)?;
let event = Event::new_update(old_binary_value, new_binary_value);
self.batch.borrow_mut().add(watcher_request, event);
Ok(())
}
/// Convert all values from the database.
///
/// This is useful when you want to change the type/model of a value.
/// You have to define [`From<SourceModel> for TargetModel`](https://doc.rust-lang.org/std/convert/trait.From.html) to convert the value.
///
/// ```rust
/// use native_db::*;
/// use native_model::{native_model, Model};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize, Clone)]
/// #[native_model(id=1, version=1)]
/// #[native_db]
/// struct Dog {
/// #[primary_key]
/// name: String,
/// }
///
/// #[derive(Serialize, Deserialize)]
/// #[native_model(id=2, version=1)]
/// #[native_db]
/// struct Animal {
/// #[primary_key]
/// name: String,
/// #[secondary_key]
/// specie: String,
/// }
///
/// impl From<Dog> for Animal {
/// fn from(dog: Dog) -> Self {
/// Animal {
/// name: dog.name,
/// specie: "dog".to_string(),
/// }
/// }
/// }
///
/// fn main() -> Result<(), db_type::Error> {
/// let mut builder = DatabaseBuilder::new();
/// builder.define::<Dog>()?;
/// builder.define::<Animal>()?;
/// let db = builder.create_in_memory()?;
///
/// // Open a read transaction
/// let rw = db.rw_transaction()?;
///
/// // Convert all values from Dog to Animal
/// rw.convert_all::<Dog, Animal>()?;
///
/// // /!\ Don't forget to commit the transaction
/// rw.commit()?;
///
/// Ok(())
/// }
/// ```
pub fn convert_all<OldType, NewType>(&self) -> Result<()>
where
OldType: Input + Clone,
NewType: Input + From<OldType>,
{
let find_all_old: Vec<OldType> = self.scan().primary()?.all().collect();
for old in find_all_old {
let new: NewType = old.clone().into();
self.internal
.concrete_insert(NewType::native_db_model(), new.to_item())?;
self.internal
.concrete_remove(OldType::native_db_model(), old.to_item())?;
}
Ok(())
}
/// Automatically migrate the data from the old model to the new model. **No matter the state of the database**,
/// if all models remain defined in the application as they are, the data will be migrated to the most recent version automatically.
///
/// Native DB use the [`native_model`](https://crates.io/crates/native_model) identifier `id` to identify the model and `version` to identify the version of the model.
/// We can define a model with the same identifier `id` but with a different version `version`.
///
/// In the example below we define one model with the identifier `id=1` with tow versions `version=1` and `version=2`.
/// - You **must** link the previous version from the new one with `from` option like `#[native_model(id=1, version=2, from=LegacyData)]`.
/// - You **must** define the interoperability between the two versions with implement `From<LegacyData> for Data` and `From<Data> for LegacyData` or implement `TryFrom<LegacyData> for Data` and `TryFrom<Data> for LegacyData`.
/// - You **must** define all models (by calling [`define`](#method.define)) before to call [`migration`](#method.migrate).
/// - You **must** call use the most recent/bigger version as the target version when you call [`migration`](#method.migrate): `migration::<Data>()`.
/// That means you can't call `migration::<LegacyData>()` because `LegacyData` has version `1` and `Data` has version `2`.
///
/// After call `migration::<Data>()` all data of the model `LegacyData` will be migrated to the model `Data`.
///
/// Under the hood, when you call [`migration`](#method.migrate) `native_model` is used to convert the data from the old model to the new model
/// using the `From` or `TryFrom` implementation for each to target the version defined when you call [`migration::<LastVersion>()`](#method.migrate).
///
/// It's advisable to perform all migrations within a **single transaction** to ensure that all migrations are successfully completed.
///
/// # Example
/// ```rust
/// use native_db::*;
/// use native_model::{native_model, Model};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize, Debug)]
/// #[native_model(id=1, version=1)]
/// #[native_db]
/// struct LegacyData {
/// #[primary_key]
/// id: u32,
/// }
///
/// impl From<Data> for LegacyData {
/// fn from(data: Data) -> Self {
/// LegacyData {
/// id: data.id as u32,
/// }
/// }
/// }
///
/// #[derive(Serialize, Deserialize, Debug)]
/// #[native_model(id=1, version=2, from=LegacyData)]
/// #[native_db]
/// struct Data {
/// #[primary_key]
/// id: u64,
/// }
///
/// impl From<LegacyData> for Data {
/// fn from(legacy_data: LegacyData) -> Self {
/// Data {
/// id: legacy_data.id as u64,
/// }
/// }
/// }
///
/// fn main() -> Result<(), db_type::Error> {
/// let mut builder = DatabaseBuilder::new();
/// builder.define::<LegacyData>()?;
/// builder.define::<Data>()?;
/// let db = builder.create_in_memory()?;
///
/// let rw = db.rw_transaction()?;
/// rw.migrate::<Data>()?;
/// // Other migrations if needed..
/// rw.commit()
/// }
/// ```
pub fn migrate<T: Input + Debug>(&self) -> Result<()> {
self.internal.migrate::<T>()
}
}