Skip to content

Added support for casting when Codable. #1327

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions SQLite.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,11 @@
64B8E1702B09748000545AFB /* WindowFunctionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64B8E16F2B09748000545AFB /* WindowFunctionsTests.swift */; };
64B8E1712B09748000545AFB /* WindowFunctionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64B8E16F2B09748000545AFB /* WindowFunctionsTests.swift */; };
64B8E1722B09748000545AFB /* WindowFunctionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 64B8E16F2B09748000545AFB /* WindowFunctionsTests.swift */; };
915BE7892E2BB05300360423 /* Query+Lazy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 915BE7882E2BB05300360423 /* Query+Lazy.swift */; };
915BE78A2E2BB05300360423 /* Query+Lazy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 915BE7882E2BB05300360423 /* Query+Lazy.swift */; };
915BE78B2E2BB05300360423 /* Query+Lazy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 915BE7882E2BB05300360423 /* Query+Lazy.swift */; };
915BE78C2E2BB05300360423 /* Query+Lazy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 915BE7882E2BB05300360423 /* Query+Lazy.swift */; };
915BE78D2E2BB05300360423 /* Query+Lazy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 915BE7882E2BB05300360423 /* Query+Lazy.swift */; };
997DF2AE287FC06D00F8DF95 /* Query+with.swift in Sources */ = {isa = PBXBuildFile; fileRef = 997DF2AD287FC06D00F8DF95 /* Query+with.swift */; };
997DF2AF287FC06D00F8DF95 /* Query+with.swift in Sources */ = {isa = PBXBuildFile; fileRef = 997DF2AD287FC06D00F8DF95 /* Query+with.swift */; };
997DF2B0287FC06D00F8DF95 /* Query+with.swift in Sources */ = {isa = PBXBuildFile; fileRef = 997DF2AD287FC06D00F8DF95 /* Query+with.swift */; };
Expand Down Expand Up @@ -428,6 +433,7 @@
49EB68C31F7B3CB400D89D40 /* Coding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Coding.swift; sourceTree = "<group>"; };
64A8EE422B095FBB00F583F7 /* WindowFunctions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowFunctions.swift; sourceTree = "<group>"; };
64B8E16F2B09748000545AFB /* WindowFunctionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WindowFunctionsTests.swift; sourceTree = "<group>"; };
915BE7882E2BB05300360423 /* Query+Lazy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Query+Lazy.swift"; sourceTree = "<group>"; };
997DF2AD287FC06D00F8DF95 /* Query+with.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Query+with.swift"; sourceTree = "<group>"; };
A121AC451CA35C79005A31D1 /* SQLite.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SQLite.framework; sourceTree = BUILT_PRODUCTS_DIR; };
DB58B21028FB864300F8EEA4 /* SchemaReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchemaReader.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -733,6 +739,7 @@
EE247AFD1C3F06E900AE3E12 /* CustomFunctions.swift */,
EE247AFE1C3F06E900AE3E12 /* Expression.swift */,
EE247AFF1C3F06E900AE3E12 /* Operators.swift */,
915BE7882E2BB05300360423 /* Query+Lazy.swift */,
EE247B001C3F06E900AE3E12 /* Query.swift */,
997DF2AD287FC06D00F8DF95 /* Query+with.swift */,
EE247B011C3F06E900AE3E12 /* Schema.swift */,
Expand Down Expand Up @@ -1133,6 +1140,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
915BE78D2E2BB05300360423 /* Query+Lazy.swift in Sources */,
03A65E801C6BB2FB0062603F /* CoreFunctions.swift in Sources */,
49EB68C61F7B3CB400D89D40 /* Coding.swift in Sources */,
03A65E761C6BB2E60062603F /* Blob.swift in Sources */,
Expand Down Expand Up @@ -1220,6 +1228,7 @@
49EB68C71F7B3CB400D89D40 /* Coding.swift in Sources */,
997DF2B1287FC06D00F8DF95 /* Query+with.swift in Sources */,
3D67B3F71DB246D700A4F4C6 /* Foundation.swift in Sources */,
915BE78C2E2BB05300360423 /* Query+Lazy.swift in Sources */,
3D67B3F81DB246D700A4F4C6 /* Helpers.swift in Sources */,
DB58B21428FB864300F8EEA4 /* SchemaReader.swift in Sources */,
3D67B3E91DB246D100A4F4C6 /* Statement.swift in Sources */,
Expand Down Expand Up @@ -1262,6 +1271,7 @@
DEB306BD2B61CEF500F9D46B /* Coding.swift in Sources */,
DEB306BE2B61CEF500F9D46B /* RTree.swift in Sources */,
DEB306BF2B61CEF500F9D46B /* Blob.swift in Sources */,
915BE7892E2BB05300360423 /* Query+Lazy.swift in Sources */,
DEB306C02B61CEF500F9D46B /* URIQueryParameter.swift in Sources */,
DEB306C12B61CEF500F9D46B /* Foundation.swift in Sources */,
DEB306C22B61CEF500F9D46B /* Connection.swift in Sources */,
Expand Down Expand Up @@ -1338,6 +1348,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
915BE78A2E2BB05300360423 /* Query+Lazy.swift in Sources */,
EE247B0F1C3F06E900AE3E12 /* CoreFunctions.swift in Sources */,
49EB68C41F7B3CB400D89D40 /* Coding.swift in Sources */,
EE247B0A1C3F06E900AE3E12 /* RTree.swift in Sources */,
Expand Down Expand Up @@ -1421,6 +1432,7 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
915BE78B2E2BB05300360423 /* Query+Lazy.swift in Sources */,
EE247B6F1C3F3FEC00AE3E12 /* CoreFunctions.swift in Sources */,
49EB68C51F7B3CB400D89D40 /* Coding.swift in Sources */,
EE247B651C3F3FEC00AE3E12 /* Blob.swift in Sources */,
Expand Down
135 changes: 90 additions & 45 deletions Sources/SQLite/Core/Statement.swift
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ public final class Statement {

reset(clearBindings: false)
_ = try step()
return row[0]
return try row.getValue(0)
}

