Search code examples
swiftsqlitegrdb

How do I divide integers in a GRDB SQLite filter?


I'm running a query in GRDB in my Swift iOS app that tries to find vocab words that have been guessed incorrectly more than a specific %:

func getIncorrectWords(db: GRDB.Database, threshold: Double) throws -> [Word] {
  return words
    .filter(Column("timesCorrect") / Column("timesSeen") < threshold)
    .fetchAll(db);
}

But it's including all words that have ever been guessed wrong.

How can I get it to compare to the correct threshold?


Solution

  • The columns are integers, so you're doing integer division.

    In the SQLite, you have to cast (CAST(timesCorrect AS REAL) / timesSeen), and there doesn't seem to be an alias in GRDB, so just write the SQL directly:

    func getIncorrectWords(db: GRDB.Database, threshold: Double) throws -> [Word] {
      return words
        .filter(sql: "CAST(timesCorrect AS REAL) / timesShown < ?", arguments: [threshold])
        .fetchAll(db);
    }