surrealdb_sql/statements/
insert.rsuse crate::ctx::Context;
use crate::dbs::{Iterable, Iterator, Options, Statement, Transaction};
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::{Data, Output, Timeout, Value};
use derive::Store;
use revision::revisioned;
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[revisioned(revision = 1)]
pub struct InsertStatement {
pub into: Value,
pub data: Data,
pub ignore: bool,
pub update: Option<Data>,
pub output: Option<Output>,
pub timeout: Option<Timeout>,
pub parallel: bool,
}
impl InsertStatement {
pub(crate) fn writeable(&self) -> bool {
true
}
pub(crate) async fn compute(
&self,
ctx: &Context<'_>,
opt: &Options,
txn: &Transaction,
doc: Option<&CursorDoc<'_>>,
) -> Result<Value, Error> {
opt.valid_for_db()?;
let mut i = Iterator::new();
let opt = &opt.new_with_futures(false).with_projections(false);
match self.into.compute(ctx, opt, txn, doc).await? {
Value::Table(into) => match &self.data {
Data::ValuesExpression(v) => {
for v in v {
let mut o = Value::base();
for (k, v) in v.iter() {
let v = v.compute(ctx, opt, txn, None).await?;
o.set(ctx, opt, txn, k, v).await?;
}
let id = o.rid().generate(&into, true)?;
i.ingest(Iterable::Mergeable(id, o));
}
}
Data::SingleExpression(v) => {
let v = v.compute(ctx, opt, txn, doc).await?;
match v {
Value::Array(v) => {
for v in v {
let id = v.rid().generate(&into, true)?;
i.ingest(Iterable::Mergeable(id, v));
}
}
Value::Object(_) => {
let id = v.rid().generate(&into, true)?;
i.ingest(Iterable::Mergeable(id, v));
}
v => {
return Err(Error::InsertStatement {
value: v.to_string(),
})
}
}
}
_ => unreachable!(),
},
v => {
return Err(Error::InsertStatement {
value: v.to_string(),
})
}
}
let stm = Statement::from(self);
i.output(ctx, opt, txn, &stm).await
}
}
impl fmt::Display for InsertStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("INSERT")?;
if self.ignore {
f.write_str(" IGNORE")?
}
write!(f, " INTO {} {}", self.into, self.data)?;
if let Some(ref v) = self.update {
write!(f, " {v}")?
}
if let Some(ref v) = self.output {
write!(f, " {v}")?
}
if let Some(ref v) = self.timeout {
write!(f, " {v}")?
}
if self.parallel {
f.write_str(" PARALLEL")?
}
Ok(())
}
}