stephencelis / SQLite.swift

A type-safe, Swift-language layer over SQLite3.
MIT License
9.57k stars 1.55k forks source link

Possible synchronisation issues #1088

Open atulmanwar opened 2 years ago

atulmanwar commented 2 years ago

Our app was facing a database corruption crash while reading from the database. I was going through the implementation of SQLite.swift to check for possible synchronisation issues and found this piece of code.

// QueryType.swift
extension Connection {
    public func prepare(_ query: QueryType) throws -> AnySequence<Row> {
        let expression = query.expression
        let statement = try prepare(expression.template, expression.bindings)

        let columnNames = try columnNamesForQuery(query)

        return AnySequence {
            AnyIterator { statement.next().map { Row(columnNames, $0) } }
        }
    }
...

Each call to statement.next() is executed in a serial queue. But in between the two calls the code switches to the caller thread and leaves the database exposed to a sneaky write operation. This can potentially cause the subsequent statement.next() call to throw a corruption error.

@jberkel @NathanFallet Please check.