stephencelis / SQLite.swift

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

SQLite.swift Flexible Typing? #1155

Closed jasaldivara closed 1 year ago

jasaldivara commented 1 year ago

I want to use SQLite's Flexible Typing in SQLite.swift.

My idea is to have a column declared as "TEXT" Datatype in my SQLite database, but with the option of also storing binary data as a BLOB.

In the Swift side of things, I'm thinkinig of declaring my type as an Enumeration with associated values:

enum MyImage {
    case iconName(String)
    case customImage(Data)
}

Is it possible to make this enum conform to SQLite.swift Value protocol and make it store it's value either as a text string or a binary blob depending on it's case?

nathanfallet commented 1 year ago

You can create a custom encoder/decoder. You set the first byte to 1 for the first case of the enum, and 2 for the second, and you read the rest of your data to initialize your object. That way, you store everything as BLOB.