資料儲存層打算試試SurrealDB,還滿酷的一個資料庫的實作,核心是使用rust編寫的,同時支援關聯式,文件式,圖式等不同的資料庫型態。
先寫放置事件的repository:
pub struct SurrealEventRepository {
pub db: Surreal<Db>,
}
impl From<surrealdb::Error> for PersistenceError {
fn from(err: surrealdb::Error) -> Self {
Self::UnknownError(Box::new(err))
}
}
實作PersistedEventRepository
trait
#[async_trait]
impl PersistedEventRepository for SurrealEventRepository {
async fn get_events<A: Aggregate>(&self, aggregate_id: &str) -> Result<Vec<SerializedEvent>, PersistenceError> {
let result = self.db
.query("SELECT * FROM events WHERE aggregate_id = $id")
.bind(("id", aggregate_id))
.await?
.take(0)?;
Ok(result)
}
async fn get_last_events<A: Aggregate>(&self, aggregate_id: &str, last_sequence: usize) -> Result<Vec<SerializedEvent>, PersistenceError> {
let result = self.db
.query("SELECT * FROM events WHERE aggregate_id = $id AND sequence > $last_sequence")
.bind(("id", aggregate_id))
.await?
.take(0)?;
Ok(result)
}
async fn get_snapshot<A: Aggregate>(&self, aggregate_id: &str) -> Result<Option<SerializedSnapshot>, PersistenceError> {
todo!()
}
async fn persist<A: Aggregate>(&self, events: &[SerializedEvent], snapshot_update: Option<(String, Value, usize)>) -> Result<(), PersistenceError> {
let event = events.first().unwrap();
let s :surrealdb::method::Content<'_, Db, &SerializedEvent, Vec<SerializedEvent>> = self.db
.create("events")
.content(event)
.await?;
Ok(())
}
async fn stream_events<A: Aggregate>(&self, aggregate_id: &str) -> Result<ReplayStream, PersistenceError> {
todo!()
}
async fn stream_all_events<A: Aggregate>(&self) -> Result<ReplayStream, PersistenceError> {
todo!()
}
}