1use puerto_nucleo::{ErrorRepositorio, EventoDominio, SobreEvento};
6use sqlx::{PgConnection, PgPool, Postgres, Transaction};
7
8use crate::mapear_error_sqlx;
9
10pub struct TransaccionPostgres {
13 tx: Transaction<'static, Postgres>,
14}
15
16impl TransaccionPostgres {
17 pub async fn begin(pool: &PgPool) -> Result<Self, ErrorRepositorio> {
18 let tx = pool.begin().await.map_err(|err| {
19 tracing::error!(error = %err, "unit_of_work: falló el begin");
20 mapear_error_sqlx(&err)
21 })?;
22 Ok(Self { tx })
23 }
24
25 pub fn tx(&mut self) -> &mut PgConnection {
27 &mut self.tx
28 }
29
30 pub async fn registrar(&mut self, event: &impl EventoDominio) -> Result<(), ErrorRepositorio> {
32 self.registrar_sobre(&SobreEvento::new(event)).await
33 }
34
35 pub async fn registrar_sobre(&mut self, event: &SobreEvento) -> Result<(), ErrorRepositorio> {
37 let headers = serde_json::to_value(&event.cabeceras).map_err(|err| {
38 tracing::error!(error = %err, event_type = %event.tipo_evento, "unit_of_work: las cabeceras no se pueden serializar");
39 ErrorRepositorio::DatosInvalidos
40 })?;
41 sqlx::query(
42 "INSERT INTO outbox \
43 (id, tipo_agregado, id_agregado, tipo_evento, version_esquema, payload, cabeceras, ocurrido_en) \
44 VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
45 )
46 .bind(event.id)
47 .bind(&event.tipo_agregado)
48 .bind(event.id_agregado)
49 .bind(&event.tipo_evento)
50 .bind(i32::from(event.version_esquema))
51 .bind(&event.payload)
52 .bind(headers)
53 .bind(event.ocurrido_en)
54 .execute(&mut *self.tx)
55 .await
56 .map_err(|err| {
57 tracing::error!(error = %err, event_type = %event.tipo_evento, "unit_of_work: falló la inserción en el outbox");
58 mapear_error_sqlx(&err)
59 })?;
60 Ok(())
61 }
62
63 pub async fn commit(self) -> Result<(), ErrorRepositorio> {
64 self.tx.commit().await.map_err(|err| {
65 tracing::error!(error = %err, "unit_of_work: falló el commit");
66 mapear_error_sqlx(&err)
67 })
68 }
69}