How to use sql unique index to restrict the number of `unfinalized` records

Viewed 24

I have 3 entities in SQL: User, Test and UserTestAttempt.

class User {
  Long id;
}

class Test {
  Long id;
}

class UserTestAttempt {
  Long id;
  Long userId;
  Long testId;
  StatusEnum status; // REGISTERED, IN_PROGRESS, PASSED, FAILED
}

A User can make a UserTestAttempt to take a Test. However, when status is REGISTERED or IN_PROGRESS, no new UserTestAttempt can be created with identical userId and testId. After status turns into PASSED or FAILED, User can create new UserTestAttempt to retake Test.

Is there an easy way to achieve this through SQL unique index? Or I have to implement it in pure code?

0 Answers
Related