diff --git a/src/main/kotlin/service/LibraryService.kt b/src/main/kotlin/service/LibraryService.kt index 59cda37..2a1fafd 100644 --- a/src/main/kotlin/service/LibraryService.kt +++ b/src/main/kotlin/service/LibraryService.kt @@ -11,12 +11,11 @@ class LibraryService(private val connection: Connection) { companion object { private const val SELECT_LIBRARY_BY_ID = "SELECT * FROM library WHERE id = ?" private const val SELECT_ALL_LIBRARIES = "SELECT * FROM library" - private const val SELECT_LIBRARY_ALL = "SELECT * FROM library ORDER BY id DESC LIMIT 25" private const val INSERT_LIBRARY = "INSERT INTO library (name, address, is_archived) VALUES (?, ?, ?)" - private const val UPDATE_LIBRARY_BY_ID = "" + private const val UPDATE_LIBRARY_BY_ID = "UPDATE library SET name = ?, address = ? WHERE id = ?" // In the event are "deleted" erroneously, having a flag set instead of actually removing the entry allows // for quick reversal. - private const val ARCHIVE_LIBRARY_BY_ID = "" + private const val ARCHIVE_LIBRARY_BY_ID = "UPDATE library SET is_archived = true WHERE id = ?" } suspend fun create(library: NewLibrary): Long { @@ -64,11 +63,32 @@ class LibraryService(private val connection: Connection) { return libraries } - suspend fun update(library: Library) {} + suspend fun update(library: Library): Library { + val statement = connection.prepareStatement(UPDATE_LIBRARY_BY_ID) + try { + statement.setString(1, library.name) + statement.setString(2, library.address) + statement.setLong(3, library.id) + statement.execute() + return readLibraryById(library.id) + } catch (e: SQLException) { + throw DbElementInsertionException("${e.message}\ncollectionItem: $library\n statement: $statement\n ", e) + } catch (e: IllegalArgumentException) { + throw DbElementInsertionException("${e.message}\ncollectionItem: $library\n statement: $statement\n ", e) + } + } - suspend fun delete(id: String) {} + suspend fun delete(id: Long) { + val statement = connection.prepareStatement(ARCHIVE_LIBRARY_BY_ID) + try { + statement.setLong(1, id) + statement.execute() + } catch (e: SQLException) { + throw DbElementNotFoundException("Could not find Library with id $id") + } + } - fun createLibraryFromResult(resultSet: ResultSet): Library { + private fun createLibraryFromResult(resultSet: ResultSet): Library { try { val id = resultSet.getLong("id") val name = resultSet.getString("name")