/// - Parameter bindings: A list of parameters to bind to the statement.
Expand Down Expand Up @@ -229,9 +229,9 @@ extension Array {
}

extension Statement: FailableIterator {
public typealias Element = [Binding?]
public func failableNext() throws -> [Binding?]? {
try step() ? Array(row) : nil
public typealias Element = Cursor
public func failableNext() throws -> Cursor? {
try step() ? row : nil
}
}

Expand All @@ -258,30 +258,103 @@ extension Statement: CustomStringConvertible {

}

public struct Cursor {
public protocol CursorProtocol {
func getValue(_ idx: Int) throws -> Binding?
func getValue(_ idx: Int) throws -> Double
func getValue(_ idx: Int) throws -> Int64
func getValue(_ idx: Int) throws -> String
func getValue(_ idx: Int) throws -> Blob
}

extension CursorProtocol {
public func getValue<T: Binding>(_ idx: Int) -> T? {
switch T.self {
case is Double.Type:
return try? getValue(idx) as Double as? T
case is Int64.Type:
return try? getValue(idx) as Int64 as? T
case is String.Type:
return try? getValue(idx) as String as? T
case is Blob.Type:
return try? getValue(idx) as Blob as? T
default:
return nil
}
}

public func getValue(_ idx: Int) throws -> Bool {
try Bool.fromDatatypeValue(getValue(idx))
}

public func getValue(_ idx: Int) throws -> Int {
try Int.fromDatatypeValue(getValue(idx))
}
}

struct CursorWithBindingArray: CursorProtocol {
let elements: [Binding?]
init(elements: [Binding?]) {
self.elements = elements
}

func getValue(_ idx: Int) throws -> Binding? {
elements[idx]
}
func getValue(_ idx: Int) throws -> Double {
guard let value = elements[idx] as? Double else {
throw QueryError.unexpectedNullValue(name: "column at index \(idx)")
}
return value
}
func getValue(_ idx: Int) throws -> Int64 {
guard let value = elements[idx] as? Int64 else {
throw QueryError.unexpectedNullValue(name: "column at index \(idx)")
}
return value
}
func getValue(_ idx: Int) throws -> String {
guard let value = elements[idx] as? String else {
throw QueryError.unexpectedNullValue(name: "column at index \(idx)")
}
return value
}
func getValue(_ idx: Int) throws -> Blob {
guard let value = elements[idx] as? Blob else {
throw QueryError.unexpectedNullValue(name: "column at index \(idx)")
}
return value
}
}

fileprivate let handle: OpaquePointer
public struct Cursor: CursorProtocol {
fileprivate let statement: Statement
fileprivate var handle: OpaquePointer {
statement.handle!
}

fileprivate let columnCount: Int

fileprivate init(_ statement: Statement) {
handle = statement.handle!
self.statement = statement
columnCount = statement.columnCount
}

public subscript(idx: Int) -> Double {
public func getValue(_ idx: Int) throws -> Double {
sqlite3_column_double(handle, Int32(idx))
}

public subscript(idx: Int) -> Int64 {
public func getValue(_ idx: Int) throws -> Int64 {
sqlite3_column_int64(handle, Int32(idx))
}

public subscript(idx: Int) -> String {
String(cString: UnsafePointer(sqlite3_column_text(handle, Int32(idx))))
public func getValue(_ idx: Int) throws -> String {
guard let text = sqlite3_column_text(handle, Int32(idx)) else {
throw QueryError.unexpectedNullValue(name: "column at index \(idx)")
}
return String(cString: UnsafePointer(text))
}

public subscript(idx: Int) -> Blob {
public func getValue(_ idx: Int) throws -> Blob {
if let pointer = sqlite3_column_blob(handle, Int32(idx)) {
let length = Int(sqlite3_column_bytes(handle, Int32(idx)))
return Blob(bytes: pointer, length: length)
Expand All @@ -292,48 +365,20 @@ public struct Cursor {
}
}

// MARK: -

public subscript(idx: Int) -> Bool {
Bool.fromDatatypeValue(self[idx])
}

public subscript(idx: Int) -> Int {
Int.fromDatatypeValue(self[idx])
}

}

/// Cursors provide direct access to a statement’s current row.
extension Cursor: Sequence {

public subscript(idx: Int) -> Binding? {
public func getValue(_ idx: Int) throws -> Binding? {
switch sqlite3_column_type(handle, Int32(idx)) {
case SQLITE_BLOB:
return self[idx] as Blob
return try getValue(idx) as Blob
case SQLITE_FLOAT:
return self[idx] as Double
return try getValue(idx) as Double
case SQLITE_INTEGER:
return self[idx] as Int64
return try getValue(idx) as Int64
case SQLITE_NULL:
return nil
case SQLITE_TEXT:
return self[idx] as String
return try getValue(idx) as String
case let type:
fatalError("unsupported column type: \(type)")
}
}

public func makeIterator() -> AnyIterator<Binding?> {
var idx = 0
return AnyIterator {
if idx >= columnCount {
return .none
} else {
idx += 1
return self[idx - 1]
}
}
}

}
10 changes: 5 additions & 5 deletions Sources/SQLite/Schema/Connection+Schema.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ public extension Connection {
// https://sqlite.org/pragma.html#pragma_foreign_key_check
func foreignKeyCheck(table: String? = nil) throws -> [ForeignKeyError] {
try run("PRAGMA foreign_key_check" + (table.map { "(\($0.quote()))" } ?? ""))
.compactMap { (row: [Binding?]) -> ForeignKeyError? in
guard let table = row[0] as? String,
let rowId = row[1] as? Int64,
let target = row[2] as? String else { return nil }
.compactMap { (row: Cursor) -> ForeignKeyError? in
guard let table = row.getValue(0) as String?,
let rowId = row.getValue(1) as Int64?,
let target = row.getValue(2) as String? else { return nil }

return ForeignKeyError(from: table, rowId: rowId, to: target)
}
Expand All @@ -29,7 +29,7 @@ public extension Connection {
precondition(table == nil || supports(.partialIntegrityCheck), "partial integrity check not supported")

return try run("PRAGMA integrity_check" + (table.map { "(\($0.quote()))" } ?? ""))
.compactMap { $0[0] as? String }
.compactMap { $0.getValue(0) as String? }
.filter { $0 != "ok" }
}
}
57 changes: 57 additions & 0 deletions Sources/SQLite/Typed/Query+Lazy.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
//
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

extension Array where Element == LazySequence<AnyIterator<Row>> {
@available(swift, deprecated: 1, message: "Please use return value of prepare as Array directly")
public init(_ values: Element) {
preconditionFailure("Please use return value of prepare as Array directly")
}
}

extension Connection {
@_disfavoredOverload
public func prepare(_ query: QueryType) throws -> [Row] {
let expression = query.expression
let statement = try prepare(expression.template, expression.bindings)

let columnNames = try columnNamesForQuery(query)

return Array(AnyIterator {
statement.next().map { cursor in
Row(columnNames, (0..<columnNames.count).map({
try? cursor.getValue($0) as Binding?
}))
}
})
}

public func prepare(_ query: QueryType) throws -> LazySequence<AnyIterator<Row>> {
let expression = query.expression
let statement = try prepare(expression.template, expression.bindings)

let columnNames = try columnNamesForQuery(query)

return AnyIterator { statement.next().map { Row(columnNames, $0) } }.lazy
}
}
Loading
Loading