2022-05-14 12:35:08 +00:00
|
|
|
use crate::ctx::Context;
|
2024-05-28 10:43:45 +00:00
|
|
|
use crate::dbs::Options;
|
2022-02-06 01:14:56 +00:00
|
|
|
use crate::dbs::Statement;
|
|
|
|
use crate::doc::Document;
|
|
|
|
use crate::err::Error;
|
|
|
|
|
2024-08-15 16:01:02 +00:00
|
|
|
impl Document {
|
2022-02-06 01:14:56 +00:00
|
|
|
pub async fn store(
|
|
|
|
&self,
|
2024-08-15 16:01:02 +00:00
|
|
|
ctx: &Context,
|
2022-03-07 18:11:44 +00:00
|
|
|
opt: &Options,
|
2023-11-20 18:13:34 +00:00
|
|
|
stm: &Statement<'_>,
|
2022-02-06 01:14:56 +00:00
|
|
|
) -> Result<(), Error> {
|
2024-03-18 20:59:39 +00:00
|
|
|
// Check if changed
|
|
|
|
if !self.changed() {
|
2022-04-02 12:25:42 +00:00
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
// Check if the table is a view
|
2024-05-28 10:43:45 +00:00
|
|
|
if self.tb(ctx, opt).await?.drop {
|
2022-04-02 12:25:42 +00:00
|
|
|
return Ok(());
|
|
|
|
}
|
2024-07-17 22:44:05 +00:00
|
|
|
// Get the transaction
|
|
|
|
let txn = ctx.tx();
|
2022-04-02 12:25:42 +00:00
|
|
|
// Get the record id
|
|
|
|
let rid = self.id.as_ref().unwrap();
|
|
|
|
// Store the record data
|
2024-06-11 09:34:21 +00:00
|
|
|
let key = crate::key::thing::new(opt.ns()?, opt.db()?, &rid.tb, &rid.id);
|
2024-07-17 22:44:05 +00:00
|
|
|
// Match the statement type
|
2023-11-20 18:13:34 +00:00
|
|
|
match stm {
|
|
|
|
// This is a CREATE statement so try to insert the key
|
2024-08-21 13:54:58 +00:00
|
|
|
Statement::Create(_) => match txn.put(key, self, opt.version).await {
|
2023-11-20 18:13:34 +00:00
|
|
|
// The key already exists, so return an error
|
2024-07-17 22:44:05 +00:00
|
|
|
Err(Error::TxKeyAlreadyExists) => Err(Error::RecordExists {
|
2023-11-20 18:13:34 +00:00
|
|
|
thing: rid.to_string(),
|
|
|
|
}),
|
|
|
|
// Return any other received error
|
|
|
|
Err(e) => Err(e),
|
|
|
|
// Record creation worked fine
|
|
|
|
Ok(v) => Ok(v),
|
|
|
|
},
|
2024-08-22 22:34:33 +00:00
|
|
|
// INSERT can be versioned
|
|
|
|
Statement::Insert(_) => txn.set(key, self, opt.version).await,
|
2023-11-20 18:13:34 +00:00
|
|
|
// This is not a CREATE statement, so update the key
|
2024-08-22 22:34:33 +00:00
|
|
|
_ => txn.set(key, self, None).await,
|
2023-11-20 18:13:34 +00:00
|
|
|
}?;
|
2022-04-02 12:25:42 +00:00
|
|
|
// Carry on
|
2022-02-06 01:14:56 +00:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|