Skip to content

Commit

Permalink
Merge pull request #21 from samnung/master
Browse files Browse the repository at this point in the history
Add support for BLOB column type
  • Loading branch information
tanner0101 authored Aug 7, 2017
2 parents 92d9195 + 5a6bedf commit f364a11
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Sources/SQLite/SQLite+Result.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import CSQLite
import Node
import typealias Core.Bytes

extension SQLite {
/**
Expand Down Expand Up @@ -43,6 +44,19 @@ extension SQLite {

data[column] = .string(value)

case SQLITE_BLOB:
if let blobPointer = sqlite3_column_blob(pointer, i) {
let length = Int(sqlite3_column_bytes(pointer, i))

let i8bufptr = UnsafeBufferPointer(start: blobPointer.assumingMemoryBound(to: Bytes.Element.self), count: length)

data[column] = .bytes(Bytes(i8bufptr))
} else {
// The return value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
// https://www.sqlite.org/c3ref/column_blob.html
data[column] = .bytes([])
}

case SQLITE_INTEGER:
let integer = Int(sqlite3_column_int64(pointer, i))
data[column] = .number(.int(integer))
Expand Down
8 changes: 8 additions & 0 deletions Sources/SQLite/SQLite+Statement.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import CSQLite
import typealias Core.Bytes

extension SQLite {
/**
Expand Down Expand Up @@ -49,6 +50,13 @@ extension SQLite {
}
}

public func bind(_ value: Bytes) throws {
let count = Int32(value.count)
if sqlite3_bind_blob(pointer, nextBindPosition, value, count, SQLITE_TRANSIENT) != SQLITE_OK {
throw SQLiteError.bind(database.errorMessage)
}
}

public func bind(_ value: Bool) throws {
try bind(value ? 1 : 0)
}
Expand Down
17 changes: 17 additions & 0 deletions Tests/SQLiteTests/SQLite3Tests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,23 @@ class SQLite3Tests: XCTestCase {
XCTAssertEqual(result.data["max"], max.makeNode(in: nil))
}
}


func testBlob() {
let data = Data(bytes: [0, 1, 2])

_ = try! database.execute("DROP TABLE IF EXISTS `foo`")
_ = try! database.execute("CREATE TABLE foo (bar BLOB(4))")
_ = try! database.execute("INSERT INTO foo VALUES (?)") { statement in
try! statement.bind(data.makeBytes())
}

if let result = try! database.execute("SELECT * FROM foo").first {
XCTAssertEqual(result.data["bar"], Node.bytes(data.makeBytes()))
} else {
XCTFail()
}
}


static let allTests = [
Expand Down

0 comments on commit f364a11

Please sign in to comment.