2017-02-07 24 views
6

Mam poniższy scenariusz i staram się użyć zręcznych działań DBIO, aby to osiągnąć.Postępuj zgodnie z błędem działania czyszczenia w prostych działaniach dbio

Execute a batch Insert operation. On success, return the inserted result On failure, 
      -> if the failure is due to duplicate value in a particular column, then remove the duplicates from the list, and try batch insert again. If the second batch insert is successful, return a successful future with the second inserted list, else the failed future of the 2nd batch insert. 
      -> if the failure is due to something else, then throw that exception 

Dla powyższego scenariusza próbowałem użyć akcji cleanUp. Ale nie wiem, jak zwrócić wyniki cleanUp, jeśli działanie główne nie powiedzie się.

W jaki sposób mogę osiągnąć moje wymaganie za pomocą działań DBIO Obsługa błędów?

def insertBatchAndReturnQuery(rowList: List[E]): FixedSqlAction[Seq[E], NoStream, Write] = { 
    query returning query ++= rowList 
} 


def insert(entities: List[E]): Future[Seq[E]] = { 
    val q = insertBatchAndReturnQuery(entities).cleanUp { 
     case Some(ex) => ex match { 
     case b: PSQLException => { 
      if (b.getSQLState.equals("23505")) { 
      //unique key exception, handle this by removing the duplicate entries from the list 
      ??? 
      } else { 
      throw new Exception("some database exception") 
      } 
     } 
     } 
     case None => insertBatchAndReturnQuery(Nil) 
    } 
    db.run(q) 
    } 

Tutaj zapytanie jest TableQuery [t].

Slick wersja: 3.2.0-M2

Odpowiedz

0

można zobaczyć z podpisem dla cleanUp że powraca akcję o wartości tego samego typu co w pierwszej akcji, więc nie ma sposobu, będziesz być w stanie zwrócić wartość z akcji cleanUp.

Jeśli chcesz zwrócić drugą wartość, musisz zawinąć swój błąd w Try, używając asTry, a następnie użyć flatMap. Na problem pod ręką, by to wyglądać mniej więcej tak:

val q = insertBatchAndReturnQuery(entities).asTry.flatMap { 
    case Failure(b: PSQLException) if b.getSQLState == "23505" => 
    //unique key exception, handle this 
    //by removing the duplicate entries from the list 
    ??? 
    case Failure(e) => 
    throw new Exception("some database exception") 
    case Success(count) => DBIO.successful(count) 
} 

Jednak dokumentacja ostrzega, że ​​za pomocą asTry traci zdolność przesyłania strumieniowego, więc może chcesz znaleźć inny sposób to zrobić ...

Powiązane problemy