Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#12048] Create SQL Logic for Get User Actions #12136

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions src/it/java/teammates/it/storage/sqlapi/UsersDbIT.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package teammates.it.storage.sqlapi;

import java.util.UUID;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import teammates.common.datatransfer.InstructorPermissionRole;
import teammates.common.datatransfer.InstructorPrivileges;
import teammates.common.util.Const;
import teammates.common.util.HibernateUtil;
import teammates.it.test.BaseTestCaseWithSqlDatabaseAccess;
import teammates.storage.sqlapi.CoursesDb;
import teammates.storage.sqlapi.UsersDb;
import teammates.storage.sqlentity.Course;
import teammates.storage.sqlentity.Instructor;
import teammates.storage.sqlentity.Student;

/**
* SUT: {@link UsersDb}.
*/
public class UsersDbIT extends BaseTestCaseWithSqlDatabaseAccess {

private final UsersDb usersDb = UsersDb.inst();
private final CoursesDb coursesDb = CoursesDb.inst();

private Course course;
private Instructor instructor;
private Student student;

@BeforeMethod
@Override
public void setUp() throws Exception {
super.setUp();

course = new Course("course-id", "course-name", Const.DEFAULT_TIME_ZONE, "institute");
coursesDb.createCourse(course);

instructor = getTypicalInstructor();
usersDb.createInstructor(instructor);

student = getTypicalStudent();
usersDb.createStudent(student);

HibernateUtil.flushSession();
}

@Test
public void testGetInstructor() {
______TS("success: gets an instructor that already exists");
Instructor actualInstructor = usersDb.getInstructor(instructor.getId());
verifyEquals(instructor, actualInstructor);

______TS("success: gets an instructor that does not exist");
UUID nonExistentId = UUID.fromString("00000000-0000-1000-0000-000000000000");
Instructor nonExistentInstructor = usersDb.getInstructor(nonExistentId);
assertNull(nonExistentInstructor);
}

@Test
public void testGetStudent() {
______TS("success: gets a student that already exists");
Student actualstudent = usersDb.getStudent(student.getId());
verifyEquals(student, actualstudent);

______TS("success: gets a student that does not exist");
UUID nonExistentId = UUID.fromString("00000000-0000-1000-0000-000000000000");
Student nonExistentstudent = usersDb.getStudent(nonExistentId);
assertNull(nonExistentstudent);
}

private Student getTypicalStudent() {
return new Student(course, "student-name", "[email protected]", "comments");
}

private Instructor getTypicalInstructor() {
InstructorPrivileges instructorPrivileges =
new InstructorPrivileges(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER);
InstructorPermissionRole role = InstructorPermissionRole
.getEnum(Const.InstructorPermissionRoleNames.INSTRUCTOR_PERMISSION_ROLE_COOWNER);

return new Instructor(course, "instructor-name", "[email protected]",
false, Const.DEFAULT_DISPLAY_NAME_FOR_INSTRUCTOR, role, instructorPrivileges);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
import teammates.storage.sqlentity.AccountRequest;
import teammates.storage.sqlentity.BaseEntity;
import teammates.storage.sqlentity.Course;
import teammates.storage.sqlentity.Instructor;
import teammates.storage.sqlentity.Notification;
import teammates.storage.sqlentity.Student;
import teammates.storage.sqlentity.UsageStatistics;
import teammates.test.BaseTestCase;

Expand Down Expand Up @@ -88,6 +90,16 @@ protected void verifyEquals(BaseEntity expected, BaseEntity actual) {
UsageStatistics actualUsageStatistics = (UsageStatistics) actual;
equalizeIrrelevantData(expectedUsageStatistics, actualUsageStatistics);
assertEquals(JsonUtils.toJson(expectedUsageStatistics), JsonUtils.toJson(actualUsageStatistics));
} else if (expected instanceof Instructor) {
Instructor expectedInstructor = (Instructor) expected;
Instructor actualInstructor = (Instructor) actual;
equalizeIrrelevantData(expectedInstructor, actualInstructor);
assertEquals(JsonUtils.toJson(expectedInstructor), JsonUtils.toJson(actualInstructor));
} else if (expected instanceof Student) {
Student expectedStudent = (Student) expected;
Student actualStudent = (Student) actual;
equalizeIrrelevantData(expectedStudent, actualStudent);
assertEquals(JsonUtils.toJson(expectedStudent), JsonUtils.toJson(actualStudent));
} else {
fail("Unknown entity");
}
Expand Down Expand Up @@ -138,6 +150,18 @@ private void equalizeIrrelevantData(UsageStatistics expected, UsageStatistics ac
expected.setCreatedAt(actual.getCreatedAt());
}

private void equalizeIrrelevantData(Instructor expected, Instructor actual) {
// Ignore time field as it is stamped at the time of creation in testing
expected.setCreatedAt(actual.getCreatedAt());
expected.setUpdatedAt(actual.getUpdatedAt());
}

private void equalizeIrrelevantData(Student expected, Student actual) {
// Ignore time field as it is stamped at the time of creation in testing
expected.setCreatedAt(actual.getCreatedAt());
expected.setUpdatedAt(actual.getUpdatedAt());
}

/**
* Generates a UUID that is different from the given {@code uuid}.
*/
Expand Down
56 changes: 56 additions & 0 deletions src/main/java/teammates/sqllogic/core/UsersLogic.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package teammates.sqllogic.core;

import java.util.UUID;

import teammates.storage.sqlapi.UsersDb;
import teammates.storage.sqlentity.Instructor;
import teammates.storage.sqlentity.Student;

/**
* Handles operations related to user (instructor & student).
*
* @see User
* @see UsersDb
*/
public final class UsersLogic {

private static final UsersLogic instance = new UsersLogic();

private UsersDb usersDb;

private UsersLogic() {
// prevent initialization
}

public static UsersLogic inst() {
return instance;
}

void initLogicDependencies(UsersDb usersDb) {
this.usersDb = usersDb;
}

/**
* Gets instructor associated with {@code id}.
*
* @param id Id of Instructor.
* @return Returns Instructor if found else null.
*/
public Instructor getInstructor(UUID id) {
assert id != null;

return usersDb.getInstructor(id);
}

/**
* Gets student associated with {@code id}.
*
* @param id Id of Student.
* @return Returns Student if found else null.
*/
public Student getStudent(UUID id) {
assert id != null;

return usersDb.getStudent(id);
}
}
35 changes: 18 additions & 17 deletions src/main/java/teammates/storage/sqlapi/UsersDb.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
* @see User
*/
public final class UsersDb extends EntitiesDb<User> {

private static final UsersDb instance = new UsersDb();

private UsersDb() {
Expand All @@ -51,7 +52,8 @@ public Instructor createInstructor(Instructor instructor)
String email = instructor.getEmail();

if (hasExistingInstructor(courseId, email)) {
throw new EntityAlreadyExistsException(String.format(ERROR_CREATE_ENTITY_ALREADY_EXISTS, instructor.toString()));
throw new EntityAlreadyExistsException(
String.format(ERROR_CREATE_ENTITY_ALREADY_EXISTS, instructor.toString()));
}

persist(instructor);
Expand All @@ -73,7 +75,8 @@ public Student createStudent(Student student)
String email = student.getEmail();

if (hasExistingStudent(courseId, email)) {
throw new EntityAlreadyExistsException(String.format(ERROR_CREATE_ENTITY_ALREADY_EXISTS, student.toString()));
throw new EntityAlreadyExistsException(
String.format(ERROR_CREATE_ENTITY_ALREADY_EXISTS, student.toString()));
}

persist(student);
Expand All @@ -83,19 +86,19 @@ public Student createStudent(Student student)
/**
* Gets an instructor by its {@code id}.
*/
public Instructor getInstructor(Integer id) {
public Instructor getInstructor(UUID id) {
assert id != null;

return HibernateUtil.getCurrentSession().get(Instructor.class, id);
return HibernateUtil.get(Instructor.class, id);
}

/**
* Gets a student by its {@code id}.
*/
public Student getStudent(Integer id) {
public Student getStudent(UUID id) {
assert id != null;

return HibernateUtil.getCurrentSession().get(Student.class, id);
return HibernateUtil.get(Student.class, id);
}

/**
Expand Down Expand Up @@ -160,33 +163,31 @@ public long getNumStudentsByTimeRange(Instant startTime, Instant endTime) {
/**
* Checks if an instructor exists by its {@code courseId} and {@code email}.
*/
private <T extends User> boolean hasExistingInstructor(String courseId, String email) {
private boolean hasExistingInstructor(String courseId, String email) {
Session session = HibernateUtil.getCurrentSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Instructor> cr = cb.createQuery(Instructor.class);
Root<Instructor> instructorRoot = cr.from(Instructor.class);

cr.select(instructorRoot.get("id"))
.where(cb.and(
cb.equal(instructorRoot.get("courseId"), courseId),
cb.equal(instructorRoot.get("email"), email)));
cr.select(instructorRoot).where(cb.and(
cb.equal(instructorRoot.get("courseId"), courseId),
cb.equal(instructorRoot.get("email"), email)));

return session.createQuery(cr).getSingleResultOrNull() != null;
}

/**
* Checks if a student exists by its {@code courseId} and {@code email}.
*/
private <T extends User> boolean hasExistingStudent(String courseId, String email) {
private boolean hasExistingStudent(String courseId, String email) {
Session session = HibernateUtil.getCurrentSession();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Student> cr = cb.createQuery(Student.class);
Root<Student> studentRoot = cr.from(Student.class);

cr.select(studentRoot.get("id"))
.where(cb.and(
cb.equal(studentRoot.get("courseId"), courseId),
cb.equal(studentRoot.get("email"), email)));
cr.select(studentRoot).where(cb.and(
cb.equal(studentRoot.get("courseId"), courseId),
cb.equal(studentRoot.get("email"), email)));

return session.createQuery(cr).getSingleResultOrNull() != null;
}
Expand All @@ -197,6 +198,6 @@ private <T extends User> boolean hasExistingStudent(String courseId, String emai
private boolean hasExistingUser(UUID id) {
assert id != null;

return HibernateUtil.getCurrentSession().get(User.class, id) != null;
return HibernateUtil.get(User.class, id) != null;
}
}
4 changes: 2 additions & 2 deletions src/main/java/teammates/storage/sqlentity/BaseEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ public Duration convertToEntityAttribute(Long minutes) {
@Converter
public static class JsonConverter<T> implements AttributeConverter<T, String> {
@Override
public String convertToDatabaseColumn(T questionDetails) {
return JsonUtils.toJson(questionDetails);
public String convertToDatabaseColumn(T entity) {
return JsonUtils.toJson(entity);
}

@Override
Expand Down
22 changes: 18 additions & 4 deletions src/main/java/teammates/storage/sqlentity/Instructor.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@

import teammates.common.datatransfer.InstructorPermissionRole;
import teammates.common.datatransfer.InstructorPrivileges;
import teammates.common.datatransfer.InstructorPrivilegesLegacy;
import teammates.common.util.FieldValidator;
import teammates.common.util.JsonUtils;
import teammates.common.util.SanitizationHelper;

import jakarta.persistence.Column;
Expand All @@ -32,17 +34,17 @@ public class Instructor extends User {
@Enumerated(EnumType.STRING)
private InstructorPermissionRole role;

@Column(nullable = false)
@Column(nullable = false, columnDefinition = "TEXT")
@Convert(converter = InstructorPrivilegesConverter.class)
private InstructorPrivileges instructorPrivileges;

protected Instructor() {
// required by Hibernate
}

public Instructor(Course course, Team team, String name, String email, boolean isDisplayedToStudents,
public Instructor(Course course, String name, String email, boolean isDisplayedToStudents,
String displayName, InstructorPermissionRole role, InstructorPrivileges instructorPrivileges) {
super(course, team, name, email);
super(course, name, email);
this.setDisplayedToStudents(isDisplayedToStudents);
this.setDisplayName(displayName);
this.setRole(role);
Expand Down Expand Up @@ -96,7 +98,7 @@ public List<String> getInvalidityInfo() {
addNonEmptyError(FieldValidator.getInvalidityInfoForPersonName(super.getName()), errors);
addNonEmptyError(FieldValidator.getInvalidityInfoForEmail(super.getEmail()), errors);
addNonEmptyError(FieldValidator.getInvalidityInfoForPersonName(displayName), errors);
addNonEmptyError(FieldValidator.getInvalidityInfoForRole(role.name()), errors);
addNonEmptyError(FieldValidator.getInvalidityInfoForRole(role.getRoleName()), errors);

return errors;
}
Expand All @@ -107,5 +109,17 @@ public List<String> getInvalidityInfo() {
@Converter
public static class InstructorPrivilegesConverter
extends JsonConverter<InstructorPrivileges> {

@Override
public String convertToDatabaseColumn(InstructorPrivileges instructorPrivileges) {
return JsonUtils.toJson(instructorPrivileges.toLegacyFormat(), InstructorPrivilegesLegacy.class);
}

@Override
public InstructorPrivileges convertToEntityAttribute(String instructorPriviledgesAsString) {
InstructorPrivilegesLegacy privilegesLegacy =
JsonUtils.fromJson(instructorPriviledgesAsString, InstructorPrivilegesLegacy.class);
return new InstructorPrivileges(privilegesLegacy);
}
}
}
4 changes: 2 additions & 2 deletions src/main/java/teammates/storage/sqlentity/Student.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ protected Student() {
// required by Hibernate
}

public Student(Course course, Team team, String name, String email, String comments) {
super(course, team, name, email);
public Student(Course course, String name, String email, String comments) {
super(course, name, email);
this.setComments(comments);
}

Expand Down
Loading