Improve sql

This commit is contained in:
Hubert Van De Walle 2020-08-17 16:01:15 +02:00
parent 48897c8b90
commit 56e742e39f
3 changed files with 13 additions and 12 deletions

View File

@ -11,8 +11,13 @@ import java.sql.SQLIntegrityConstraintViolationException
internal class UserRepositoryImpl(private val db: Database) : UserRepository {
override fun create(user: User): PersistedUser? {
return try {
db.useTransaction { db.users.add(user.toEntity()) }
find(user.username)
db.useTransaction {
val id = db.insertAndGenerateKey(Users) {
it.username to user.username
it.password to user.password
} as Int
PersistedUser(user.username, user.password, id)
}
} catch (e: SQLIntegrityConstraintViolationException) {
null
}
@ -22,5 +27,5 @@ internal class UserRepositoryImpl(private val db: Database) : UserRepository {
override fun find(id: Int) = db.users.find { it.id eq id }?.toPersistedUser()
override fun exists(username: String) = db.users.any { it.username eq username }
override fun exists(id: Int) = db.users.any { it.id eq id }
override fun delete(id: Int) = db.useTransaction { db.users.find { it.id eq id }?.delete() == 1 }
override fun delete(id: Int) = db.useTransaction { db.delete(Users) { it.id eq id } == 1 }
}

View File

@ -26,14 +26,6 @@ internal interface UserEntity : Entity<UserEntity> {
internal fun UserEntity.toPersistedUser() = PersistedUser(username, password, id)
internal fun PersistedUser.toEntity(): UserEntity {
val user = this
return UserEntity {
this.username = user.username
this.password = user.password
}.apply { this["id"] = user.id }
}
internal fun User.toEntity(): UserEntity {
val user = this
return UserEntity {

View File

@ -63,7 +63,11 @@ internal class UserRepositoryImplTest {
@Test
fun `insert user`() {
val user = User("username", "test")
assertThat(userRepo.create(user)).isNotNull
assertThat(userRepo.create(user))
.isNotNull
.hasFieldOrPropertyWithValue("username", user.username)
.hasFieldOrPropertyWithValue("password", user.password)
assertThat(db.users.find { it.username eq user.username }).isNotNull
assertThat(db.users.toList()).hasSize(1)
assertThat(userRepo.create(user)).isNull()