From 86947d548ba7888fdf757d496e9bf624b6386b8f Mon Sep 17 00:00:00 2001 From: Tanner Date: Thu, 16 Jul 2020 19:25:48 -0400 Subject: [PATCH] Support storing json in text columns (#87) * add support for storing json in text columns * newlines --- Sources/SQLiteKit/SQLiteDataDecoder.swift | 7 +++++-- Tests/SQLiteKitTests/SQLiteKitTests.swift | 12 ++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/Sources/SQLiteKit/SQLiteDataDecoder.swift b/Sources/SQLiteKit/SQLiteDataDecoder.swift index d91cc6c..eb3ada9 100644 --- a/Sources/SQLiteKit/SQLiteDataDecoder.swift +++ b/Sources/SQLiteKit/SQLiteDataDecoder.swift @@ -43,9 +43,12 @@ public struct SQLiteDataDecoder { func jsonDecoder() throws -> Decoder { let data: Data - if case .blob(let buffer) = self.data { + switch self.data { + case .blob(let buffer): data = Data(buffer.readableBytesView) - } else { + case .text(let string): + data = Data(string.utf8) + default: data = .init() } return try JSONDecoder() diff --git a/Tests/SQLiteKitTests/SQLiteKitTests.swift b/Tests/SQLiteKitTests/SQLiteKitTests.swift index c3f76f3..634a378 100644 --- a/Tests/SQLiteKitTests/SQLiteKitTests.swift +++ b/Tests/SQLiteKitTests/SQLiteKitTests.swift @@ -95,6 +95,18 @@ class SQLiteKitTests: XCTestCase { XCTAssertEqual(res[0].column("foreign_keys"), .integer(1)) } + func testJSONStringColumn() throws { + _ = try self.connection.query("CREATE TABLE foo (bar TEXT)").wait() + _ = try self.connection.query(#"INSERT INTO foo (bar) VALUES ('{"baz": "qux"}')"#).wait() + let rows = try self.connection.query("SELECT * FROM foo").wait() + + struct Bar: Codable { + var baz: String + } + let bar = try SQLiteDataDecoder().decode(Bar.self, from: rows[0].column("bar")!) + XCTAssertEqual(bar.baz, "qux") + } + func testMultipleInMemoryDatabases() throws { let a = SQLiteConnectionSource( configuration: .init(storage: .memory, enableForeignKeys: true),