vapor-community / postgresql

Robust PostgreSQL interface for Swift
MIT License
131 stars 33 forks source link

Problem with bytea field #45

Closed myfirmapp closed 7 years ago

myfirmapp commented 7 years ago

Hello

I am trying to save data (formed from an NSAttributedString) to a bytea field.

As a test i try to save a string and retrieve it.

Here is my code:

`
let s = "Une string".data(using: .utf8)!

    let bytesfroms = [UInt8](s)

    let da = Data.init(bytes: bytesfroms)

    let st = String(data: da, encoding: String.Encoding.utf8)

    print(st)

    Optional("Une string")

    let savedData = try! conn.execute("INSERT INTO files (filename,file) VALUES ($1,$2)",[fileName.makeNode(in: nil),bytesfroms.makeNode(in: nil)])`

Sa far as i test i can see that my string is transformet into Data and i can retrieve it before saving.

I save it in the database (the bytea field says BINARY (39 bytes).

When i tried to retrieve my string from the database i do:

`let results = try! conn.execute("SELECT filename,file FROM files ORDER BY id")

    let row = results[0]

    var b:[UInt8]? = row?["file"]!.bytes

    let da:Data = Data(bytes: b!)

    let st = String(data: da, encoding: String.Encoding.utf8)

    print("String: \(st)")

` The result is:

    String: Optional("{85,110,101,32,115,116,114,105,110,103}")

I expect to see String: Optional("Une string")

What i am doing wrong with the Node ?

myfirmapp commented 7 years ago

So after following the discussion from the link above i managed to make it work by using let savedData = try! conn.execute("INSERT INTO files (filename,file) VALUES ($1,$2)",[fileName.makeNode(in: nil),StructuredData.bytes(bytesfroms)])