SQLite.swift icon indicating copy to clipboard operation
SQLite.swift copied to clipboard

Filter is not working when Inserting Encodable Values

Open Firas-Shrourou opened this issue 5 years ago • 7 comments

Inserting using [String: String] is working fine like this:

func insertSomeValues(tableName: String, contentValues: [String: String]) {
        do {
            let table = Table(tableName)
            let rowid = try database.run(table.insert(contentValues))
            print ("inserted id: \(rowid)")
        } catch {
            print("Insertion Into Table Failed: \(error)")
        }
    }

But when filtering the table using .filter(Key == "Some_Key") it will not work

You need to use it like this to work

.filter(Key == ""SomeKey"")

What is the problem here ?

Firas-Shrourou avatar Aug 02 '20 20:08 Firas-Shrourou

Seems that we need to make a change in the code

        func encode<T>(_ value: T, forKey key: Key) throws where T: Swift.Encodable {
            if let data = value as? Data {
                self.encoder.setters.append(Expression(key.stringValue) <- data)
            } else if let string = value as? String {
                self.encoder.setters.append(Expression(key.stringValue) <- string)
            } else {
                let encoded = try JSONEncoder().encode(value)
                let string = String(data: encoded, encoding: .utf8)
                self.encoder.setters.append(Expression(key.stringValue) <- string)
            }
        }

Firas-Shrourou avatar Aug 03 '20 09:08 Firas-Shrourou

Yes. This is a quickfix I proposed. It fixes the issue about strings being inserted as "your_string" instead of your_string.

TenMaKo avatar Aug 03 '20 13:08 TenMaKo

You need also to clean folder and rebuild.

Firas-Shrourou avatar Aug 03 '20 14:08 Firas-Shrourou

You need also to clean folder and rebuild.

Yes, as it won't correct already inserted data.

TenMaKo avatar Aug 03 '20 14:08 TenMaKo

is there any plan to fix this inside the distributed package/ pod in the future?

Firas-Shrourou avatar Aug 03 '20 14:08 Firas-Shrourou

is there any plan to fix this inside the distributed package/ pod in the future?

This repo doesn't seem to be maintained anymore and I'm in no way connected to the maintainer. In other opened issues related to Codable, you will find workarounds to be able to use this protocol but it's not a proper implementation so I have no plan about creating a PR or fork. Sorry :/

TenMaKo avatar Aug 03 '20 14:08 TenMaKo

@TenMaKo We would be happy to review your PR if you open one (and mark it as fixing this issue)

nathanfallet avatar Aug 22 '21 16:08 nathanfallet