ホーム 全セッション S06

SQLite と in-memory の実装の比較

発展 1 / 1 目安 時間外

ページ一覧

あとで読む: examinationStartedStore の2つの実装を比較して、保存と競合の扱いの違いを確認します。

examples/session-06-solution の examinationStartedStore の2つの実装を、左の SQLite と右の in-memory で比較します。

SQLite と in-memory の実装の比較

SQLite と in-memory の違い

  1. SQLite は、database.transaction に渡した関数の中で saveState と appendAudit を呼びます。関数が例外を投げずに完了すると、transaction が確定し、状態と監査記録が同時に残ります。in-memory は、新しい Map と配列 nextEvents を作り、appointments と events を続けて置き換えます。
  2. SQLite は、transaction の中で取得した current から Appointment.startExamination を再度実行し、作り直した committedEvent の状態を保存します。ユースケースの取得後に reason などが変更されていても、変更後の値を古い event の値で上書きしないためです。in-memory は、渡された event の aggregateState をそのまま保存し、event も nextEvents に追加します。
  3. 予約が存在しないとき、SQLite は存在しない場合と CheckedIn ではない場合を同じ条件で判定し、どちらも AppointmentConflict を Err で返します。in-memory は存在しない場合に Error を投げ、reject にします。
SQLite examples/session-06-solution/src/adaptor/secondary/sqlite/examinationStartedStore.ts:149, 163-166
database.transaction((transaction) => {
  …
  saveState(transaction, committedEvent.aggregateState);
  appendAudit(transaction, committedEvent);
  return ok(undefined);
});
SQLite examples/session-06-solution/src/adaptor/secondary/sqlite/examinationStartedStore.ts:150, 158-163
const current = findInTransaction(transaction, event.appointmentId);
…
const committedEvent = Appointment.startExamination({
  eventId: event.eventId,
  occurredAt: event.occurredAt,
})(current, event.aggregateState.veterinarianId);

saveState(transaction, committedEvent.aggregateState);
SQLite examples/session-06-solution/src/adaptor/secondary/sqlite/examinationStartedStore.ts:150-156
const current = findInTransaction(transaction, event.appointmentId);
if (current === undefined || current.kind !== "CheckedIn") {
  return err({
    kind: "AppointmentConflict",
    appointmentId: event.appointmentId,
  } as const);
}
in-memory examples/session-06-solution/src/adaptor/secondary/inMemory/inMemoryExaminationStartedStore.ts:59-66
const nextAppointments = new Map(appointments);
nextAppointments.set(event.appointmentId, event.aggregateState);
const nextEvents = [...events, event];

appointments = nextAppointments;
events = nextEvents;

return ok(undefined);
in-memory examples/session-06-solution/src/adaptor/secondary/inMemory/inMemoryExaminationStartedStore.ts:60-61
nextAppointments.set(event.appointmentId, event.aggregateState);
const nextEvents = [...events, event];
in-memory examples/session-06-solution/src/adaptor/secondary/inMemory/inMemoryExaminationStartedStore.ts:48-57
const currentAppointment = appointments.get(event.appointmentId);
if (currentAppointment === undefined) {
  throw new Error(`Appointment missing at commit: ${event.appointmentId}`);
}
if (currentAppointment.kind !== "CheckedIn") {
  return err({
    kind: "AppointmentConflict",
    appointmentId: event.appointmentId,
  } as const);
}

fake である in-memory を使うテストでは、SQLite が予約の欠落を Err で返す動作を確認できません。