From 034a24dfe3cef3eadbad8cbaab7b4848da84c4b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 22 Jul 2016 12:56:26 +0200 Subject: [PATCH] _SQLExpression.sql(_:_:) turns all values into safely escaped SQL literals when given nil arguments. (addresses #83) --- GRDB.xcodeproj/project.pbxproj | 18 ++++++++ .../QueryInterfaceRequest.swift | 4 +- GRDB/QueryInterface/SQLCollation.swift | 2 +- GRDB/QueryInterface/SQLSelectQuery.swift | 41 +++++++++++-------- Tests/Private/SQLExpressionLiteralTests.swift | 40 ++++++++++++++++++ 5 files changed, 85 insertions(+), 20 deletions(-) create mode 100644 Tests/Private/SQLExpressionLiteralTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 6f3e038bb..1309ef4db 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -272,6 +272,14 @@ 56494C161D41F5C300529CB4 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56494C101D41F5C300529CB4 /* DatabaseValueConvertibleEscapingTests.swift */; }; 56494C171D41F5C300529CB4 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56494C101D41F5C300529CB4 /* DatabaseValueConvertibleEscapingTests.swift */; }; 56494C181D41F5C300529CB4 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56494C101D41F5C300529CB4 /* DatabaseValueConvertibleEscapingTests.swift */; }; + 56494C221D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56494C211D422BAE00529CB4 /* SQLExpressionLiteralTests.swift */; }; + 56494C231D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56494C211D422BAE00529CB4 /* SQLExpressionLiteralTests.swift */; }; + 56494C241D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56494C211D422BAE00529CB4 /* SQLExpressionLiteralTests.swift */; }; + 56494C251D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56494C211D422BAE00529CB4 /* SQLExpressionLiteralTests.swift */; }; + 56494C261D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56494C211D422BAE00529CB4 /* SQLExpressionLiteralTests.swift */; }; + 56494C271D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56494C211D422BAE00529CB4 /* SQLExpressionLiteralTests.swift */; }; + 56494C281D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56494C211D422BAE00529CB4 /* SQLExpressionLiteralTests.swift */; }; + 56494C291D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56494C211D422BAE00529CB4 /* SQLExpressionLiteralTests.swift */; }; 564A50C71BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; }; 564A50C81BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */; }; 565049051CE32543000A97D8 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565049041CE32543000A97D8 /* FetchedRecordsControllerTests.swift */; }; @@ -1330,6 +1338,7 @@ 563ABAF61D18824F003B37F3 /* NSUUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSUUID.swift; sourceTree = ""; }; 563ABB051D188555003B37F3 /* NSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSUUIDTests.swift; sourceTree = ""; }; 56494C101D41F5C300529CB4 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; + 56494C211D422BAE00529CB4 /* SQLExpressionLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionLiteralTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* CollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CollationTests.swift; sourceTree = ""; }; 565049041CE32543000A97D8 /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXCrashTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -1844,6 +1853,7 @@ 56494C101D41F5C300529CB4 /* DatabaseValueConvertibleEscapingTests.swift */, 56EB0AB11BCD787300A3DC55 /* NSDataMemoryTests.swift */, 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */, + 56494C211D422BAE00529CB4 /* SQLExpressionLiteralTests.swift */, 5605F1861C69111300235C62 /* StatementInformationTests.swift */, ); path = Private; @@ -3098,6 +3108,7 @@ EED6C2D71D00B6D200F8E701 /* NSURLTests.swift in Sources */, 560FC58D1CB00B880014AA8E /* Row+FoundationTests.swift in Sources */, 567156141CB141D0007DC145 /* InMemoryDatabaseTests.swift in Sources */, + 56494C231D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */, 560FC58E1CB00B880014AA8E /* PrimaryKeyRowIDTests.swift in Sources */, EE5075861D00E611005D9C5B /* DatabaseValue+FoundationTests.swift in Sources */, 560FC58F1CB00B880014AA8E /* DatabaseReaderTests.swift in Sources */, @@ -3211,6 +3222,7 @@ 5671564B1CB16729007DC145 /* Row+FoundationTests.swift in Sources */, 5671564C1CB16729007DC145 /* InMemoryDatabaseTests.swift in Sources */, 563ABB081D188555003B37F3 /* NSUUIDTests.swift in Sources */, + 56494C241D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */, 5671564D1CB16729007DC145 /* PrimaryKeyRowIDTests.swift in Sources */, 5671564E1CB16729007DC145 /* DatabaseReaderTests.swift in Sources */, 5671564F1CB16729007DC145 /* RecordEditedTests.swift in Sources */, @@ -3356,6 +3368,7 @@ 56AFCA581CB1AA9900F48B96 /* Row+FoundationTests.swift in Sources */, 569178411CED8E0C00E179EA /* FetchedRecordsControllerTests.swift in Sources */, 56AFCA5A1CB1AA9900F48B96 /* RecordSubClassTests.swift in Sources */, + 56494C271D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */, 56AFCA5B1CB1AA9900F48B96 /* DatabaseValueTests.swift in Sources */, 56AFCA5C1CB1AA9900F48B96 /* ReadOnlyDatabaseTests.swift in Sources */, 56AFCA5D1CB1AA9900F48B96 /* DatabaseReaderTests.swift in Sources */, @@ -3454,6 +3467,7 @@ 56AFCAB31CB1ABC800F48B96 /* RecordSubClassTests.swift in Sources */, 56AFCAB41CB1ABC800F48B96 /* DatabaseValueTests.swift in Sources */, EED6C2D41D00B6CD00F8E701 /* NSStringTests.swift in Sources */, + 56494C281D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */, 5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 56AFCAB51CB1ABC800F48B96 /* ReadOnlyDatabaseTests.swift in Sources */, 56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */, @@ -3610,6 +3624,7 @@ 56EA86951C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */, 565B0FF01BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */, 563ABB0A1D188555003B37F3 /* NSUUIDTests.swift in Sources */, + 56494C261D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */, 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56A238581B9C74A90082EB20 /* PrimaryKeyRowIDTests.swift in Sources */, 56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */, @@ -3650,6 +3665,7 @@ files = ( 5614DEF81BAA1B43003163B3 /* DatabaseValueConversionTests.swift in Sources */, 56300B851C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */, + 56494C221D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */, 563363BD1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */, 56A238551B9C74A90082EB20 /* PrimaryKeyNoneTests.swift in Sources */, 56A2384F1B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */, @@ -3909,6 +3925,7 @@ F3BA80BD1CFB2FD1003DC1BA /* DatabasePoolFunctionTests.swift in Sources */, F3BA81261CFB3063003DC1BA /* RecordCopyTests.swift in Sources */, 563ABB0D1D188555003B37F3 /* NSUUIDTests.swift in Sources */, + 56494C291D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */, F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */, F3BA80F91CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, F3BA81091CFB3056003DC1BA /* NSDateComponentsTests.swift in Sources */, @@ -4002,6 +4019,7 @@ files = ( F3BA80D81CFB300B003DC1BA /* DatabaseValueTests.swift in Sources */, F3BA80CC1CFB2FD8003DC1BA /* DatabaseQueueTests.swift in Sources */, + 56494C251D422BAE00529CB4 /* SQLExpressionLiteralTests.swift in Sources */, F3BA81341CFB3064003DC1BA /* RecordCopyTests.swift in Sources */, F3BA81101CFB3057003DC1BA /* Row+FoundationTests.swift in Sources */, F3BA812C1CFB3064003DC1BA /* MinimalPrimaryKeyRowIDTests.swift in Sources */, diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index e0dfb1ffd..b33292dc3 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -25,10 +25,10 @@ extension QueryInterfaceRequest : FetchRequest { @warn_unused_result public func prepare(db: Database) throws -> (SelectStatement, RowAdapter?) { // TODO: split statement generation from arguments building - var arguments = StatementArguments() + var arguments: StatementArguments? = StatementArguments() let sql = try query.sql(db, &arguments) let statement = try db.selectStatement(sql) - try statement.setArgumentsWithValidation(arguments) + try statement.setArgumentsWithValidation(arguments!) return (statement, nil) } } diff --git a/GRDB/QueryInterface/SQLCollation.swift b/GRDB/QueryInterface/SQLCollation.swift index eee8c8fe7..fbf8cf5d4 100644 --- a/GRDB/QueryInterface/SQLCollation.swift +++ b/GRDB/QueryInterface/SQLCollation.swift @@ -46,7 +46,7 @@ extension _SQLCollatedExpression : _SQLOrdering { /// Do not use it directly. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func orderingSQL(db: Database, inout _ arguments: StatementArguments) throws -> String { + public func orderingSQL(db: Database, inout _ arguments: StatementArguments?) throws -> String { return try sqlExpression.orderingSQL(db, &arguments) } } diff --git a/GRDB/QueryInterface/SQLSelectQuery.swift b/GRDB/QueryInterface/SQLSelectQuery.swift index 5d34bce57..55b696dc7 100644 --- a/GRDB/QueryInterface/SQLSelectQuery.swift +++ b/GRDB/QueryInterface/SQLSelectQuery.swift @@ -50,7 +50,7 @@ public struct _SQLSelectQuery { self.limit = limit } - func sql(db: Database, inout _ arguments: StatementArguments) throws -> String { + func sql(db: Database, inout _ arguments: StatementArguments?) throws -> String { var sql = "SELECT" if distinct { @@ -200,7 +200,7 @@ indirect enum _SQLSource { case Table(name: String, alias: String?) case Query(query: _SQLSelectQuery, alias: String?) - func sql(db: Database, inout _ arguments: StatementArguments) throws -> String { + func sql(db: Database, inout _ arguments: StatementArguments?) throws -> String { switch self { case .Table(let table, let alias): if let alias = alias { @@ -227,7 +227,7 @@ indirect enum _SQLSource { /// See https://github.com/groue/GRDB.swift/#the-query-interface public protocol _SQLOrdering { var reversedSortDescriptor: _SQLSortDescriptor { get } - func orderingSQL(db: Database, inout _ arguments: StatementArguments) throws -> String + func orderingSQL(db: Database, inout _ arguments: StatementArguments?) throws -> String } /// This type is an implementation detail of the query interface. @@ -258,7 +258,7 @@ extension _SQLSortDescriptor : _SQLOrdering { /// Do not use it directly. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func orderingSQL(db: Database, inout _ arguments: StatementArguments) throws -> String { + public func orderingSQL(db: Database, inout _ arguments: StatementArguments?) throws -> String { switch self { case .Asc(let expression): return try expression.sql(db, &arguments) + " ASC" @@ -347,7 +347,7 @@ extension _SpecificSQLExpressible where Self: _SQLOrdering { /// Do not use it directly. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func orderingSQL(db: Database, inout _ arguments: StatementArguments) throws -> String { + public func orderingSQL(db: Database, inout _ arguments: StatementArguments?) throws -> String { return try sqlExpression.sql(db, &arguments) } } @@ -358,7 +358,7 @@ extension _SpecificSQLExpressible where Self: _SQLSelectable { /// Do not use it directly. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func resultColumnSQL(db: Database, inout _ arguments: StatementArguments) throws -> String { + public func resultColumnSQL(db: Database, inout _ arguments: StatementArguments?) throws -> String { return try sqlExpression.sql(db, &arguments) } @@ -366,7 +366,7 @@ extension _SpecificSQLExpressible where Self: _SQLSelectable { /// Do not use it directly. /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func countedSQL(db: Database, inout _ arguments: StatementArguments) throws -> String { + public func countedSQL(db: Database, inout _ arguments: StatementArguments?) throws -> String { return try sqlExpression.sql(db, &arguments) } @@ -464,7 +464,7 @@ public indirect enum _SQLExpression { case CountDistinct(_SQLExpression) /// - func sql(db: Database, inout _ arguments: StatementArguments) throws -> String { + func sql(db: Database, inout _ arguments: StatementArguments?) throws -> String { // NOTE: this method *was* slow to compile // https://medium.com/swift-programming/speeding-up-slow-swift-build-times-922feeba5780#.s77wmh4h0 // 10746.4ms /Users/groue/Documents/git/groue/GRDB.swift/GRDB/FetchRequest/SQLSelectQuery.swift:439:10 func sql(db: Database, inout _ arguments: StatementArguments) throws -> String @@ -473,12 +473,15 @@ public indirect enum _SQLExpression { switch self { case .Literal(let sql, let literalArguments): if let literalArguments = literalArguments { - arguments.values.appendContentsOf(literalArguments.values) + guard arguments != nil else { + fatalError("Not implemented") + } + arguments!.values.appendContentsOf(literalArguments.values) for (name, value) in literalArguments.namedValues { - if arguments.namedValues[name] != nil { + if arguments!.namedValues[name] != nil { throw DatabaseError(code: SQLITE_MISUSE, message: "argument \(String(reflecting: name)) can't be reused") } - arguments.namedValues[name] = value + arguments!.namedValues[name] = value } } return sql @@ -487,8 +490,12 @@ public indirect enum _SQLExpression { guard let value = value else { return "NULL" } - arguments.values.append(value) - return "?" + if arguments == nil { + return value.sqlLiteral + } else { + arguments!.values.append(value) + return "?" + } case .Identifier(let identifier, let sourceName): if let sourceName = sourceName { @@ -650,8 +657,8 @@ extension _SQLExpression : _SQLOrdering {} /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public protocol _SQLSelectable { - func resultColumnSQL(db: Database, inout _ arguments: StatementArguments) throws -> String - func countedSQL(db: Database, inout _ arguments: StatementArguments) throws -> String + func resultColumnSQL(db: Database, inout _ arguments: StatementArguments?) throws -> String + func countedSQL(db: Database, inout _ arguments: StatementArguments?) throws -> String var sqlSelectableKind: _SQLSelectableKind { get } } @@ -671,7 +678,7 @@ enum _SQLResultColumn { extension _SQLResultColumn : _SQLSelectable { - func resultColumnSQL(db: Database, inout _ arguments: StatementArguments) throws -> String { + func resultColumnSQL(db: Database, inout _ arguments: StatementArguments?) throws -> String { switch self { case .Star(let sourceName): if let sourceName = sourceName { @@ -684,7 +691,7 @@ extension _SQLResultColumn : _SQLSelectable { } } - func countedSQL(db: Database, inout _ arguments: StatementArguments) throws -> String { + func countedSQL(db: Database, inout _ arguments: StatementArguments?) throws -> String { switch self { case .Star: return "*" diff --git a/Tests/Private/SQLExpressionLiteralTests.swift b/Tests/Private/SQLExpressionLiteralTests.swift new file mode 100644 index 000000000..48e257fd3 --- /dev/null +++ b/Tests/Private/SQLExpressionLiteralTests.swift @@ -0,0 +1,40 @@ +import XCTest + +#if USING_SQLCIPHER + @testable import GRDBCipher +#elseif USING_CUSTOMSQLITE + @testable import GRDBCustomSQLite +#else + @testable import GRDB +#endif + +class SQLExpressionLiteralTests: GRDBTestCase { + + func testWithArguments() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + let expression = SQLColumn("foo").collating("NOCASE") == "'bar'" && SQLColumn("baz") >= 1 + var arguments: StatementArguments? = StatementArguments() + let sql = try dbQueue.inDatabase { db -> String in + try expression.sql(db, &arguments) + } + XCTAssertEqual(sql, "((\"foo\" = ? COLLATE NOCASE) AND (\"baz\" >= ?))") + let values = arguments!.values + XCTAssertEqual(values.count, 2) + XCTAssertEqual((values[0] as! String), "'bar'") + XCTAssertEqual((values[1] as! Int), 1) + } + } + + func testWithoutArguments() { + assertNoError { + let dbQueue = try makeDatabaseQueue() + let expression = SQLColumn("foo").collating("NOCASE") == "'bar'" && SQLColumn("baz") >= 1 + let sql = try dbQueue.inDatabase { db -> String in + var arguments: StatementArguments? = nil + return try expression.sql(db, &arguments) + } + XCTAssertEqual(sql, "((\"foo\" = '''bar''' COLLATE NOCASE) AND (\"baz\" >= 1))") + } + } +}