stephencelis / SQLite.swift

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

[QUESTION] Storing data as [String] in column #987

Closed benmckillop closed 3 years ago

benmckillop commented 4 years ago
private let mixer = Expression<[String]>("mixer")

   func createTable() {
        do {
            try db!.run(trays.create(ifNotExists: true) { table in
                table.column(mixer) <- Error here
            })
        }
        catch {
            print("Unable to create table")
        }
    }

I'm trying to store items in an array of strings but at the line table.column(mixer) I get:

Instance method 'column(_:unique:check:defaultValue:)' requires that '[String]' conform to 'Value'

Any advice on how I can store values in an array? I can't see anything in the docs

xgjyjy commented 4 years ago

me too

nathanfallet commented 4 years ago

Try to encode your String array to json and store the json output (best solution to store an array)

import Foundation

// ENCODING
print("ENCODING")

// Assume this is our array of strings
let array = ["one", "two", "three"]

// Convert your array to JSON
if let jsonData = try? JSONEncoder().encode(array), let json = String(bytes: jsonData, encoding: .utf8) {
    // Here you have your array as a json string
    // So you can save it into a string column

    print(json) // ["one","two","three"]
}

// DECODING
print("DECODING")

// Assume this is the string retrieved from database
let json = "[\"one\",\"two\",\"three\"]"

// Convert JSON to array
if let jsonData = json.data(using: .utf8), let array = try? JSONDecoder().decode([String].self, from: jsonData) {
    // Here you have your array back

    for e in array {
        print(e)
    }
}

Screen Shot 2020-07-10 at 6 59 27 PM

pujiaxin33 commented 4 years ago

I also encountered the same problem before, adding extension to Array conform Value Protocol, you can directly store [String] type data.

I encapsulated the code into the SQLiteValueExtension library, you can introduce it through Cocoapods, you can directly store the data of the [String] type.

Specific details can be found in the SQLiteValueExtension Github homepage:SQLiteValueExtension

nathanfallet commented 3 years ago

@pujiaxin33 Feel free to open a PR to add this feature to SQLite.swift. Closing for now as a solution was found.