Create a general update function for Slick 3.1.1

I have this fucntion:

 def updateInvoiceAdminStatusField(id: Int, newAdminStatus: AdminStatus): Future[Int] = {


    db.run {

      val adminStatus: Query[Rep[AdminStatus], AdminStatus, Seq] = InvoicesTable.filter(invoice => invoice.id === id).map(invoice => invoice.status)

      adminStatus.update(newAdminStatus)
    }
  }

I thought to make it general:

   def updateInvoiceField[T](id: Int, fieldExtractor: (Invoices) => Rep[T], newValue: T): Future[Int] = {

    db.run {

      val adminStatus = InvoicesTable.filter(invoice => invoice.id === id).map(invoice => {

        fieldExtractor(invoice)
      })

      adminStatus.update(newValue)
    }
  }

But this does not compile. Can anyone help?

+4
source share
1 answer

This is almost good. With minor changes, as shown below, it should work:

// I added below T: ColumnType
def updateInvoiceField[T: ColumnType](id: Int, fieldExtractor: (Invoices) => Rep[T], newValue: T): Future[Int] = {

  db.run {
      val adminStatus = InvoicesTable.filter(invoice => invoice.id === id).map(invoice => {
          fieldExtractor(invoice)
      })

      adminStatus.update(newValue)
  }
}

Notice, I added this one : ColumnType, which basically means that you should have a proper implicit scope - in particular, one that will convert T=> ColumnType[T]. This is simply because it Tcan be anything else, but Slicknot be able to understand how to transform it.

, , String, Int .., , , ( api /). MappedColumnType . ( ):

implicit def columnType[T]: BaseColumnType[Id[T]] =
    MappedColumnType.base[Id[T], Long](toLong, fromLong)

private def fromLong[T](dbId: Long): Id[T] = Id(dbId)

private def toLong[T](id: Id[T]): Long = id.value
+2

Source: https://habr.com/ru/post/1665079/


All Articles