use async_trait::async_trait;
use fraiseql_error::{FraiseQLError, Result};
use super::{BatchRowGate, ChangeLogWrite, DatabaseAdapter, MutationRowGate};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WriteMode {
Commit,
DryRun,
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct DerivedCascade<'a> {
pub max_entities: i32,
pub views: &'a [(&'a str, &'a str)],
}
impl<'a> DerivedCascade<'a> {
#[must_use]
pub const fn new(max_entities: i32, views: &'a [(&'a str, &'a str)]) -> Self {
Self {
max_entities,
views,
}
}
}
pub const DERIVED_CASCADE_KEY: &str = "__fraiseql_derived_cascade";
pub const CHANGED_ROWS_KEY: &str = "__fraiseql_changed_rows";
pub type ChangedCollections =
std::collections::BTreeMap<String, std::collections::BTreeSet<String>>;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChangedRows {
pub rows: std::collections::BTreeMap<String, std::collections::BTreeSet<String>>,
pub types: std::collections::BTreeSet<String>,
pub collections: Option<ChangedCollections>,
}
impl Default for ChangedRows {
fn default() -> Self {
Self {
rows: std::collections::BTreeMap::new(),
types: std::collections::BTreeSet::new(),
collections: Some(ChangedCollections::new()),
}
}
}
impl ChangedRows {
#[must_use]
pub fn from_report(report: &serde_json::Value) -> Option<Self> {
let report = report.as_object()?;
let mut changed = Self {
collections: None,
..Self::default()
};
for arm in ["updated", "deleted"] {
let entries = match report.get(arm) {
None => continue,
Some(entries) => entries.as_array()?,
};
for entry in entries {
let typename = entry.get("__typename")?.as_str()?;
match entry.get("id") {
Some(serde_json::Value::String(id)) => {
changed.rows.entry(typename.to_string()).or_default().insert(id.clone());
},
Some(serde_json::Value::Number(id)) => {
changed
.rows
.entry(typename.to_string())
.or_default()
.insert(id.to_string());
},
_ => {
changed.types.insert(typename.to_string());
},
}
}
}
if let Some(types) = report.get("invalidated_types") {
for typename in types.as_array()? {
changed.types.insert(typename.as_str()?.to_string());
}
}
if let Some(collections) = report.get("collections") {
let mut read = ChangedCollections::new();
let mut readable = true;
for (key, parents) in collections.as_object()? {
let Some((child_type, _)) = key
.split_once('.')
.filter(|(child_type, column)| !child_type.is_empty() && !column.is_empty())
else {
readable = false;
continue;
};
for parent in parents.as_array()? {
match parent {
serde_json::Value::String(id) => {
read.entry(key.clone()).or_default().insert(id.clone());
},
serde_json::Value::Number(id) => {
read.entry(key.clone()).or_default().insert(id.to_string());
},
_ => {
changed.types.insert(child_type.to_string());
},
}
}
}
changed.collections = readable.then_some(read);
}
Some(changed)
}
pub fn absorb(&mut self, other: Self) {
for (typename, ids) in other.rows {
self.rows.entry(typename).or_default().extend(ids);
}
self.types.extend(other.types);
match (self.collections.as_mut(), other.collections) {
(Some(mine), Some(theirs)) => {
for (key, parents) in theirs {
mine.entry(key).or_default().extend(parents);
}
},
_ => self.collections = None,
}
}
pub fn type_names(&self) -> impl Iterator<Item = &str> {
self.rows.keys().chain(&self.types).map(String::as_str)
}
}
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct WriteRequest<'a> {
pub function: &'a str,
pub args: &'a [serde_json::Value],
pub session_vars: &'a [(&'a str, &'a str)],
pub changelog: Option<&'a ChangeLogWrite<'a>>,
pub mode: WriteMode,
pub derived_cascade: Option<&'a DerivedCascade<'a>>,
pub report_changes: Option<i32>,
pub decimals: Option<&'a super::WriteDecimals>,
}
impl<'a> WriteRequest<'a> {
#[must_use]
pub const fn new(function: &'a str, args: &'a [serde_json::Value]) -> Self {
Self {
function,
args,
session_vars: &[],
changelog: None,
mode: WriteMode::Commit,
derived_cascade: None,
report_changes: None,
decimals: None,
}
}
#[must_use]
pub const fn with_decimals(mut self, decimals: Option<&'a super::WriteDecimals>) -> Self {
self.decimals = decimals;
self
}
#[must_use]
pub const fn with_changes_reported(mut self, max_entities: Option<i32>) -> Self {
self.report_changes = max_entities;
self
}
#[must_use]
pub const fn with_derived_cascade(
mut self,
derived_cascade: Option<&'a DerivedCascade<'a>>,
) -> Self {
self.derived_cascade = derived_cascade;
self
}
#[must_use]
pub const fn with_session_vars(mut self, session_vars: &'a [(&'a str, &'a str)]) -> Self {
self.session_vars = session_vars;
self
}
#[must_use]
pub const fn with_changelog(mut self, changelog: Option<&'a ChangeLogWrite<'a>>) -> Self {
self.changelog = changelog;
self
}
#[must_use]
pub const fn with_mode(mut self, mode: WriteMode) -> Self {
self.mode = mode;
self
}
}
#[async_trait]
pub trait Writer: DatabaseAdapter {
async fn execute_write(
&self,
request: &WriteRequest<'_>,
gate: MutationRowGate<'_>,
) -> Result<Vec<std::collections::HashMap<String, serde_json::Value>>>;
async fn execute_writes(
&self,
_requests: &[WriteRequest<'_>],
_gate: BatchRowGate<'_>,
) -> Result<Vec<Vec<std::collections::HashMap<String, serde_json::Value>>>> {
Err(FraiseQLError::Unsupported {
message: "this database adapter cannot run a batch of writes in one transaction"
.to_string(),
})
}
async fn bump_fact_table_versions(&self, _tables: &[String]) -> Result<()> {
Ok(())
}
}