/
sqlite_issue_repository.rs
329 lines (292 loc) · 10.5 KB
/
sqlite_issue_repository.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
use std::{
fs,
path::{Path, PathBuf},
str::FromStr,
};
use async_trait::async_trait;
use domain::{
aggregate::{IssueAggregate, IssueAggregateEvent},
IssueId,
};
use sqlx::{
any::{AnyArguments, AnyConnectOptions, AnyRow},
migrate::Migrator,
query::Query,
sqlite::{SqliteConnectOptions, SqliteJournalMode},
Any, AnyPool, FromRow, Row, Transaction,
};
use use_case::{IssueRepository, RepositoryError};
use crate::{
adapter::sqlite::event_store::{AggregateVersion, Event},
event_dto::EventDto,
SqliteQueryHandler,
};
use super::{
command_migration_source::CommandMigrationSource,
event_store::{self, AggregateId},
};
#[derive(Debug)]
pub struct SqliteIssueRepository {
pool: AnyPool,
// update query db
query_handler: SqliteQueryHandler,
}
#[derive(Debug)]
struct IssueIdRow {
issue_number: i64,
aggregate_id: String,
}
impl IssueIdRow {
fn issue_id(&self) -> IssueId {
IssueId::from_str(self.issue_number.to_string().as_str()).unwrap()
}
fn aggregate_id(&self) -> AggregateId {
AggregateId::from_str(self.aggregate_id.as_str()).unwrap()
}
}
impl<'r> FromRow<'r, AnyRow> for IssueIdRow {
fn from_row(row: &'r AnyRow) -> Result<Self, sqlx::Error> {
Ok(Self {
issue_number: row.get("issue_number"),
aggregate_id: row.get("aggregate_id"),
})
}
}
impl SqliteIssueRepository {
async fn connection(path: &Path) -> Result<AnyPool, RepositoryError> {
let options = SqliteConnectOptions::from_str(&format!(
"sqlite:{}?mode=rwc",
path.to_str().ok_or(RepositoryError::IO)?
))
.map_err(|_| RepositoryError::IO)?
.journal_mode(SqliteJournalMode::Delete);
let options = AnyConnectOptions::from(options);
let pool = AnyPool::connect_with(options)
.await
.map_err(|_| RepositoryError::IO)?;
Ok(pool)
}
pub async fn new(data_dir: PathBuf) -> Result<Self, RepositoryError> {
if !data_dir.exists() {
fs::create_dir_all(data_dir.as_path()).map_err(|_| RepositoryError::IO)?;
}
let pool = Self::connection(data_dir.join("command.sqlite").as_path())
.await
.map_err(|_| RepositoryError::IO)?;
let query_handler = SqliteQueryHandler::new(data_dir.as_path())
.await
.map_err(|_| RepositoryError::IO)?;
let migrator = Migrator::new(CommandMigrationSource::default())
.await
.map_err(|_| RepositoryError::IO)?;
migrator.run(&pool).await.map_err(|_| RepositoryError::IO)?;
Ok(Self {
pool,
query_handler,
})
}
async fn find_aggregate_id_by_issue_id(
&self,
transaction: &mut Transaction<'_, Any>,
issue_id: &IssueId,
) -> Result<Option<AggregateId>, RepositoryError> {
let issue_id_row: Option<IssueIdRow> = sqlx::query_as(include_str!(
"../../../sql/command/select_issue_id_by_issue_id.sql"
))
.bind(
i64::try_from(usize::from(issue_id.issue_number())).map_err(|_| {
RepositoryError::Unknown("Failed to convert issue_number to i64".to_string())
})?,
)
.fetch_optional(&mut *transaction)
.await
.map_err(|e| RepositoryError::Unknown(e.to_string()))?;
Ok(issue_id_row.map(|row| row.aggregate_id()))
}
async fn find_max_issue_id(
&self,
transaction: &mut Transaction<'_, Any>,
) -> Result<Option<IssueId>, RepositoryError> {
let issue_id_row: Option<IssueIdRow> =
sqlx::query_as(include_str!("../../../sql/command/select_max_issue_id.sql"))
.fetch_optional(transaction)
.await
.map_err(|_| RepositoryError::IO)?;
Ok(issue_id_row.map(|row| row.issue_id()))
}
async fn insert_issue_id(
&self,
transaction: &mut Transaction<'_, Any>,
issue_id: &IssueId,
aggregate_id: AggregateId,
) -> Result<(), RepositoryError> {
let query: Query<Any, AnyArguments> =
sqlx::query(include_str!("../../../sql/command/insert_issue_id.sql"))
.bind(
i64::try_from(usize::from(issue_id.issue_number())).map_err(|_| {
RepositoryError::Unknown(
"Failed to convert issue_number to i64".to_string(),
)
})?,
)
.bind(aggregate_id.to_string());
let result = query
.execute(transaction)
.await
.map_err(|_| RepositoryError::IO)?;
if result.rows_affected() != 1 {
return Err(RepositoryError::IO);
}
Ok(())
}
}
#[async_trait]
impl IssueRepository for SqliteIssueRepository {
async fn find_by_id(
&self,
issue_id: &IssueId,
) -> Result<Option<IssueAggregate>, RepositoryError> {
let mut transaction = self.pool.begin().await.map_err(|_| RepositoryError::IO)?;
match self
.find_aggregate_id_by_issue_id(&mut transaction, issue_id)
.await?
{
Some(aggregate_id) => {
let events =
event_store::find_events_by_aggregate_id(&mut transaction, aggregate_id)
.await
.map_err(|_| RepositoryError::IO)?;
let mut issue_aggregate_events = vec![];
for event in events {
let dto = serde_json::from_str::<'_, EventDto>(event.data.as_str())
.map_err(|_| RepositoryError::IO)?;
// TODO: check dto.version and aggregate_id
issue_aggregate_events
.push(IssueAggregateEvent::try_from(dto).map_err(|_| RepositoryError::IO)?);
}
IssueAggregate::from_events(&issue_aggregate_events)
.map(Some)
.map_err(|_| RepositoryError::IO)
}
None => Ok(None),
}
}
async fn last_created(&self) -> Result<Option<IssueAggregate>, RepositoryError> {
let mut transaction = self.pool.begin().await.map_err(|_| RepositoryError::IO)?;
Ok(match self.find_max_issue_id(&mut transaction).await? {
Some(issue_id) => self.find_by_id(&issue_id).await?,
None => None,
})
}
async fn save(&self, event: IssueAggregateEvent) -> Result<(), RepositoryError> {
let mut transaction = self.pool.begin().await.map_err(|_| RepositoryError::IO)?;
let issue_id = event.issue_id().clone();
if let Some(aggregate_id) = self
.find_aggregate_id_by_issue_id(&mut transaction, &issue_id)
.await?
{
// update
let version = event.version();
event_store::save(
&mut transaction,
version
.prev()
.map(|version| {
u32::try_from(u64::from(version))
.map(AggregateVersion::from)
.map_err(|_| RepositoryError::IO)
})
.transpose()?,
Event {
aggregate_id,
data: serde_json::to_string(&EventDto::from(event))
.map_err(|_| RepositoryError::IO)?,
version: AggregateVersion::from(
u32::try_from(u64::from(version)).map_err(|_| RepositoryError::IO)?,
),
},
)
.await
.map_err(|_| RepositoryError::IO)?;
} else {
// create
let aggregate_id = AggregateId::generate();
let version = event.version();
event_store::save(
&mut transaction,
None,
Event {
aggregate_id,
data: serde_json::to_string(&EventDto::from(event))
.map_err(|_| RepositoryError::IO)?,
version: AggregateVersion::from(
u32::try_from(u64::from(version)).map_err(|_| RepositoryError::IO)?,
),
},
)
.await
.map_err(|_| RepositoryError::IO)?;
self.insert_issue_id(&mut transaction, &issue_id, aggregate_id)
.await?;
}
transaction
.commit()
.await
.map_err(|_| RepositoryError::IO)?;
{
// update query db
let issue = self
.find_by_id(&issue_id)
.await?
.ok_or(RepositoryError::IO)?;
self.query_handler
.save_issue(issue)
.await
.map_err(|_| RepositoryError::IO)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use domain::aggregate::{
IssueAggregateCommand, IssueAggregateCreateIssue, IssueAggregateFinishIssue,
};
use limited_date_time::Instant;
use tempfile::tempdir;
use super::*;
#[tokio::test]
async fn test() -> anyhow::Result<()> {
let temp_dir = tempdir()?;
let sqlite_path = temp_dir.path().join("its");
let issue_repository = SqliteIssueRepository::new(sqlite_path).await?;
// create
let (created, created_event) = IssueAggregate::transaction(IssueAggregateCommand::Create(
IssueAggregateCreateIssue {
issue_number: "123".parse()?,
issue_title: "title".parse()?,
issue_due: Some("2021-02-03T04:05:06Z".parse()?),
at: Instant::now(),
},
))?;
issue_repository.save(created_event).await?;
// last_created
let last_created = issue_repository.last_created().await?;
assert_eq!(Some(created.clone()), last_created);
// find_by_id
let found = issue_repository.find_by_id(created.id()).await?;
assert_eq!(Some(created), found);
let found = found.ok_or(anyhow::anyhow!("found is not Some"))?;
// update
let (updated, updated_event) = IssueAggregate::transaction(IssueAggregateCommand::Finish(
IssueAggregateFinishIssue {
issue: found,
at: Instant::now(),
},
))?;
issue_repository.save(updated_event).await?;
let found = issue_repository.find_by_id(updated.id()).await?;
assert_eq!(Some(updated), found);
Ok(())
}
}