From a7acd50159f2fee85bf46ad93171ceaa5364ac6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 15 Dec 2016 17:26:23 +0100 Subject: [PATCH] StatementArguments.append(contentsOf:) --- GRDB/Core/Statement.swift | 44 +++++++++++++++++++++++++++++++++++++-- TODO.md | 2 ++ 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index a1fcf635d..98dc0ab1a 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -559,6 +559,46 @@ public struct StatementArguments { } + // MARK: Adding arguments + + /// Use this method to append or replace arguments. + /// + /// var arguments: StatementArguments = [1] + /// arguments.append(contentsOf: [2, 3]) + /// print(arguments) + /// // Prints [1, 2, 3] + /// + /// // Builds the ["foo": 2, "bar": 3] arguments + /// var arguments: StatementArguments = ["foo": 1] + /// arguments.append(contentsOf: ["foo": 2, "bar": 3]) + /// print(arguments) + /// // Prints [foo:2, bar:3] + /// + /// This method can build arguments that mix named and positional arguments: + /// + /// var arguments: StatementArguments = ["foo": 1] + /// arguments.append(contentsOf: [2, 3]) + /// print(arguments) + /// // Prints [foo:1, 2, 3] + /// + /// When arguments mix named and positional elements, statements prefer + /// named arguments (which can be reused) over positional ones (which are + /// never reused). For example: + /// + /// var arguments: StatementArguments = ["foo": 1] + /// arguments.append(contentsOf: [2, 3]) // [foo:1, 2, 3] + /// let sql = "SELECT ? AS a, :foo AS foo, ? AS c, :foo AS foo2" + /// let row = try Row.fetchOne(db, sql, arguments: arguments)! + /// print(row) + /// // Prints + public mutating func append(contentsOf arguments: StatementArguments) { + self.values.append(contentsOf: arguments.values) + for (key, value) in arguments.namedValues { + self.namedValues.updateValue(value, forKey: key) + } + } + + // MARK: Not Public var values: [DatabaseValue] = [] @@ -616,8 +656,8 @@ extension StatementArguments : CustomStringConvertible { public var description: String { let valuesDescriptions = values.map { $0.description } let namedValuesDescriptions = namedValues.map { (key, value) -> String in - return "\(key):\(value))" + return "\(key):\(value)" } - return "[" + (valuesDescriptions + namedValuesDescriptions).joined(separator: ", ") + "]" + return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]" } } diff --git a/TODO.md b/TODO.md index e67b4d405..736c1036e 100644 --- a/TODO.md +++ b/TODO.md @@ -1,3 +1,5 @@ +- [ ] Document StatementArguments.append(contentsOf:) +- [ ] Test StatementArguments.append(contentsOf:) - [ ] Request.bound(to:adapter:) (requires adapters to be able to adapt an already adapted row) - [ ] Think about supporting Cursor's underestimatedCount, which could speed up Array(cursor) and fetchAll() - [ ] FetchedRecordsController: handle fetch errors