How to access an FTS table in SQLite.swift using the IN condition

一曲冷凌霜 提交于 2019-12-06 02:59:14

I ended up just running the raw SQL command. This doesn't exactly answer what I was asking in the question (since it doesn't use the pure SQLite.swift API) but for those who just need to get something working, ... it works.

Here is a modified example that I pulled from some of my source code.

static func findLinesContaining(_ searchTerms: String, forSearchScope scope: SearchScope) throws -> [TextLines] {

    guard let db = SQLiteDataStore.sharedInstance.TextDB else {
        throw DataAccessError.datastore_Connection_Error
    }

    // TODO: convert to SQLite.swift syntax rather than using a SQL string
    var statement: Statement? = nil
    switch scope {
    case .wholeCollection:
        statement = try db.run("SELECT bookId, chapterId, lineId, lineText" +
            " FROM lines" +
            " WHERE rowid IN (SELECT docid FROM fts_table" +
            " WHERE fts_table MATCH ?);", searchTerms)

    case .singleBook(let chosenBookId):
        statement = try db.run("SELECT bookId, chapterId, lineId, lineText" +
            " FROM lines" +
            " WHERE rowid IN (SELECT docid FROM fts_table" +
            " WHERE fts_table MATCH ?) AND bookId = ?;", [searchTerms, chosenBookId])
    }


    var returnList: [TextLine] = []
    for row in statement! {

        let line = TextLine()
        if let bookId = row[0] as? Int64,
            let chapterId = row[1] as? Int64,
            let lineId = row[2] as? Int64,
            let text = row[3] as? String {

            line.bookId = Int(bookId)
            line.chapterId = Int(chapterId)
            line.lineId = Int(lineId)
            line.lineText = text
        }

        returnList.append(line)
    }

    return returnList
}

The above code is untested after renaming variables and classes for use on SO. You have my permission to edit the code if you find a bug.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!