From 15b892af6e2754acf3f439e651e7b66c9538dfee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 17 Feb 2021 08:45:57 +0100 Subject: [PATCH 01/35] Implement filters with SQLExpression? instead of [SQLExpression] Those arrays were introduced so that we can generate nicer sql: `a AND b AND c`, instead of `(a AND b) AND c`. This flattening is provided by the && operator and `SQLExpression.associativeBinary`, so those arrays are no longer needed. --- GRDB/QueryInterface/SQL/SQLExpression.swift | 20 ----- GRDB/QueryInterface/SQL/SQLQuery.swift | 13 +-- GRDB/QueryInterface/SQL/SQLRelation.swift | 64 +++++++------- .../SQLGeneration/SQLQueryGenerator.swift | 83 ++++++++----------- 4 files changed, 76 insertions(+), 104 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 5a470c64f..7dcf92b75 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -980,26 +980,6 @@ extension SQLExpression { } } -extension SQLExpression { - /// Returns true iff the expression is trivially true. - /// - /// When in doubt, returns false. - /// - /// This property helps clearing up the JOIN clauses. - var isTrue: Bool { - switch impl { - case .databaseValue(true.databaseValue): - return true - - case let .collated(expression, _): - return expression.isTrue - - default: - return false - } - } -} - extension SQLExpression { /// Returns a qualified expression func qualified(with alias: TableAlias) -> SQLExpression { diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index ba461f740..8a2915ab1 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -5,10 +5,7 @@ struct SQLQuery { var relation: SQLRelation var isDistinct: Bool = false var groupPromise: DatabasePromise<[SQLExpression]>? - // Having clause is an array of expressions that we'll join with - // the AND operator. This gives nicer output in generated SQL: - // `(a AND b AND c)` instead of `((a AND b) AND c)`. - var havingExpressionsPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: []) + var havingExpressionPromise: DatabasePromise = DatabasePromise(value: nil) var limit: SQLLimit? var ctes: OrderedDictionary = [:] } @@ -65,9 +62,13 @@ extension SQLQuery: AggregatingRequest { } func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - map(\.havingExpressionsPromise) { havingExpressionsPromise in + map(\.havingExpressionPromise) { promise in DatabasePromise { db in - try havingExpressionsPromise.resolve(db) + [predicate(db).sqlExpression] + if let filter = try promise.resolve(db) { + return try filter && predicate(db) + } else { + return try predicate(db).sqlExpression + } } } } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 50459e48a..2a724ec05 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -13,21 +13,19 @@ /// • selection /// /// Other SQL clauses such as GROUP BY, LIMIT are defined one level up, in the -/// SQLQuery type. +/// `SQLQuery` type. /// /// ## Promises /// -/// Filter and ordering are actually "promises", which are only resolved -/// when a database connection is available. This is how we can implement -/// requests such as `Record.filter(key: 1)` or `Record.orderByPrimaryKey()`: -/// both need a database connection in order to introspect the primary key. +/// Selection, filter, and ordering are "promises" which are resolved when a +/// database connection is available. This is how we can implement requests such +/// as `Record.filter(key: 1)` or `Record.orderByPrimaryKey()`: both need a +/// database connection in order to introspect the primary key. For example: /// -/// // SELECT * FROM player -/// // WHERE continent = 'EU' -/// // ORDER BY code -- primary key infered from the database schema -/// Country -/// .filter(Column("continent") == "EU") -/// .orderByPrimaryKey() +/// // SELECT * FROM country ORDER BY code +/// // ~~~~~~~~~~~~~ +/// // primary key infered from the database schema +/// Country.orderByPrimaryKey() /// /// ## Children /// @@ -159,13 +157,11 @@ struct SQLRelation { var source: SQLSource var selectionPromise: DatabasePromise<[SQLSelection]> = DatabasePromise(value: []) - // Filter is an array of expressions that we'll join with the AND operator. - // This gives nicer output in generated SQL: `(a AND b AND c)` instead of - // `((a AND b) AND c)`. - var filtersPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: []) + var filterPromise: DatabasePromise = DatabasePromise(value: nil) var ordering: SQLRelation.Ordering = SQLRelation.Ordering() var children: OrderedDictionary = [:] + /// All prefetched associations (`including(all:)`), recursively var prefetchedAssociations: [_SQLAssociation] { children.flatMap { key, child -> [_SQLAssociation] in switch child.kind { @@ -247,9 +243,13 @@ extension SQLRelation: Refinable { extension SQLRelation: FilteredRequest { func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - map(\.filtersPromise) { filtersPromise in + map(\.filterPromise) { promise in DatabasePromise { db in - try filtersPromise.resolve(db) + [predicate(db).sqlExpression] + if let filter = try promise.resolve(db) { + return try filter && predicate(db) + } else { + return try predicate(db).sqlExpression + } } } } @@ -555,11 +555,11 @@ enum SQLAssociationCondition { /// player[Column("id")] == bonus[Column("playerID")] /// }) /// Player.with(bonus).joining(required: association) - case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpression) + case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpression?) /// The condition that does not constrain the two associated tables /// in any way. - static let none = expression({ _, _ in true.sqlExpression }) + static let none = expression({ _, _ in nil }) func reversed(to destinationTable: String) -> SQLAssociationCondition { switch self { @@ -570,19 +570,19 @@ enum SQLAssociationCondition { } } - func joinExpressions( + func joinExpression( _ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) - throws -> [SQLExpression] + throws -> SQLExpression? { switch self { case let .expression(condition): - return [condition(leftAlias, rightAlias)] + return condition(leftAlias, rightAlias) case let .foreignKey(foreignKey): return try foreignKey .joinMapping(db, from: leftAlias.tableName) - .joinExpressions(leftAlias: leftAlias, rightAlias: rightAlias) + .joinExpression(leftAlias: leftAlias, rightAlias: rightAlias) } } } @@ -718,7 +718,7 @@ extension JoinMapping { } } - /// Resolves the condition into SQL expressions which involve both left + /// Resolves the condition into an SQL expression which involve both left /// and right tables. /// /// SELECT * FROM left JOIN right ON (right.a = left.b) @@ -728,10 +728,8 @@ extension JoinMapping { /// JOIN operator. /// - parameter rightAlias: A TableAlias for the table on the right of the /// JOIN operator. - /// - Returns: An array of SQL expression that should be joined with - /// the AND operator and qualified with the right table. - func joinExpressions(leftAlias: TableAlias, rightAlias: TableAlias) -> [SQLExpression] { - map { rightAlias[$0.right] == leftAlias[$0.left] } + func joinExpression(leftAlias: TableAlias, rightAlias: TableAlias) -> SQLExpression { + map { rightAlias[$0.right] == leftAlias[$0.left] }.joined(operator: .and) } } @@ -791,8 +789,12 @@ extension SQLRelation { return nil } - let mergedFiltersPromise = DatabasePromise<[SQLExpression]> { db in - try self.filtersPromise.resolve(db) + other.filtersPromise.resolve(db) + let mergedFilterPromise = DatabasePromise { db in + switch try (self.filterPromise.resolve(db), other.filterPromise.resolve(db)) { + case let (lhs?, rhs?): return lhs && rhs + case let (nil, expr?), let (expr?, nil): return expr + case (nil, nil): return nil + } } var mergedChildren: OrderedDictionary = [:] @@ -827,7 +829,7 @@ extension SQLRelation { return SQLRelation( source: mergedSource, selectionPromise: mergedSelectionPromise, - filtersPromise: mergedFiltersPromise, + filterPromise: mergedFilterPromise, ordering: mergedOrdering, children: mergedChildren) } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 5df7d302a..58f203e82 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -3,7 +3,7 @@ struct SQLQueryGenerator: Refinable { fileprivate private(set) var relation: SQLQualifiedRelation private let isDistinct: Bool private let groupPromise: DatabasePromise<[SQLExpression]>? - private let havingExpressionsPromise: DatabasePromise<[SQLExpression]> + private let havingExpressionPromise: DatabasePromise private let limit: SQLLimit? private let singleResult: Bool private let ctes: OrderedDictionary @@ -49,7 +49,7 @@ struct SQLQueryGenerator: Refinable { groupPromise = query.groupPromise?.map { $0.map { $0.qualified(with: sourceAlias) } } - havingExpressionsPromise = query.havingExpressionsPromise.map { + havingExpressionPromise = query.havingExpressionPromise.map { $0.map { $0.qualified(with: sourceAlias) } } @@ -88,12 +88,10 @@ struct SQLQueryGenerator: Refinable { } } - let filters = try relation.filtersPromise.resolve(context.db) - if filters.isEmpty == false { + let filter = try relation.filterPromise.resolve(context.db) + if let filter = filter { sql += " WHERE " - sql += try filters - .joined(operator: .and) - .sql(context) + sql += try filter.sql(context) } let groupExpressions = try groupPromise?.resolve(context.db) ?? [] @@ -104,12 +102,9 @@ struct SQLQueryGenerator: Refinable { .joined(separator: ", ") } - let havingExpressions = try havingExpressionsPromise.resolve(context.db) - if havingExpressions.isEmpty == false { + if let havingExpression = try havingExpressionPromise.resolve(context.db) { sql += " HAVING " - sql += try havingExpressions - .joined(operator: .and) - .sql(context) + sql += try havingExpression.sql(context) } let orderings = try relation.ordering.resolve(context.db) @@ -124,7 +119,7 @@ struct SQLQueryGenerator: Refinable { if try singleResult && !expectsSingleResult( context.db, selection: selection, - filters: filters, + filter: filter, groupExpressions: groupExpressions) { limit = SQLLimit(limit: 1, offset: limit?.offset) @@ -204,8 +199,9 @@ struct SQLQueryGenerator: Refinable { } // The filter knows better - let filter = try relation.filtersPromise.resolve(db).joined(operator: .and) - guard let rowIDs = try filter.identifyingRowIDs(db, for: relation.source.alias) else { + guard let filter = try relation.filterPromise.resolve(db), + let rowIDs = try filter.identifyingRowIDs(db, for: relation.source.alias) + else { return selectedRegion } @@ -219,7 +215,7 @@ struct SQLQueryGenerator: Refinable { private func expectsSingleResult( _ db: Database, selection: [SQLSelection], - filters: [SQLExpression], + filter: SQLExpression?, groupExpressions: [SQLExpression]) throws -> Bool { @@ -230,14 +226,12 @@ struct SQLQueryGenerator: Refinable { // Do we filter on a unique key? let tableName = relation.source.tableName - if try db.tableExists(tableName) { // skip views - let identifyingColums = try filters - .joined(operator: .and) - .identifyingColums(db, for: relation.source.alias) - if try db.table(tableName, hasUniqueKey: identifyingColums) { - // Filter by unique key: guaranteed single row! - return true - } + if try db.tableExists(tableName), // skip views + let identifyingColums = try filter?.identifyingColums(db, for: relation.source.alias), + try db.table(tableName, hasUniqueKey: identifyingColums) + { + // Filter by unique key: guaranteed single row! + return true } // Do we aggregate without grouping? @@ -261,12 +255,9 @@ struct SQLQueryGenerator: Refinable { var sql = try commonTableExpressionsPrefix(context) sql += try "DELETE FROM " + relation.source.sql(context) - let filters = try relation.filtersPromise.resolve(db) - if filters.isEmpty == false { + if let filter = try relation.filterPromise.resolve(db) { sql += " WHERE " - sql += try filters - .joined(operator: .and) - .sql(context) + sql += try filter.sql(context) } if let limit = limit { @@ -350,12 +341,9 @@ struct SQLQueryGenerator: Refinable { .map { try $0.sql(context) } .joined(separator: ", ") - let filters = try relation.filtersPromise.resolve(db) - if filters.isEmpty == false { + if let filter = try relation.filterPromise.resolve(db) { sql += " WHERE " - sql += try filters - .joined(operator: .and) - .sql(context) + sql += try filter.sql(context) } if let limit = limit { @@ -576,8 +564,8 @@ private struct SQLQualifiedRelation { /// /// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ... /// | - /// • filtersPromise - let filtersPromise: DatabasePromise<[SQLExpression]> + /// • filterPromise + let filterPromise: DatabasePromise /// The ordering of source, not including ordering of joined relations private let sourceOrdering: SQLRelation.Ordering @@ -615,7 +603,7 @@ private struct SQLQualifiedRelation { sourceSelectionPromise = relation.selectionPromise.map { $0.map { $0.qualified(with: sourceAlias) } } - filtersPromise = relation.filtersPromise.map { + filterPromise = relation.filterPromise.map { $0.map { $0.qualified(with: sourceAlias) } } sourceOrdering = relation.ordering.qualified(with: sourceAlias) @@ -780,19 +768,20 @@ private struct SQLQualifiedJoin: Refinable { // JOIN table... var sql = try "\(kind.rawValue) \(relation.source.sql(context))" - // ... ON + // ... ON AND let rightAlias = relation.source.alias - var conditions = try condition.joinExpressions(context.db, - leftAlias: leftAlias, - rightAlias: rightAlias) + var conditions: [SQLExpression] = [] - // ... AND - conditions += try relation.filtersPromise - .resolve(context.db) - .map { $0.qualified(with: rightAlias) } + if let expression = try condition.joinExpression(context.db, + leftAlias: leftAlias, + rightAlias: rightAlias) + { + conditions.append(expression) + } - // Avoid generating on ON clause for trivially true conditions - conditions = conditions.filter { !$0.isTrue } + if let filter = try relation.filterPromise.resolve(context.db) { + conditions.append(filter.qualified(with: rightAlias)) + } if conditions.isEmpty == false { sql += " ON " From 488849535e04b2a3a09fc27154fa2ee7c6913961 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 17 Feb 2021 13:22:28 +0100 Subject: [PATCH 02/35] CommonTableExpression has an implicit Void RowDecoder --- .../Request/CommonTableExpression.swift | 158 ++++++++++++++++-- .../CommonTableExpressionTests.swift | 78 +++++---- 2 files changed, 194 insertions(+), 42 deletions(-) diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index de5487bb5..bb9f3d52b 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -6,13 +6,47 @@ public struct CommonTableExpression { /// For example: /// /// // WITH answer AS (SELECT 42) ... - /// let answer = CommonTableExpression( + /// let answer = CommonTableExpression( /// named: "answer", /// sql: "SELECT 42") /// answer.tableName // "answer" public var tableName: String var cte: SQLCTE + + /// Creates a common table expression from a request. + /// + /// For example: + /// + /// // WITH p AS (SELECT * FROM player) ... + /// let p = CommonTableExpression( + /// named: "p", + /// request: Player.all()) + /// + /// // WITH p AS (SELECT * FROM player) ... + /// let p = CommonTableExpression( + /// named: "p", + /// request: SQLRequest(sql: "SELECT * FROM player")) + /// + /// - parameter recursive: Whether this common table expression needs a + /// `WITH RECURSIVE` sql clause. + /// - parameter tableName: The table name of the common table expression. + /// - parameter columns: The columns of the common table expression. If nil, + /// the columns are the columns of the request. + /// - parameter request: A request. + private init( + recursive: Bool = false, + named tableName: String, + columns: [String]? = nil, + request: Request, + type: RowDecoder.Type) + { + self.tableName = tableName + self.cte = SQLCTE( + columns: columns, + sqlSubquery: request.sqlSubquery, + isRecursive: recursive) + } } extension CommonTableExpression { @@ -43,11 +77,11 @@ extension CommonTableExpression { request: Request) { self.init( - tableName: tableName, - cte: SQLCTE( - columns: columns, - sqlSubquery: request.sqlSubquery, - isRecursive: recursive)) + recursive: recursive, + named: tableName, + columns: columns, + request: request, + type: RowDecoder.self) } /// Creates a common table expression from an SQL string and @@ -79,7 +113,8 @@ extension CommonTableExpression { recursive: recursive, named: tableName, columns: columns, - request: SQLRequest(sql: sql, arguments: arguments)) + request: SQLRequest(sql: sql, arguments: arguments), + type: RowDecoder.self) } /// Creates a common table expression from an `SQLLiteral`. @@ -107,7 +142,106 @@ extension CommonTableExpression { recursive: recursive, named: tableName, columns: columns, - request: SQLRequest(literal: sqlLiteral)) + request: SQLRequest(literal: sqlLiteral), + type: RowDecoder.self) + } +} + +extension CommonTableExpression where RowDecoder == Void { + /// Creates a common table expression from a request. + /// + /// For example: + /// + /// // WITH p AS (SELECT * FROM player) ... + /// let p = CommonTableExpression( + /// named: "p", + /// request: Player.all()) + /// + /// // WITH p AS (SELECT * FROM player) ... + /// let p = CommonTableExpression( + /// named: "p", + /// request: SQLRequest(sql: "SELECT * FROM player")) + /// + /// - parameter recursive: Whether this common table expression needs a + /// `WITH RECURSIVE` sql clause. + /// - parameter tableName: The table name of the common table expression. + /// - parameter columns: The columns of the common table expression. If nil, + /// the columns are the columns of the request. + /// - parameter request: A request. + public init( + recursive: Bool = false, + named tableName: String, + columns: [String]? = nil, + request: Request) + { + self.init( + recursive: recursive, + named: tableName, + columns: columns, + request: request, + type: Void.self) + } + + /// Creates a common table expression from an SQL string and + /// optional arguments. + /// + /// For example: + /// + /// // WITH p AS (SELECT * FROM player WHERE name = 'O''Brien') ... + /// let p = CommonTableExpression( + /// named: "p", + /// sql: "SELECT * FROM player WHERE name = ?", + /// arguments: ["O'Brien"]) + /// + /// - parameter recursive: Whether this common table expression needs a + /// `WITH RECURSIVE` sql clause. + /// - parameter tableName: The table name of the common table expression. + /// - parameter columns: The columns of the common table expression. If nil, + /// the columns are the columns of the request. + /// - parameter sql: An SQL query. + /// - parameter arguments: Statement arguments. + public init( + recursive: Bool = false, + named tableName: String, + columns: [String]? = nil, + sql: String, + arguments: StatementArguments = StatementArguments()) + { + self.init( + recursive: recursive, + named: tableName, + columns: columns, + request: SQLRequest(sql: sql, arguments: arguments), + type: Void.self) + } + + /// Creates a common table expression from an `SQLLiteral`. + /// + /// For example: + /// + /// // WITH p AS (SELECT * FROM player WHERE name = 'O''Brien') ... + /// let p = CommonTableExpression( + /// named: "p", + /// literal: "SELECT * FROM player WHERE name = \("O'Brien")") + /// + /// - parameter recursive: Whether this common table expression needs a + /// `WITH RECURSIVE` sql clause. + /// - parameter tableName: The table name of the common table expression. + /// - parameter columns: The columns of the common table expression. If nil, + /// the columns are the columns of the request. + /// - parameter sqlLiteral: An SQLLiteral. + public init( + recursive: Bool = false, + named tableName: String, + columns: [String]? = nil, + literal sqlLiteral: SQLLiteral) + { + self.init( + recursive: recursive, + named: tableName, + columns: columns, + request: SQLRequest(literal: sqlLiteral), + type: Void.self) } } @@ -137,7 +271,7 @@ extension CommonTableExpression { /// // WITH answer AS (SELECT 42 AS value) /// // SELECT * FROM player /// // WHERE score = (SELECT * FROM answer) - /// let answer = CommonTableExpression( + /// let answer = CommonTableExpression( /// named: "answer", /// sql: "SELECT 42 AS value") /// let players = try Player @@ -151,7 +285,7 @@ extension CommonTableExpression { /// An SQL expression that checks the inclusion of an expression in a /// common table expression. /// - /// let playerNameCTE = CommonTableExpression( + /// let playerNameCTE = CommonTableExpression( /// named: "playerName", /// request: Player.select(Column("name")) /// @@ -288,7 +422,7 @@ extension QueryInterfaceRequest { /// .annotated(with: max(Column("date"))) /// .group(Column("chatID")) /// - /// let latestMessageCTE = CommonTableExpression( + /// let latestMessageCTE = CommonTableExpression( /// named: "latestMessage", /// request: latestMessageRequest) /// @@ -327,7 +461,7 @@ extension TableRecord { /// .annotated(with: max(Column("date"))) /// .group(Column("chatID")) /// - /// let latestMessageCTE = CommonTableExpression( + /// let latestMessageCTE = CommonTableExpression( /// named: "latestMessage", /// request: latestMessageRequest) /// diff --git a/Tests/GRDBTests/CommonTableExpressionTests.swift b/Tests/GRDBTests/CommonTableExpressionTests.swift index 8772b45cf..b024203b5 100644 --- a/Tests/GRDBTests/CommonTableExpressionTests.swift +++ b/Tests/GRDBTests/CommonTableExpressionTests.swift @@ -2,6 +2,24 @@ import XCTest import GRDB class CommonTableExpressionTests: GRDBTestCase { + func testInitializers() { + // Implicit Void + _ = CommonTableExpression(named: "foo", sql: "") + _ = CommonTableExpression(named: "foo", literal: "") + _ = CommonTableExpression(named: "foo", request: SQLRequest("")) + + // Explicit Void + _ = CommonTableExpression(named: "foo", sql: "") + _ = CommonTableExpression(named: "foo", literal: "") + _ = CommonTableExpression(named: "foo", request: SQLRequest("")) + + // Explicit type + struct S { } + _ = CommonTableExpression(named: "foo", sql: "") + _ = CommonTableExpression(named: "foo", literal: "") + _ = CommonTableExpression(named: "foo", request: SQLRequest("")) + } + func testQuery() throws { struct T: TableRecord { } try makeDatabaseQueue().write { db in @@ -11,7 +29,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Just add a WITH clause: sql + arguments do { - let cte = CommonTableExpression( + let cte = CommonTableExpression( named: "cte", sql: "SELECT ?", arguments: ["O'Brien"]) @@ -25,7 +43,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Just add a WITH clause: sql interpolation do { - let cte = CommonTableExpression( + let cte = CommonTableExpression( named: "cte", literal: "SELECT \("O'Brien")") let request = T.all() @@ -39,7 +57,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Just add a WITH clause: query interface request do { let cteRequest = T.all() - let cte = CommonTableExpression(named: "cte", request: cteRequest) + let cte = CommonTableExpression(named: "cte", request: cteRequest) let request = T.all() .with(cte) try assertEqualSQL(db, request, """ @@ -51,7 +69,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Just add a WITH clause: sql request do { let cteRequest: SQLRequest = "SELECT \("O'Brien")" - let cte = CommonTableExpression(named: "cte", request: cteRequest) + let cte = CommonTableExpression(named: "cte", request: cteRequest) let request = T.all() .with(cte) try assertEqualSQL(db, request, """ @@ -62,7 +80,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Include query interface request as a CTE do { - let cte = CommonTableExpression(named: "cte", request: T.all()) + let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .including(optional: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] })) @@ -76,7 +94,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Include SQL request as a CTE do { - let cte = CommonTableExpression( + let cte = CommonTableExpression( named: "cte", literal: "SELECT 1 as id") let request = T.all() @@ -92,7 +110,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Include a filtered SQL request as a CTE do { - let cte = CommonTableExpression( + let cte = CommonTableExpression( named: "cte", literal: "SELECT 1 AS a") let request = T.all() @@ -108,7 +126,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Include SQL request as a CTE (empty columns) do { - let cte = CommonTableExpression( + let cte = CommonTableExpression( named: "cte", columns: [], literal: "SELECT 1 AS id") @@ -125,7 +143,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Include SQL request as a CTE (custom column name) do { - let cte = CommonTableExpression( + let cte = CommonTableExpression( named: "cte", columns: ["id", "a"], literal: "SELECT 1, 2") @@ -142,7 +160,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Include SQL request as a CTE (empty ON clause) do { - let cte = CommonTableExpression( + let cte = CommonTableExpression( named: "cte", literal: "SELECT \("O'Brien")") let request = T.all() @@ -158,7 +176,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Join query interface request as a CTE do { - let cte = CommonTableExpression(named: "cte", request: T.all()) + let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .joining(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] })) @@ -172,7 +190,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Include filtered CTE do { - let cte = CommonTableExpression(named: "cte", request: T.all()) + let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .including(required: T.association(to: cte).filter(Column("id") > 0)) @@ -186,7 +204,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Include ordered CTE do { - let cte = CommonTableExpression(named: "cte", request: T.all()) + let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .including(required: T.association(to: cte).order(Column("id"))) @@ -201,7 +219,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Aliased CTE do { - let cte = CommonTableExpression(named: "cte", request: T.all()) + let cte = CommonTableExpression(named: "cte", request: T.all()) let alias = TableAlias() let request = T.all() .with(cte) @@ -218,7 +236,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Include one CTE twice with same key and condition do { - let cte = CommonTableExpression(named: "cte", request: T.all()) + let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .including(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] })) @@ -233,7 +251,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Include one CTE twice with same key but different condition (last condition wins) do { - let cte = CommonTableExpression(named: "cte", request: T.all()) + let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .including(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] })) @@ -248,7 +266,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Include one CTE twice with different keys do { - let cte = CommonTableExpression(named: "cte", request: T.all()) + let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .including(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] }).forKey("a")) @@ -291,7 +309,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Use CTE as a subquery do { - let cte = CommonTableExpression(named: "cte", request: T.all()) + let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .annotated(with: cte.all()) @@ -303,7 +321,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Use CTE as a collection do { - let cte = CommonTableExpression(named: "cte", request: T.all()) + let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .filter(cte.contains(Column("id"))) @@ -317,7 +335,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Use filtered CTE as a subquery do { - let cte = CommonTableExpression(named: "cte", request: T.all()) + let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .annotated(with: cte.all().filter(Column("id") > 1)) @@ -330,7 +348,7 @@ class CommonTableExpressionTests: GRDBTestCase { // Select from a CTE do { - let cte = CommonTableExpression(named: "cte", request: T.all()) + let cte = CommonTableExpression(named: "cte", request: T.all()) let request = cte.all().with(cte) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ @@ -372,7 +390,7 @@ class CommonTableExpressionTests: GRDBTestCase { t.autoIncrementedPrimaryKey("id") t.column("score", .integer) } - let answer = CommonTableExpression( + let answer = CommonTableExpression( named: "answer", sql: "SELECT 42 AS value") let request = Player @@ -430,7 +448,7 @@ class CommonTableExpressionTests: GRDBTestCase { .annotated(with: max(Column("date"))) .group(Column("chatID")) - let latestPostCTE = CommonTableExpression( + let latestPostCTE = CommonTableExpression( named: "latestPost", request: latestPostRequest) @@ -490,7 +508,7 @@ class CommonTableExpressionTests: GRDBTestCase { func testInterpolation() throws { try makeDatabaseQueue().read { db in do { - let cte = CommonTableExpression( + let cte = CommonTableExpression( named: "cte", literal: "SELECT \("O'Brien")") let request: SQLRequest = """ @@ -503,7 +521,7 @@ class CommonTableExpressionTests: GRDBTestCase { """) } do { - let cte = CommonTableExpression( + let cte = CommonTableExpression( named: "cte", literal: "SELECT \("O'Brien")") let request: SQLRequest = """ @@ -516,7 +534,7 @@ class CommonTableExpressionTests: GRDBTestCase { """) } do { - let cte = CommonTableExpression( + let cte = CommonTableExpression( named: "cte", columns: [], literal: "SELECT \("O'Brien")") @@ -530,7 +548,7 @@ class CommonTableExpressionTests: GRDBTestCase { """) } do { - let cte = CommonTableExpression( + let cte = CommonTableExpression( named: "cte", columns: ["name"], literal: "SELECT \("O'Brien")") @@ -544,7 +562,7 @@ class CommonTableExpressionTests: GRDBTestCase { """) } do { - let cte = CommonTableExpression( + let cte = CommonTableExpression( named: "cte", columns: ["name", "score"], literal: "SELECT \("O'Brien"), 12") @@ -567,7 +585,7 @@ class CommonTableExpressionTests: GRDBTestCase { } struct T: Encodable, PersistableRecord { } - let cte = CommonTableExpression(named: "cte", sql: "SELECT 1") + let cte = CommonTableExpression(named: "cte", sql: "SELECT 1") try T.with(cte).updateAll(db, Column("a").set(to: cte.all())) XCTAssertEqual(lastSQLQuery, """ @@ -583,7 +601,7 @@ class CommonTableExpressionTests: GRDBTestCase { } struct T: Encodable, PersistableRecord { } - let cte = CommonTableExpression(named: "cte", sql: "SELECT 1") + let cte = CommonTableExpression(named: "cte", sql: "SELECT 1") try T.with(cte) .filter(cte.contains(Column("a"))) From 7eaf579c18e898ca7e5167a7564255396975178c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 17 Feb 2021 13:44:51 +0100 Subject: [PATCH 03/35] Update CommonTableExpression documentation about the implicit Void RowDecoder --- Documentation/CommonTableExpressions.md | 78 ++++++++++++++----------- 1 file changed, 45 insertions(+), 33 deletions(-) diff --git a/Documentation/CommonTableExpressions.md b/Documentation/CommonTableExpressions.md index 37fd28c47..585f5e9c7 100644 --- a/Documentation/CommonTableExpressions.md +++ b/Documentation/CommonTableExpressions.md @@ -29,7 +29,7 @@ The CTE request can be provided as a [query interface request]: ```swift // WITH playerName AS (SELECT name FROM player) ... -let playerNameCTE = CommonTableExpression( +let playerNameCTE = CommonTableExpression( named: "playerName", request: Player.select(Column("name"))) ``` @@ -40,18 +40,18 @@ You can feed a CTE with raw SQL as well (second and third examples use [SQL Inte let name = "O'Brien" // WITH playerName AS (SELECT 'O''Brien') ... -let playerNameCTE = CommonTableExpression( +let playerNameCTE = CommonTableExpression( named: "playerName", sql: "SELECT ?", arguments: [name]) // WITH playerName AS (SELECT 'O''Brien') ... -let playerNameCTE = CommonTableExpression( +let playerNameCTE = CommonTableExpression( named: "playerName", literal: "SELECT \(name)") // WITH playerName AS (SELECT 'O''Brien') ... let request: SQLRequest = "SELECT \(name)" -let playerNameCTE = CommonTableExpression( +let playerNameCTE = CommonTableExpression( named: "playerName", request: requests) ``` @@ -60,7 +60,7 @@ All CTEs can be provided with explicit column names: ```swift // WITH pair(a, b) AS (SELECT 1, 2) ... -let pairCTE = CommonTableExpression( +let pairCTE = CommonTableExpression( named: "pair", columns: ["a", "b"], sql: "SELECT 1, 2") @@ -71,7 +71,7 @@ Recursive CTEs need the `recursive` flag. The example below selects all integers ```swift // WITH RECURSIVE counter(x) AS // (VALUES(1) UNION ALL SELECT x+1 FROM counter WHERE x<1000) -let counterCTE = CommonTableExpression( +let counterCTE = CommonTableExpression( recursive: true, named: "counter", columns: ["x"], @@ -84,8 +84,6 @@ let counterCTE = CommonTableExpression( > :point_up: **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs. -As you can see in all above examples, `CommonTableExpression` is a generic type: `CommonTableExpression`, `CommonTableExpression`. The generic argument (`Void`, `Int`) turns useful when you [join common table expressions](#associations-to-common-table-expressions), or when you [fetch values directly from a common table expression](#fetch-values-from-common-table-expressions). Otherwise, you can just use `Void`. - ## Embed Common Table Expressions in Requests @@ -103,7 +101,7 @@ We first build a `CommonTableExpression`: ```swift let name = "O'Brien" -let playerNameCTE = CommonTableExpression( +let playerNameCTE = CommonTableExpression( named: "playerName", literal: "SELECT \(name)") ``` @@ -184,11 +182,34 @@ try Player In the previous chapter, a common table expression was embedded as a subquery, with the `CommonTableExpression.all()` method. -`all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests. You can also fetch from it, but only as long as it is provided with the definition of the CTE. +`all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests. -This will generally give requests of the form `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`. +You can also fetch from it, but only as long as it is provided with the definition of the CTE. This will generally give requests of the form `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`: -The generic type of `CommonTableExpression<...>` now turns out useful, so that you can fetch the desired outcome (database [rows](../README.md#row-queries), simple [values](../README.md#value-queries), or custom [records](../README.md#records)). +```swift +let cte = CommonTableExpression(...) +let request = cte.all().with(cte) +``` + +This request, of type `QueryInterfaceRequest`, doesn't quite know what to fetch and how. You must help it so that it can actually fetch database [rows](../README.md#row-queries), simple [values](../README.md#value-queries), or custom [records](../README.md#records). You have two possible options: + +1. Use the `asRequest(of:)` method: + + ```swift + let cte = CommonTableExpression(...) + let request = cte.all().with(cte).asRequest(of: Player.self) + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + let players = try request.fetchAll(db) + ``` + +2. Provide the fetched type to the cte itself: + + ```swift + let cte = CommonTableExpression(...) + // ~~~~~~~~ + let request = cte.all().with(cte) + let players = try request.fetchAll(db) + ``` For example, let's fetch a range of integer: @@ -215,17 +236,6 @@ let values = try dbQueue.read { db in print(values) // prints "[3, 4, 5, 6, 7]" ``` -When you have to fetch from a `CommonTableExpression` which does not have the desired generic type, you can still use the `asRequest(of:)` method: - -```swift -let cte: CommonTableExpression = ... -let rows: [Row] = try dbQueue.read { db in - try cte.all().with(cte) - .asRequest(of: Row.self) - .fetchAll(db) -} -``` - ## Associations to Common Table Expressions @@ -337,7 +347,7 @@ We can now define the CTE for the latest messages: ```swift // WITH latestMessage AS // (SELECT *, MAX(date) FROM message GROUP BY chatID) -let latestMessageCTE = CommonTableExpression( +let latestMessageCTE = CommonTableExpression( named: "latestMessage", request: latestMessageRequest) ``` @@ -378,9 +388,9 @@ And we can fetch the data that feeds our application screen: let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll) ``` -> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, our go-to `CommonTableExpression` CTEs can work against type safety. So when you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your `CommonTableExpression` with a type instead of `Void`. +> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, anonymous `CommonTableExpression` CTEs can work against type safety. When you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your common table expressions with an explicit type: `CommonTableExpression`. > -> You can use an existing record type, or an ad-hoc enum. For example: +> To do so, you can use an existing record type, or an ad-hoc enum. For example: > > ```swift > enum CTE1 { } @@ -389,9 +399,9 @@ let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll) > enum CTE2 { } > let cte2 = CommonTableExpression(...) > -> let assoc1 = BaseRecord.association(to: cte1, on: ...) -> let assoc2 = cte1.association(to: cte2, on: ...) -> let assoc3 = cte2.association(to: FarRecord.self, on: ...) +> let assoc1 = BaseRecord.association(to: cte1, on: ...) // from BaseRecord to CTE1 +> let assoc2 = cte1.association(to: cte2, on: ...) // from CTE1 to CTE2 +> let assoc3 = cte2.association(to: FarRecord.self, on: ...) // from CTE2 to FarRecord > > // WITH ... > // SELECT base.* FROM base @@ -400,12 +410,14 @@ let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll) > // JOIN far ON ... > let request = BaseRecord > .with(cte1).with(cte2) -> .joining(required: assoc1 -> .joining(required: assoc2 -> .joining(required: assoc3))) +> .joining(required: assoc1. // OK +> .joining(required: assoc2. // OK +> .joining(required: assoc3))) // OK > > // Compiler error -> let request = BaseRecord.joining(required: assoc2) +> let request = BaseRecord +> .joining(required: assoc2) // Not OK +> .joining(required: assoc3) // Not OK > ``` [query interface request]: ../README.md#requests From 340771559902b9f591a5f47f95251ba95cd5f8d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 17 Feb 2021 13:47:15 +0100 Subject: [PATCH 04/35] CHANGELOG --- CHANGELOG.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 924ae06b9..4efb9bb87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases +- [Development Branch](#development-branch) - `5.4.x` Releases - [5.4.0](#540) - `5.3.x` Releases - [5.3.0](#530) - `5.2.x` Releases - [5.2.0](#520) @@ -69,6 +70,18 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... + +## Development Branch + +- **New**: You can now define common table expressions without the `` generic qualifier: + + ```diff + -let cte = CommonTableExpression(...) + +let cte = CommonTableExpression(...) + ``` + + The [Common Table Expressions Guide](Documentation/CommonTableExpressions.md) was updated accordingly. + ## 5.4.0 Released February 15, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.3.0...v5.4.0) From bda63c70bf338b97c96a82d5fb60f4c6a38ef8f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 17 Feb 2021 13:51:23 +0100 Subject: [PATCH 05/35] Document the type of variables --- Documentation/CommonTableExpressions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/CommonTableExpressions.md b/Documentation/CommonTableExpressions.md index 585f5e9c7..7f9463516 100644 --- a/Documentation/CommonTableExpressions.md +++ b/Documentation/CommonTableExpressions.md @@ -199,7 +199,7 @@ This request, of type `QueryInterfaceRequest`, doesn't quite know what to let cte = CommonTableExpression(...) let request = cte.all().with(cte).asRequest(of: Player.self) // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ - let players = try request.fetchAll(db) + let players = try request.fetchAll(db) // [Player] ``` 2. Provide the fetched type to the cte itself: @@ -208,7 +208,7 @@ This request, of type `QueryInterfaceRequest`, doesn't quite know what to let cte = CommonTableExpression(...) // ~~~~~~~~ let request = cte.all().with(cte) - let players = try request.fetchAll(db) + let players = try request.fetchAll(db) // [Player] ``` For example, let's fetch a range of integer: From c4620aa58759b424d3c99b93d959a4c8c638d60b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 17 Feb 2021 17:43:57 +0100 Subject: [PATCH 06/35] SQLRelation no longer depends on SQLExpressible and _JoinableRequest Those are one level up --- .../Request/Association/Association.swift | 2 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 41 +++++++++++-------- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 7fa7a724b..676ba263c 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -160,7 +160,7 @@ extension Association { /// let association = Player.team.filter { db in true } /// var request = Player.including(required: association) public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - mapDestinationRelation { $0.filter(predicate) } + mapDestinationRelation { $0.filter { try predicate($0).sqlExpression } } } /// Creates an association with the provided *orderings promise*. diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 2a724ec05..864710f97 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -207,7 +207,13 @@ extension SQLRelation: Refinable { /// Removes all selections from chidren func selectOnly(_ selection: [SQLSelection]) -> Self { - select(selection).map(\.children, { $0.mapValues { $0.map(\.relation, { $0.selectOnly([]) }) } }) + self + .select(selection) + .map(\.children) { children in + children.mapValues { child in + child.map(\.relation) { $0.selectOnly([]) } + } + } } func annotated(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self { @@ -223,6 +229,23 @@ extension SQLRelation: Refinable { annotated(with: { _ in selection }) } + func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { + map(\.filterPromise) { promise in + DatabasePromise { db in + if let filter = try promise.resolve(db) { + return try filter && predicate(db) + } else { + return try predicate(db) + } + } + } + } + + // Convenience + func filter(_ predicate: SQLExpression) -> Self { + filter { _ in predicate } + } + func order(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self { with(\.ordering, SQLRelation.Ordering(orderings: orderings)) } @@ -241,20 +264,6 @@ extension SQLRelation: Refinable { } } -extension SQLRelation: FilteredRequest { - func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - map(\.filterPromise) { promise in - DatabasePromise { db in - if let filter = try promise.resolve(db) { - return try filter && predicate(db) - } else { - return try predicate(db).sqlExpression - } - } - } - } -} - extension SQLRelation { /// Returns a relation extended with an association. /// @@ -389,7 +398,7 @@ extension SQLRelation { } } -extension SQLRelation: _JoinableRequest { +extension SQLRelation { func _including(all association: _SQLAssociation) -> Self { appendingChild(for: association, kind: .allPrefetched) } From 0dd345eb91281ff87b18892cdc48b21fdd114397 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 17 Feb 2021 18:00:53 +0100 Subject: [PATCH 07/35] SQLQuery no longer depends on SQLExpressible and other high-level protocols --- .../Request/QueryInterfaceRequest.swift | 16 +++--- GRDB/QueryInterface/SQL/SQLQuery.swift | 51 +++++++++---------- 2 files changed, 33 insertions(+), 34 deletions(-) diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index a9b7f8ce7..506e7b56d 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -83,7 +83,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// .select { db in [Column("id")] } /// .select { db in [Column("email")] } public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { - map(\.query) { $0.select(selection) } + map(\.query) { $0.select { try selection($0).map(\.sqlSelection) } } } /// Creates a request which selects *selection*, and fetches values of @@ -97,7 +97,7 @@ extension QueryInterfaceRequest: SelectionRequest { public func select(_ selection: [SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest { - map(\.query, { $0.select(selection) }).asRequest(of: RowDecoder.self) + select(selection).asRequest(of: RowDecoder.self) } /// Creates a request which selects *selection*, and fetches values of @@ -174,7 +174,7 @@ extension QueryInterfaceRequest: SelectionRequest { /// .select([Column("id"), Column("email")]) /// .annotated(with: { db in [Column("name")] }) public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest { - map(\.query) { $0.annotated(with: selection) } + map(\.query) { $0.annotated { try selection($0).map(\.sqlSelection) } } } } @@ -186,7 +186,7 @@ extension QueryInterfaceRequest: FilteredRequest { /// var request = Player.all() /// request = request.filter { db in true } public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { - map(\.query) { $0.filter(predicate) } + map(\.query) { $0.filter { try predicate($0).sqlExpression } } } } @@ -205,7 +205,7 @@ extension QueryInterfaceRequest: OrderedRequest { /// .reversed() /// .order{ _ in [Column("name")] } public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { - map(\.query) { $0.order(orderings) } + map(\.query) { $0.order { try orderings($0).map(\.sqlOrdering) } } } /// Creates a request that reverses applied orderings. @@ -236,13 +236,13 @@ extension QueryInterfaceRequest: OrderedRequest { extension QueryInterfaceRequest: AggregatingRequest { /// Creates a request grouped according to *expressions promise*. public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest { - map(\.query) { $0.group(expressions) } + map(\.query) { $0.group { try expressions($0).map(\.sqlExpression) } } } /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { - map(\.query) { $0.having(predicate) } + map(\.query) { $0.having { try predicate($0).sqlExpression } } } } @@ -657,7 +657,7 @@ private func prefetch( } let originCTE = CommonTableExpression( named: "grdb_base", - request: originQuery) + request: SQLSubquery.query(originQuery)) let pivotRowValue = SQLExpression.rowValue(pivotColumns.map(SQLExpression.column))! let pivotFilter = originCTE.contains(pivotRowValue) diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index 8a2915ab1..0ecd19a97 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -26,25 +26,30 @@ extension SQLQuery: Refinable { } } -extension SQLQuery: SelectionRequest { - func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { - map(\.relation) { $0.select { try selection($0).map(\.sqlSelection) } } +extension SQLQuery { + func select(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self { + map(\.relation) { $0.select(selection) } } - func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self { - map(\.relation) { $0.annotated { try selection($0).map(\.sqlSelection) } } + // Convenience + func select(_ expressions: SQLExpression...) -> Self { + select { _ in expressions.map { .expression($0) } } + } + + func annotated(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self { + map(\.relation) { $0.annotated(with: selection) } } } -extension SQLQuery: FilteredRequest { - func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { - map(\.relation) { $0.filter { try predicate($0).sqlExpression } } +extension SQLQuery { + func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { + map(\.relation) { $0.filter(predicate) } } } -extension SQLQuery: OrderedRequest { - func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { - map(\.relation) { $0.order { try orderings($0).map(\.sqlOrdering) } } +extension SQLQuery { + func order(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self { + map(\.relation) { $0.order(orderings) } } func reversed() -> Self { @@ -56,25 +61,25 @@ extension SQLQuery: OrderedRequest { } } -extension SQLQuery: AggregatingRequest { - func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self { - with(\.groupPromise, DatabasePromise { db in try expressions(db).map(\.sqlExpression) }) +extension SQLQuery { + func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self { + with(\.groupPromise, DatabasePromise(expressions)) } - func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { + func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { map(\.havingExpressionPromise) { promise in DatabasePromise { db in if let filter = try promise.resolve(db) { return try filter && predicate(db) } else { - return try predicate(db).sqlExpression + return try predicate(db) } } } } } -extension SQLQuery: _JoinableRequest { +extension SQLQuery{ func _including(all association: _SQLAssociation) -> Self { map(\.relation) { $0._including(all: association) } } @@ -96,12 +101,6 @@ extension SQLQuery: _JoinableRequest { } } -extension SQLQuery: SQLSubqueryable { - var sqlSubquery: SQLSubquery { - .query(self) - } -} - extension SQLQuery { func fetchCount(_ db: Database) throws -> Int { guard groupPromise == nil && limit == nil && ctes.isEmpty else { @@ -126,9 +125,9 @@ extension SQLQuery { countQuery.isDistinct = false switch count { case .all: - countQuery = countQuery.select(SQLExpression.count(.allColumns)) + countQuery = countQuery.select(.count(.allColumns)) case .distinct(let expression): - countQuery = countQuery.select(SQLExpression.countDistinct(expression)) + countQuery = countQuery.select(.countDistinct(expression)) } return try QueryInterfaceRequest(query: countQuery).fetchOne(db)! } else { @@ -148,7 +147,7 @@ extension SQLQuery { // SELECT COUNT(*) FROM (self) func fetchTrivialCount(_ db: Database) throws -> Int { - let countRequest: SQLRequest = "SELECT COUNT(*) FROM (\(unordered()))" + let countRequest: SQLRequest = "SELECT COUNT(*) FROM (\(SQLSubquery.query(unordered())))" return try countRequest.fetchOne(db)! } } From de52856cf3073424314a3b3736a18fbcb191c789 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 17 Feb 2021 18:11:00 +0100 Subject: [PATCH 08/35] Aliasing is not qualifying --- GRDB/QueryInterface/Request/Association/Association.swift | 2 +- GRDB/QueryInterface/Request/QueryInterfaceRequest.swift | 4 ++-- GRDB/QueryInterface/SQL/SQLQuery.swift | 6 ++---- GRDB/QueryInterface/SQL/SQLRelation.swift | 6 +++--- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index 676ba263c..d04576c0a 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -285,7 +285,7 @@ extension Association { /// .including(required: Player.team.aliased(teamAlias)) /// .filter(sql: "custom.color = ?", arguments: ["red"]) public func aliased(_ alias: TableAlias) -> Self { - mapDestinationRelation { $0.qualified(with: alias) } + mapDestinationRelation { $0.aliased(alias) } } } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 506e7b56d..cc0ea8f6e 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -300,7 +300,7 @@ extension QueryInterfaceRequest: TableRequest { /// .aliased(playerAlias) /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { - map(\.query) { $0.qualified(with: alias) } + map(\.query) { $0.aliased(alias) } } } @@ -737,7 +737,7 @@ func makePrefetchRequest( let pivotAlias = TableAlias() let prefetchRelation = association - .map(\.pivot.relation, { $0.qualified(with: pivotAlias).filter(pivotFilter) }) + .map(\.pivot.relation, { $0.aliased(pivotAlias).filter(pivotFilter) }) .destinationRelation() .annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") }) diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index 0ecd19a97..c069475b9 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -19,10 +19,8 @@ extension SQLQuery: Refinable { with(\.limit, SQLLimit(limit: limit, offset: offset)) } - func qualified(with alias: TableAlias) -> Self { - // We do not need to qualify group and having clauses. They will be - // in SQLQueryGenerator.init() - map(\.relation) { $0.qualified(with: alias) } + func aliased(_ alias: TableAlias) -> Self { + map(\.relation) { $0.aliased(alias) } } } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 864710f97..85a6b0b00 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -259,8 +259,8 @@ extension SQLRelation: Refinable { .map(\.children, { $0.mapValues { $0.map(\.relation, { $0.unordered() }) } }) } - func qualified(with alias: TableAlias) -> Self { - map(\.source) { $0.qualified(with: alias) } + func aliased(_ alias: TableAlias) -> Self { + map(\.source) { $0.aliased(alias) } } } @@ -426,7 +426,7 @@ struct SQLSource { var tableName: String var alias: TableAlias? - func qualified(with alias: TableAlias) -> SQLSource { + func aliased(_ alias: TableAlias) -> SQLSource { if let sourceAlias = self.alias { alias.becomeProxy(of: sourceAlias) return self From e40534942c1df06654b1049cbefd699076df5849 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 17 Feb 2021 18:19:52 +0100 Subject: [PATCH 09/35] format --- GRDB/QueryInterface/SQL/SQLRelation.swift | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 85a6b0b00..b1f0530eb 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -255,8 +255,13 @@ extension SQLRelation: Refinable { } func unordered() -> Self { - self.with(\.ordering, SQLRelation.Ordering()) - .map(\.children, { $0.mapValues { $0.map(\.relation, { $0.unordered() }) } }) + self + .with(\.ordering, SQLRelation.Ordering()) + .map(\.children) { children in + children.mapValues { child in + child.map(\.relation) { $0.unordered() } + } + } } func aliased(_ alias: TableAlias) -> Self { From c9332a8c9ecdd08a54119129d09c1558cea720bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 17 Feb 2021 20:03:59 +0100 Subject: [PATCH 10/35] Fix typo --- Tests/GRDBTests/AssociationPrefetchingSQLTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 74f046e36..6401c8438 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -937,8 +937,8 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { // This request is an example of what users are unlikely to // want, because of the shared key between the two different // pivot associations. - // However, A.hasMany(C.self) does not conflict. Thos is an - // indirect proof that it feeds an association kt, "as", which + // However, A.hasMany(C.self) does not conflict. This is an + // indirect proof that it feeds an association key, "as", which // is distinc from "a" (A.hasOne(C.self)). let request = A .including(all: A From 3665a533cf486ec0948fc3ca61298174af2035a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 17 Feb 2021 20:04:35 +0100 Subject: [PATCH 11/35] Add missing tests for has-many through association with three steps --- .../AssociationHasManyThroughSQLTests.swift | 660 ++++++++++++++++++ 1 file changed, 660 insertions(+) diff --git a/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift b/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift index 3fc66af7b..d054a57c2 100644 --- a/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift @@ -432,4 +432,664 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { } } } + + // MARK: - Three Steps + + func testHasManyHasManyHasMany() throws { + struct A: TableRecord, EncodableRecord { + static let bs = hasMany(B.self) + static let cs = hasMany(C.self, through: bs, using: B.cs) + static let dsThroughCs = hasMany(D.self, through: cs, using: C.ds) + static let dsThroughBs = hasMany(D.self, through: bs, using: B.ds) + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } + } + struct B: TableRecord { + static let cs = hasMany(C.self) + static let ds = hasMany(D.self, through: cs, using: C.ds) + } + struct C: TableRecord { + static let ds = hasMany(D.self) + } + struct D: TableRecord { + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "a") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "b") { t in + t.autoIncrementedPrimaryKey("id") + t.column("aId").references("a") + } + try db.create(table: "c") { t in + t.autoIncrementedPrimaryKey("id") + t.column("bId").references("b") + } + try db.create(table: "d") { t in + t.autoIncrementedPrimaryKey("id") + t.column("cId").references("c") + } + + try testHasManyWithThreeSteps( + db, bs: A.bs, cs: A.cs, dsThroughCs: A.dsThroughCs, dsThroughBs: A.dsThroughBs, + bsCondition: "\"b\".\"aId\" = \"a\".\"id\"", + csCondition: "\"c\".\"bId\" = \"b\".\"id\"", + dsCondition: "\"d\".\"cId\" = \"c\".\"id\"") + + try assertEqualSQL(db, A().request(for: A.dsThroughCs), """ + SELECT "d".* \ + FROM "d" \ + JOIN "c" ON "c"."id" = "d"."cId" \ + JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1) + """) + try assertEqualSQL(db, A().request(for: A.dsThroughBs), """ + SELECT "d".* \ + FROM "d" \ + JOIN "c" ON "c"."id" = "d"."cId" \ + JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1) + """) + } + } + + func testBelongsToHasManyHasMany() throws { + struct A: TableRecord, EncodableRecord { + static let b = belongsTo(B.self) + static let cs = hasMany(C.self, through: b, using: B.cs) + static let dsThroughCs = hasMany(D.self, through: cs, using: C.ds) + static let dsThroughB = hasMany(D.self, through: b, using: B.ds) + func encode(to container: inout PersistenceContainer) { + container["bId"] = 1 + } + } + struct B: TableRecord { + static let cs = hasMany(C.self) + static let ds = hasMany(D.self, through: cs, using: C.ds) + } + struct C: TableRecord { + static let ds = hasMany(D.self) + } + struct D: TableRecord { + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "b") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "c") { t in + t.autoIncrementedPrimaryKey("id") + t.column("bId").references("b") + } + try db.create(table: "d") { t in + t.autoIncrementedPrimaryKey("id") + t.column("cId").references("c") + } + try db.create(table: "a") { t in + t.autoIncrementedPrimaryKey("id") + t.column("bId").references("b") + } + + try testHasManyWithThreeSteps( + db, bs: A.b, cs: A.cs, dsThroughCs: A.dsThroughCs, dsThroughBs: A.dsThroughB, + bsCondition: "\"b\".\"id\" = \"a\".\"bId\"", + csCondition: "\"c\".\"bId\" = \"b\".\"id\"", + dsCondition: "\"d\".\"cId\" = \"c\".\"id\"") + + try assertEqualSQL(db, A().request(for: A.dsThroughCs), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON "c"."id" = "d"."cId" \ + JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."id" = 1) + """) + try assertEqualSQL(db, A().request(for: A.dsThroughB), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON "c"."id" = "d"."cId" \ + JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."id" = 1) + """) + } + } + + func testHasManyHasManyBelongsTo() throws { + struct A: TableRecord, EncodableRecord { + static let bs = hasMany(B.self) + static let cs = hasMany(C.self, through: bs, using: B.cs) + static let dsThroughCs = hasMany(D.self, through: cs, using: C.d) + static let dsThroughBs = hasMany(D.self, through: bs, using: B.ds) + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } + } + struct B: TableRecord { + static let cs = hasMany(C.self) + static let ds = hasMany(D.self, through: cs, using: C.d) + } + struct C: TableRecord { + static let d = belongsTo(D.self) + } + struct D: TableRecord { + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "a") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "d") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "b") { t in + t.autoIncrementedPrimaryKey("id") + t.column("aId").references("a") + } + try db.create(table: "c") { t in + t.autoIncrementedPrimaryKey("id") + t.column("bId").references("b") + t.column("dId").references("d") + } + + try testHasManyWithThreeSteps( + db, bs: A.bs, cs: A.cs, dsThroughCs: A.dsThroughCs, dsThroughBs: A.dsThroughBs, + bsCondition: "\"b\".\"aId\" = \"a\".\"id\"", + csCondition: "\"c\".\"bId\" = \"b\".\"id\"", + dsCondition: "\"d\".\"id\" = \"c\".\"dId\"") + + try assertEqualSQL(db, A().request(for: A.dsThroughCs), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON "c"."dId" = "d"."id" \ + JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1) + """) + try assertEqualSQL(db, A().request(for: A.dsThroughBs), """ + SELECT "d".* FROM "d" \ + JOIN "c" ON "c"."dId" = "d"."id" \ + JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1) + """) + } + } + + private func testHasManyWithThreeSteps( + _ db: Database, + bs: BsAssociation, + cs: CsAssociation, + dsThroughCs: DsCsAssociation, + dsThroughBs: DsBsAssociation, + bsCondition: String, + csCondition: String, + dsCondition: String) throws + where + BsAssociation: Association, + CsAssociation: Association, + DsCsAssociation: Association, + DsBsAssociation: Association, + BsAssociation.OriginRowDecoder: TableRecord, + BsAssociation.OriginRowDecoder == CsAssociation.OriginRowDecoder, + BsAssociation.OriginRowDecoder == DsCsAssociation.OriginRowDecoder, + BsAssociation.OriginRowDecoder == DsBsAssociation.OriginRowDecoder + { + let A = CsAssociation.OriginRowDecoder.self + + do { + for request in [ + A.including(optional: dsThroughCs), + A.including(optional: dsThroughBs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.including(required: dsThroughCs), + A.including(required: dsThroughBs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(optional: dsThroughCs), + A.joining(optional: dsThroughBs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(required: dsThroughCs), + A.joining(required: dsThroughBs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + } + + do { + do { + for request in [ + A.including(optional: dsThroughCs).including(optional: bs), + A.including(optional: dsThroughBs).including(optional: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.including(required: dsThroughCs).including(optional: bs), + A.including(required: dsThroughBs).including(optional: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(optional: dsThroughCs).including(optional: bs), + A.joining(optional: dsThroughBs).including(optional: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(required: dsThroughCs).including(optional: bs), + A.joining(required: dsThroughBs).including(optional: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + } + + do { + for request in [ + A.including(optional: dsThroughCs).including(required: bs), + A.including(optional: dsThroughBs).including(required: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.including(required: dsThroughCs).including(required: bs), + A.including(required: dsThroughBs).including(required: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(optional: dsThroughCs).including(required: bs), + A.joining(optional: dsThroughBs).including(required: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(required: dsThroughCs).including(required: bs), + A.joining(required: dsThroughBs).including(required: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + } + + do { + for request in [ + A.including(optional: dsThroughCs).joining(optional: bs), + A.including(optional: dsThroughBs).joining(optional: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.including(required: dsThroughCs).joining(optional: bs), + A.including(required: dsThroughBs).joining(optional: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(optional: dsThroughCs).joining(optional: bs), + A.joining(optional: dsThroughBs).joining(optional: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(required: dsThroughCs).joining(optional: bs), + A.joining(required: dsThroughBs).joining(optional: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + } + + do { + for request in [ + A.including(optional: dsThroughCs).joining(required: bs), + A.including(optional: dsThroughBs).joining(required: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.including(required: dsThroughCs).joining(required: bs), + A.including(required: dsThroughBs).joining(required: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(optional: dsThroughCs).joining(required: bs), + A.joining(optional: dsThroughBs).joining(required: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(required: dsThroughCs).joining(required: bs), + A.joining(required: dsThroughBs).joining(required: bs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + } + } + + do { + do { + for request in [ + A.including(optional: dsThroughCs).including(optional: cs), + A.including(optional: dsThroughBs).including(optional: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.including(required: dsThroughCs).including(optional: cs), + A.including(required: dsThroughBs).including(optional: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(optional: dsThroughCs).including(optional: cs), + A.joining(optional: dsThroughBs).including(optional: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(required: dsThroughCs).including(optional: cs), + A.joining(required: dsThroughBs).including(optional: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + } + + do { + for request in [ + A.including(optional: dsThroughCs).including(required: cs), + A.including(optional: dsThroughBs).including(required: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.including(required: dsThroughCs).including(required: cs), + A.including(required: dsThroughBs).including(required: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(optional: dsThroughCs).including(required: cs), + A.joining(optional: dsThroughBs).including(required: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(required: dsThroughCs).including(required: cs), + A.joining(required: dsThroughBs).including(required: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + } + + do { + for request in [ + A.including(optional: dsThroughCs).joining(optional: cs), + A.including(optional: dsThroughBs).joining(optional: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.including(required: dsThroughCs).joining(optional: cs), + A.including(required: dsThroughBs).joining(optional: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(optional: dsThroughCs).joining(optional: cs), + A.joining(optional: dsThroughBs).joining(optional: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON \(bsCondition) \ + LEFT JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(required: dsThroughCs).joining(optional: cs), + A.joining(required: dsThroughBs).joining(optional: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + } + + do { + for request in [ + A.including(optional: dsThroughCs).joining(required: cs), + A.including(optional: dsThroughBs).joining(required: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.including(required: dsThroughCs).joining(required: cs), + A.including(required: dsThroughBs).joining(required: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(optional: dsThroughCs).joining(required: cs), + A.joining(optional: dsThroughBs).joining(required: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + LEFT JOIN "d" ON \(dsCondition) + """) + } + for request in [ + A.joining(required: dsThroughCs).joining(required: cs), + A.joining(required: dsThroughBs).joining(required: cs)] + { + try assertEqualSQL(db, request, """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON \(bsCondition) \ + JOIN "c" ON \(csCondition) \ + JOIN "d" ON \(dsCondition) + """) + } + } + } + } } From d7f61fa0f5bffdc0193c81eca741df4e49be6d5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 18 Feb 2021 07:58:10 +0100 Subject: [PATCH 12/35] Documentation --- GRDB/QueryInterface/SQL/SQLRelation.swift | 72 ++++++++++++++++++----- 1 file changed, 58 insertions(+), 14 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index b1f0530eb..a342372bb 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -108,15 +108,6 @@ struct SQLRelation { case allPrefetched // Record.including(all: associationThroughPivot) case allNotPrefetched - - var isSingular: Bool { - switch self { - case .oneOptional, .oneRequired: - return true - case .allPrefetched, .allNotPrefetched: - return false - } - } } var kind: Kind @@ -303,12 +294,65 @@ extension SQLRelation { /// as HasManyThrough, which have any number of pivot relations between the /// origin and the destination. func appendingChild(for association: _SQLAssociation, kind: SQLRelation.Child.Kind) -> Self { - // Preserve association cardinality in intermediate steps of - // including(all:), and force desired cardinality otherwize - let isSingular = (kind == .allNotPrefetched) - ? association.destination.cardinality.isSingular - : kind.isSingular + // Our goal here is to append a child with a correct (singular or + // plural) key, so that the user can decode it later under the expected + // name. + // + // To know if the child key should be singular or plural, we look at the + // association, which may be to-one or to-many, and at the kind of the + // child, which may be joined (singular), or prefetched (plural). + // + // We prefer the cardinality of the child kind, but for the specific + // case of prefetched has-many-through associations (kind + // `.allNotPrefetched`), where we use the cardinality of + // the association. + // + // By prefering the cardinality of the child kind in general, we make it + // possible to join to a plural association and decode it in a singular + // key. In the example below, we have a singular kind `.oneRequired`, + // a plural to-many association, and we use a singular key: + // + // // Decode a Player in the singular "player" key + // // + // // SELECT team.*, player.* + // // FROM team + // // JOIN player ON player.teamID = team.id + // Team.joining(required: Team.players) + // + // The exception for has-many-through associations exists because the + // pivot of the association may be singular, and may conflict with a + // plural association with the same association key, as in the example + // below: + // + // We want the child for the "captain" in the following request to be + // registered under the singular "player" key, and not the plural + // "players" key, so that it does not conflict with the other child + // named "players" (we can not have two distinct children with the + // same key): + // + // struct Team: TableRecord { + // static let players = hasMany(Player.self) + // static let captain = hasOne(Player.self).filter(Column("isCaptain") == true) + // static let captainAwards = hasMany(Award.self, through: captain, using: Player.awards) + // } + // struct Player: TableRecord { + // static let awards = hasMany(Award.self) + // } + // struct Award: TableRecord { } + // let request = Team + // .including(all: Team.captainAwards) // child "player" (with an "awards" child inside) + // .including(all: Team.players) // child "players" + let isSingular: Bool + switch kind { + case .oneOptional, .oneRequired: + isSingular = true + case .allPrefetched: + isSingular = false + case .allNotPrefetched: + isSingular = association.destination.cardinality.isSingular + } let childKey = association.destination.key.name(singular: isSingular) + let child = SQLRelation.Child( kind: kind, condition: association.destination.condition, From 10a16ac6f01fee6de26a680b82d424a34336d3e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 18 Feb 2021 08:42:01 +0100 Subject: [PATCH 13/35] Rename .allNotPrefetched to .bridge --- GRDB/QueryInterface/SQL/SQLRelation.swift | 75 +++++++++---------- .../SQLGeneration/SQLQueryGenerator.swift | 2 +- 2 files changed, 37 insertions(+), 40 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index a342372bb..edccdff43 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -72,31 +72,27 @@ /// // JOIN author ON author.id = book.id AND author.country = 'FR' /// Book.including(required: Book.author.filter(Column("country") == "FR")) /// -/// - `.allPrefetched`: +/// - `.all`: /// -/// Such children are prefetched using several SQL requests: +/// Such children are prefetched using an extra SQL request: /// -/// // SELECT * FROM countries WHERE continent = 'EU' -/// // SELECT * FROM passport WHERE countryCode IN ('BE', 'DE', 'FR', ...) -/// Country -/// .filter(Column("continent") == "EU") -/// .including(all: Country.passports) +/// // SELECT * FROM countries; +/// // SELECT * FROM passport +/// // WHERE countryCode IN ('BE', 'DE', 'FR', ...); +/// Country.including(all: Country.passports) /// -/// - `.allNotPrefetched`: +/// - `.bridge`: /// /// Such children are not joined, and not prefetched. They are used as /// intermediate children towards a prefetched child. In the example -/// below, the country relation has a `.allNotPrefetched` child to -/// passports, and the passport relation has a `.allPrefetched` child -/// to citizens. +/// below, the country relation has a `.bridge` child to passports, and the +/// passport relation has an `.all` child to citizens. /// -/// // SELECT * FROM countries WHERE continent = 'EU' +/// // SELECT * FROM countries; /// // SELECT citizens.* FROM citizens /// // JOIN passport ON passport.citizenId = citizens.id -/// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...) -/// Country -/// .filter(Column("continent") == "EU") -/// .including(all: Country.citizens) +/// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...); +/// Country.including(all: Country.citizens) struct SQLRelation { struct Child: Refinable { enum Kind { @@ -105,9 +101,9 @@ struct SQLRelation { // Record.including(required: association) case oneRequired // Record.including(all: association) - case allPrefetched + case all // Record.including(all: associationThroughPivot) - case allNotPrefetched + case bridge } var kind: Kind @@ -122,7 +118,7 @@ struct SQLRelation { switch kind { case .oneOptional, .oneRequired: return true - case .allPrefetched, .allNotPrefetched: + case .all, .bridge: return false } } @@ -134,7 +130,7 @@ struct SQLRelation { switch kind { case .oneOptional, .oneRequired: cardinality = .toOne - case .allPrefetched, .allNotPrefetched: + case .all, .bridge: cardinality = .toMany } @@ -156,9 +152,9 @@ struct SQLRelation { var prefetchedAssociations: [_SQLAssociation] { children.flatMap { key, child -> [_SQLAssociation] in switch child.kind { - case .allPrefetched: + case .all: return [child.makeAssociationForKey(key)] - case .oneOptional, .oneRequired, .allNotPrefetched: + case .oneOptional, .oneRequired, .bridge: return child.relation.prefetchedAssociations.map { association in // Remove redundant pivot child let pivotKey = association.pivot.keyName @@ -303,9 +299,9 @@ extension SQLRelation { // child, which may be joined (singular), or prefetched (plural). // // We prefer the cardinality of the child kind, but for the specific - // case of prefetched has-many-through associations (kind - // `.allNotPrefetched`), where we use the cardinality of - // the association. + // case of the `.bridge` child kind, involved in prefetched + // has-many-through associations, where we user the cardinality of + // the association instead. // // By prefering the cardinality of the child kind in general, we make it // possible to join to a plural association and decode it in a singular @@ -346,9 +342,9 @@ extension SQLRelation { switch kind { case .oneOptional, .oneRequired: isSingular = true - case .allPrefetched: + case .all: isSingular = false - case .allNotPrefetched: + case .bridge: isSingular = association.destination.cardinality.isSingular } let childKey = association.destination.key.name(singular: isSingular) @@ -395,10 +391,11 @@ extension SQLRelation { .appendingChild(child, forKey: childKey) switch kind { - case .oneRequired, .oneOptional, .allNotPrefetched: + case .oneRequired, .oneOptional, .bridge: return appendingChild(for: reducedAssociation, kind: kind) - case .allPrefetched: - // Intermediate steps of indirect associations are not prefetched. + case .all: + // Intermediate steps of an indirect association are not prefetched: + // use the `.bridge` kind. // // For example, the request below prefetches citizens, not // intermediate passports: @@ -408,7 +405,7 @@ extension SQLRelation { // static let citizens = hasMany(Citizens.self, through: passports, using: Passport.citizen) // } // let request = Country.including(all: Country.citizens) - return appendingChild(for: reducedAssociation, kind: .allNotPrefetched) + return appendingChild(for: reducedAssociation, kind: .bridge) } } @@ -440,7 +437,7 @@ extension SQLRelation { func removingChildrenForPrefetchedAssociations() -> Self { filteringChildren { switch $0.kind { - case .allPrefetched, .allNotPrefetched: return false + case .all, .bridge: return false case .oneRequired, .oneOptional: return true } } @@ -449,7 +446,7 @@ extension SQLRelation { extension SQLRelation { func _including(all association: _SQLAssociation) -> Self { - appendingChild(for: association, kind: .allPrefetched) + appendingChild(for: association, kind: .all) } func _including(optional association: _SQLAssociation) -> Self { @@ -982,28 +979,28 @@ extension SQLRelation.Child.Kind { // .including(optional: association) return .oneOptional - case (.allPrefetched, .allPrefetched): + case (.all, .all): // Equivalent to Record.including(all: association): // // Record // .including(all: association) // .including(all: association) - return .allPrefetched + return .all - case (.allPrefetched, .allNotPrefetched), - (.allNotPrefetched, .allPrefetched): + case (.all, .bridge), + (.bridge, .all): // Record // .including(all: associationToDestinationThroughPivot) // .including(all: associationToPivot) fatalError("Not implemented: merging a direct association and an indirect one with including(all:)") - case (.allNotPrefetched, .allNotPrefetched): + case (.bridge, .bridge): // Equivalent to Record.including(all: association) // // Record // .including(all: association) // .including(all: association) - return .allNotPrefetched + return .bridge default: // Likely a programmer error: diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 58f203e82..8ec497706 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -714,7 +714,7 @@ private struct SQLQualifiedJoin: Refinable { self = .innerJoin case .oneOptional: self = .leftJoin - case .allPrefetched, .allNotPrefetched: + case .all, .bridge: // Eager loading of to-many associations is not implemented with joins return nil } From 7dd36ecc0fe5f81125dccbe843526a56e2b64f67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 18 Feb 2021 22:47:14 +0100 Subject: [PATCH 14/35] Tests for SQLRelation children --- GRDB.xcodeproj/project.pbxproj | 8 + GRDBCustom.xcodeproj/project.pbxproj | 6 + .../AssociationPrefetchingRelationTests.swift | 649 ++++++++++++++++++ 3 files changed, 663 insertions(+) create mode 100644 Tests/GRDBTests/AssociationPrefetchingRelationTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index e56b05cb3..167cdd330 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -18,6 +18,9 @@ 560432A1228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; 560432A4228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; + 5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; }; + 5604484A25DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; }; + 5604484B25DEEEF8002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; }; 56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C4E2291B16900A7CB10 /* AssociationHasManyRowScopeTests.swift */; }; 56057C562291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C4E2291B16900A7CB10 /* AssociationHasManyRowScopeTests.swift */; }; 56057C622291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C612291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */; }; @@ -1234,6 +1237,7 @@ 56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; + 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; 56057C4E2291B16900A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = ""; }; 56057C612291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughRowScopeTests.swift; sourceTree = ""; }; 5605F1491C672E4000235C62 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = ""; }; @@ -1983,6 +1987,7 @@ 56DF001A228DDBA300D611F3 /* AssociationPrefetchingCodableRecordTests.swift */, 569BBA20228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift */, 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */, + 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */, 56DF0019228DDBA200D611F3 /* AssociationPrefetchingRowTests.swift */, 560714E2227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift */, 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */, @@ -3280,6 +3285,7 @@ 561CFA7923735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, 56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */, 5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, + 5604484A25DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, 5653EAE720944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 56419C6F24A519A3004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */, 563EF440216131D1007DAACD /* AssociationAggregateTests.swift in Sources */, @@ -3506,6 +3512,7 @@ 5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, 561CFA7823735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, 56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, + 5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, 56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */, 5653EAE020944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 56419C6A24A519A2004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */, @@ -3863,6 +3870,7 @@ 561CFA7A23735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, AAA4DD8E230F262000C74B15 /* RecordEditedTests.swift in Sources */, AAA4DD8F230F262000C74B15 /* AssociationTableAliasTestsSQLTests.swift in Sources */, + 5604484B25DEEEF8002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, AAA4DD90230F262000C74B15 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 56419C7424A519A4004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */, AAA4DD91230F262000C74B15 /* AssociationAggregateTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 390cbefb1..64ebc63df 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -15,6 +15,8 @@ 56043297228F00A9009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */; }; 560432A6228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; 560432A7228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */; }; + 5604484E25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */; }; + 5604484F25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */; }; 56057C592291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C572291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift */; }; 56057C5A2291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C572291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift */; }; 56057C652291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56057C642291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */; }; @@ -756,6 +758,7 @@ 56012B80257404A300B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = ""; }; 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = ""; }; + 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; 56057C572291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyRowScopeTests.swift; sourceTree = ""; }; 56057C642291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughRowScopeTests.swift; sourceTree = ""; }; 5605F1491C672E4000235C62 /* CGFloat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloat.swift; sourceTree = ""; }; @@ -1463,6 +1466,7 @@ 56DF0013228DDB8200D611F3 /* AssociationPrefetchingCodableRecordTests.swift */, 569BBA29228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift */, 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */, + 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */, 56DF0014228DDB8200D611F3 /* AssociationPrefetchingRowTests.swift */, 560714EB227DD10F0091BB10 /* AssociationPrefetchingSQLTests.swift */, 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */, @@ -2530,6 +2534,7 @@ 561CFA7E2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, 56B964D21DA521450002DA19 /* FTS5RecordTests.swift in Sources */, F3BA80F91CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, + 5604484F25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, 56A5EF161EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, F3BA80DA1CFB300E003DC1BA /* DatabaseTimestampTests.swift in Sources */, 563EF443216131F5007DAACD /* AssociationAggregateTests.swift in Sources */, @@ -2887,6 +2892,7 @@ 561CFA7D2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */, 5623936C1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, F3BA80E01CFB300F003DC1BA /* DatabaseTimestampTests.swift in Sources */, + 5604484E25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */, 56A5EF121EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, F3BA80B21CFB2FC5003DC1BA /* DatabaseTests.swift in Sources */, 563EF442216131F5007DAACD /* AssociationAggregateTests.swift in Sources */, diff --git a/Tests/GRDBTests/AssociationPrefetchingRelationTests.swift b/Tests/GRDBTests/AssociationPrefetchingRelationTests.swift new file mode 100644 index 000000000..92aeff797 --- /dev/null +++ b/Tests/GRDBTests/AssociationPrefetchingRelationTests.swift @@ -0,0 +1,649 @@ +import XCTest +@testable import GRDB + +class AssociationPrefetchingRelationTests: GRDBTestCase { + func testAssociationKeyInflections() { + do { + let key = SQLAssociationKey.inflected("player") + XCTAssertEqual(key.baseName, "player") + XCTAssertEqual(key.singularizedName, "player") + XCTAssertEqual(key.pluralizedName, "players") + XCTAssertEqual(key.name(singular: true), "player") + XCTAssertEqual(key.name(singular: false), "players") + } + do { + let key = SQLAssociationKey.fixedSingular("player") + XCTAssertEqual(key.baseName, "player") + XCTAssertEqual(key.singularizedName, "player") + XCTAssertEqual(key.pluralizedName, "players") + XCTAssertEqual(key.name(singular: true), "player") + XCTAssertEqual(key.name(singular: false), "players") + } + do { + let key = SQLAssociationKey.fixedSingular("players") + XCTAssertEqual(key.baseName, "players") + XCTAssertEqual(key.singularizedName, "players") + XCTAssertEqual(key.pluralizedName, "players") + XCTAssertEqual(key.name(singular: true), "players") + XCTAssertEqual(key.name(singular: false), "players") + } + do { + let key = SQLAssociationKey.fixedPlural("player") + XCTAssertEqual(key.baseName, "player") + XCTAssertEqual(key.singularizedName, "player") + XCTAssertEqual(key.pluralizedName, "player") + XCTAssertEqual(key.name(singular: true), "player") + XCTAssertEqual(key.name(singular: false), "player") + } + do { + let key = SQLAssociationKey.fixedPlural("players") + XCTAssertEqual(key.baseName, "players") + XCTAssertEqual(key.singularizedName, "player") + XCTAssertEqual(key.pluralizedName, "players") + XCTAssertEqual(key.name(singular: true), "player") + XCTAssertEqual(key.name(singular: false), "players") + } + do { + let key = SQLAssociationKey.fixed("player") + XCTAssertEqual(key.baseName, "player") + XCTAssertEqual(key.singularizedName, "player") + XCTAssertEqual(key.pluralizedName, "player") + XCTAssertEqual(key.name(singular: true), "player") + XCTAssertEqual(key.name(singular: false), "player") + } + do { + let key = SQLAssociationKey.fixed("players") + XCTAssertEqual(key.baseName, "players") + XCTAssertEqual(key.singularizedName, "players") + XCTAssertEqual(key.pluralizedName, "players") + XCTAssertEqual(key.name(singular: true), "players") + XCTAssertEqual(key.name(singular: false), "players") + } + } + + func testOneStep() { + let cardinalities: [SQLAssociationCardinality] = [ + .toOne, + .toMany, + ] + + let keys: [SQLAssociationKey] = [ + .inflected("player"), + .fixedSingular("player"), + .fixedSingular("players"), + .fixedPlural("player"), + .fixedPlural("players"), + .fixed("player"), + ] + + for cardinality in cardinalities { + for key in keys { + + let relation = SQLRelation.all(fromTable: "ignored") + + let association = _SQLAssociation( + key: key, + condition: .none, + relation: .all(fromTable: "ignored"), + cardinality: cardinality) + + for relation in [ + relation._joining(optional: association), + relation._including(optional: association), + ] { + do { + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + } + do { + let relation = relation._joining(optional: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + } + do { + let relation = relation._joining(required: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + } + do { + let relation = relation._including(optional: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + } + do { + let relation = relation._including(required: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + } + if key.name(singular: true) != key.name(singular: false) { + let relation = relation._including(all: association) + XCTAssertEqual(relation.children.count, 2) + XCTAssertEqual(relation.children[0].key, key.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[1].key, key.name(singular: false)) + XCTAssertEqual(relation.children[1].value.kind, .all) + } + } + + for relation in [ + relation._joining(required: association), + relation._including(required: association), + ] { + do { + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + } + do { + let relation = relation._joining(optional: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + } + do { + let relation = relation._joining(required: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + } + do { + let relation = relation._including(optional: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + } + do { + let relation = relation._including(required: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + } + if key.name(singular: true) != key.name(singular: false) { + let relation = relation._including(all: association) + XCTAssertEqual(relation.children.count, 2) + XCTAssertEqual(relation.children[0].key, key.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[1].key, key.name(singular: false)) + XCTAssertEqual(relation.children[1].value.kind, .all) + } + } + + do { + let relation = relation._including(all: association) + do { + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key.name(singular: false)) + XCTAssertEqual(relation.children[0].value.kind, .all) + } + if key.name(singular: true) != key.name(singular: false) { + let relation = relation._joining(optional: association) + XCTAssertEqual(relation.children.count, 2) + XCTAssertEqual(relation.children[0].key, key.name(singular: false)) + XCTAssertEqual(relation.children[0].value.kind, .all) + XCTAssertEqual(relation.children[1].key, key.name(singular: true)) + XCTAssertEqual(relation.children[1].value.kind, .oneOptional) + } + if key.name(singular: true) != key.name(singular: false) { + let relation = relation._joining(required: association) + XCTAssertEqual(relation.children.count, 2) + XCTAssertEqual(relation.children[0].key, key.name(singular: false)) + XCTAssertEqual(relation.children[0].value.kind, .all) + XCTAssertEqual(relation.children[1].key, key.name(singular: true)) + XCTAssertEqual(relation.children[1].value.kind, .oneRequired) + } + if key.name(singular: true) != key.name(singular: false) { + let relation = relation._including(optional: association) + XCTAssertEqual(relation.children.count, 2) + XCTAssertEqual(relation.children[0].key, key.name(singular: false)) + XCTAssertEqual(relation.children[0].value.kind, .all) + XCTAssertEqual(relation.children[1].key, key.name(singular: true)) + XCTAssertEqual(relation.children[1].value.kind, .oneOptional) + } + if key.name(singular: true) != key.name(singular: false) { + let relation = relation._including(required: association) + XCTAssertEqual(relation.children.count, 2) + XCTAssertEqual(relation.children[0].key, key.name(singular: false)) + XCTAssertEqual(relation.children[0].value.kind, .all) + XCTAssertEqual(relation.children[1].key, key.name(singular: true)) + XCTAssertEqual(relation.children[1].value.kind, .oneRequired) + } + do { + let relation = relation._including(all: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key.name(singular: false)) + XCTAssertEqual(relation.children[0].value.kind, .all) + } + } + } + } + } + + func testTwoSteps() { + let cardinalities: [SQLAssociationCardinality] = [ + .toOne, + .toMany, + ] + + let keys1: [SQLAssociationKey] = [ + .inflected("player"), + .fixedSingular("player"), + .fixedSingular("players"), + .fixedPlural("player"), + .fixedPlural("players"), + .fixed("player"), + ] + + let keys2: [SQLAssociationKey] = [ + .inflected("award"), + .fixedSingular("award"), + .fixedSingular("awards"), + .fixedPlural("award"), + .fixedPlural("awards"), + .fixed("award"), + ] + + for cardinality1 in cardinalities { + for key1 in keys1 { + for cardinality2 in cardinalities { + for key2 in keys2 { + let relation = SQLRelation.all(fromTable: "ignored") + + let association1 = _SQLAssociation( + key: key1, + condition: .none, + relation: .all(fromTable: "ignored"), + cardinality: cardinality1) + + let association2 = _SQLAssociation( + key: key2, + condition: .none, + relation: .all(fromTable: "ignored"), + cardinality: cardinality2) + + let association = association2.through(association1) + + for relation in [ + relation._joining(optional: association), + relation._including(optional: association), + ] { + do { + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional) + } + do { + do { + let relation = relation._joining(optional: association1) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional) + } + do { + let relation = relation._joining(required: association1) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional) + } + do { + let relation = relation._including(optional: association1) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional) + } + do { + let relation = relation._including(required: association1) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional) + } + if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) { + let relation = relation._including(all: association1) + XCTAssertEqual(relation.children.count, 2) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[1].key, key1.name(singular: false)) + XCTAssertEqual(relation.children[1].value.kind, .all) + XCTAssertEqual(relation.children[1].value.relation.children.count, 0) + } + } + do { + do { + let relation = relation._joining(optional: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional) + } + do { + let relation = relation._joining(required: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } + do { + let relation = relation._including(optional: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional) + } + do { + let relation = relation._including(required: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } + // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? + // ~~~~~~~~~~~~~~~~~~~~~~~~ + if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) { + let relation = relation._including(all: association) + XCTAssertEqual(relation.children.count, 2) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[1].key, key1.name(singular: false)) + XCTAssertEqual(relation.children[1].value.kind, .bridge) + XCTAssertEqual(relation.children[1].value.relation.children.count, 1) + XCTAssertEqual(relation.children[1].value.relation.children[0].key, key2.name(singular: false)) + XCTAssertEqual(relation.children[1].value.relation.children[0].value.kind, .all) + } + } + } + + for relation in [ + relation._joining(required: association), + relation._including(required: association), + ] { + do { + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } + do { + do { + let relation = relation._joining(optional: association1) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } + do { + let relation = relation._joining(required: association1) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } + do { + let relation = relation._including(optional: association1) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } + do { + let relation = relation._including(required: association1) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } + if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) { + let relation = relation._including(all: association1) + XCTAssertEqual(relation.children.count, 2) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[1].key, key1.name(singular: false)) + XCTAssertEqual(relation.children[1].value.kind, .all) + XCTAssertEqual(relation.children[1].value.relation.children.count, 0) + } + } + do { + do { + let relation = relation._joining(optional: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } + do { + let relation = relation._joining(required: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } + do { + let relation = relation._including(optional: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } + do { + let relation = relation._including(required: association) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } + // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? + // ~~~~~~~~~~~~~~~~~~~~~~~~ + if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) { + let relation = relation._including(all: association) + XCTAssertEqual(relation.children.count, 2) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[1].key, key1.name(singular: false)) + XCTAssertEqual(relation.children[1].value.kind, .bridge) + XCTAssertEqual(relation.children[1].value.relation.children.count, 1) + XCTAssertEqual(relation.children[1].value.relation.children[0].key, key2.name(singular: false)) + XCTAssertEqual(relation.children[1].value.relation.children[0].value.kind, .all) + } + } + } + + do { + let relation = relation._including(all: association) + do { + XCTAssertEqual(relation.children.count, 1) + // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? + // ~~~~~~~~~~~~~~~~~~~~~~~ + XCTAssertEqual(relation.children[0].key, key1.name(singular: cardinality1.isSingular)) + XCTAssertEqual(relation.children[0].value.kind, .bridge) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: false)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .all) + } + } + } + } + } + } + } + + func testThreeSteps() { + let cardinalities: [SQLAssociationCardinality] = [ + .toOne, + .toMany, + ] + + let keys1: [SQLAssociationKey] = [ + .inflected("player"), + .fixedSingular("player"), + .fixedSingular("players"), + .fixedPlural("player"), + .fixedPlural("players"), + .fixed("player"), + ] + + let keys2: [SQLAssociationKey] = [ + .inflected("award"), + .fixedSingular("award"), + .fixedSingular("awards"), + .fixedPlural("award"), + .fixedPlural("awards"), + .fixed("award"), + ] + + let keys3: [SQLAssociationKey] = [ + .inflected("sponsor"), + .fixedSingular("sponsor"), + .fixedSingular("sponsors"), + .fixedPlural("sponsor"), + .fixedPlural("sponsors"), + .fixed("sponsor"), + ] + + for cardinality1 in cardinalities { + for key1 in keys1 { + for cardinality2 in cardinalities { + for key2 in keys2 { + for cardinality3 in cardinalities { + for key3 in keys3 { + let relation = SQLRelation.all(fromTable: "ignored") + + let association1 = _SQLAssociation( + key: key1, + condition: .none, + relation: .all(fromTable: "ignored"), + cardinality: cardinality1) + + let association2 = _SQLAssociation( + key: key2, + condition: .none, + relation: .all(fromTable: "ignored"), + cardinality: cardinality2) + + let association3 = _SQLAssociation( + key: key3, + condition: .none, + relation: .all(fromTable: "ignored"), + cardinality: cardinality3) + + for association in [ + association3.through(association2.through(association1)), + association3.through(association2).through(association1), + ] { + + for relation in [ + relation._joining(optional: association), + relation._including(optional: association), + ] { + do { + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .oneOptional) + } + } + + for relation in [ + relation._joining(required: association), + relation._including(required: association), + ] { + do { + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } + } + + do { + let relation = relation._including(all: association) + do { + XCTAssertEqual(relation.children.count, 1) + // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? + // ~~~~~~~~~~~~~~~~~~~~~~~ + XCTAssertEqual(relation.children[0].key, key1.name(singular: cardinality1.isSingular)) + XCTAssertEqual(relation.children[0].value.kind, .bridge) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? + // ~~~~~~~~~~~~~~~~~~~~~~~ + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: cardinality2.isSingular)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .bridge) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: false)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .all) + } + } + } + } + } + } + } + } + } + } +} From 081500b5ce76a3fd77d1a90722e76d28ab09ba40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 19 Feb 2021 13:26:18 +0100 Subject: [PATCH 15/35] TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index e65b9b2a0..c4967f4e4 100644 --- a/TODO.md +++ b/TODO.md @@ -15,6 +15,7 @@ ## Features +- [ ] Paranoid: always assume there are external connections. Wrap DatabaseQueue.read in a transaction, deprecate DatabaseQueue.inDatabase (use unsafeWriteWithoutTransaction or unsafeRead instead). - [ ] GRDB 6: decoding errors - [ ] GRDB 6: conflict resolution in persistence methods - [ ] Long run edition. Use case: user edits the database (CRUD) but the application wants to commmit and the end of the editing session. From d419d233682e05e956c7c40bb5af796e8751db83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 19 Feb 2021 16:28:22 +0100 Subject: [PATCH 16/35] Tests for SQLRelation children --- .../AssociationPrefetchingRelationTests.swift | 68 ++++++++++++++++++- 1 file changed, 66 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/AssociationPrefetchingRelationTests.swift b/Tests/GRDBTests/AssociationPrefetchingRelationTests.swift index 92aeff797..069ddf744 100644 --- a/Tests/GRDBTests/AssociationPrefetchingRelationTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingRelationTests.swift @@ -376,7 +376,7 @@ class AssociationPrefetchingRelationTests: GRDBTestCase { XCTAssertEqual(relation.children[0].value.relation.children.count, 1) XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional) - XCTAssertEqual(relation.children[1].key, key1.name(singular: false)) + XCTAssertEqual(relation.children[1].key, key1.name(singular: cardinality1.isSingular)) XCTAssertEqual(relation.children[1].value.kind, .bridge) XCTAssertEqual(relation.children[1].value.relation.children.count, 1) XCTAssertEqual(relation.children[1].value.relation.children[0].key, key2.name(singular: false)) @@ -494,7 +494,7 @@ class AssociationPrefetchingRelationTests: GRDBTestCase { XCTAssertEqual(relation.children[0].value.relation.children.count, 1) XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) - XCTAssertEqual(relation.children[1].key, key1.name(singular: false)) + XCTAssertEqual(relation.children[1].key, key1.name(singular: cardinality1.isSingular)) XCTAssertEqual(relation.children[1].value.kind, .bridge) XCTAssertEqual(relation.children[1].value.relation.children.count, 1) XCTAssertEqual(relation.children[1].value.relation.children[0].key, key2.name(singular: false)) @@ -515,6 +515,24 @@ class AssociationPrefetchingRelationTests: GRDBTestCase { XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: false)) XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .all) } + + #warning("TODO: here we see the problem: it should be possible to merge association1 when it is singular.") + // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? + // ~~~~~~~~~~~~~~~~~~~~~~~~ + if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) { + let relation = relation._joining(optional: association1) + XCTAssertEqual(relation.children.count, 2) + // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? + // ~~~~~~~~~~~~~~~~~~~~~~~ + XCTAssertEqual(relation.children[0].key, key1.name(singular: cardinality1.isSingular)) + XCTAssertEqual(relation.children[0].value.kind, .bridge) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: false)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .all) + XCTAssertEqual(relation.children[1].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[1].value.kind, .oneOptional) + XCTAssertEqual(relation.children[1].value.relation.children.count, 0) + } } } } @@ -601,6 +619,18 @@ class AssociationPrefetchingRelationTests: GRDBTestCase { XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: true)) XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .oneOptional) } + do { + let relation = relation._joining(optional: association1) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneOptional) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .oneOptional) + } } for relation in [ @@ -618,6 +648,18 @@ class AssociationPrefetchingRelationTests: GRDBTestCase { XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: true)) XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .oneRequired) } + do { + let relation = relation._joining(optional: association1) + XCTAssertEqual(relation.children.count, 1) + XCTAssertEqual(relation.children[0].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: true)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .oneRequired) + } } do { @@ -637,6 +679,28 @@ class AssociationPrefetchingRelationTests: GRDBTestCase { XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: false)) XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .all) } + #warning("TODO: here we see the problem: it should be possible to merge association1 when it is singular.") + // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? + // ~~~~~~~~~~~~~~~~~~~~~~~~ + if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) { + let relation = relation._joining(optional: association1) + XCTAssertEqual(relation.children.count, 2) + // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? + // ~~~~~~~~~~~~~~~~~~~~~~~ + XCTAssertEqual(relation.children[0].key, key1.name(singular: cardinality1.isSingular)) + XCTAssertEqual(relation.children[0].value.kind, .bridge) + XCTAssertEqual(relation.children[0].value.relation.children.count, 1) + // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? + // ~~~~~~~~~~~~~~~~~~~~~~~ + XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: cardinality2.isSingular)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .bridge) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: false)) + XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .all) + XCTAssertEqual(relation.children[1].key, key1.name(singular: true)) + XCTAssertEqual(relation.children[1].value.kind, .oneOptional) + XCTAssertEqual(relation.children[1].value.relation.children.count, 0) + } } } } From 8c8a25a73b37d05fdd8b1622b2365223583394c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 20 Feb 2021 11:42:54 +0100 Subject: [PATCH 17/35] Spot the possible improvement on SQLRelation children --- .../AssociationPrefetchingRelationTests.swift | 24 ++----------------- 1 file changed, 2 insertions(+), 22 deletions(-) diff --git a/Tests/GRDBTests/AssociationPrefetchingRelationTests.swift b/Tests/GRDBTests/AssociationPrefetchingRelationTests.swift index 069ddf744..cd12610f2 100644 --- a/Tests/GRDBTests/AssociationPrefetchingRelationTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingRelationTests.swift @@ -366,8 +366,6 @@ class AssociationPrefetchingRelationTests: GRDBTestCase { XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) } - // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? - // ~~~~~~~~~~~~~~~~~~~~~~~~ if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) { let relation = relation._including(all: association) XCTAssertEqual(relation.children.count, 2) @@ -484,8 +482,6 @@ class AssociationPrefetchingRelationTests: GRDBTestCase { XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: true)) XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .oneRequired) } - // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? - // ~~~~~~~~~~~~~~~~~~~~~~~~ if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) { let relation = relation._including(all: association) XCTAssertEqual(relation.children.count, 2) @@ -507,8 +503,6 @@ class AssociationPrefetchingRelationTests: GRDBTestCase { let relation = relation._including(all: association) do { XCTAssertEqual(relation.children.count, 1) - // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? - // ~~~~~~~~~~~~~~~~~~~~~~~ XCTAssertEqual(relation.children[0].key, key1.name(singular: cardinality1.isSingular)) XCTAssertEqual(relation.children[0].value.kind, .bridge) XCTAssertEqual(relation.children[0].value.relation.children.count, 1) @@ -516,14 +510,10 @@ class AssociationPrefetchingRelationTests: GRDBTestCase { XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .all) } - #warning("TODO: here we see the problem: it should be possible to merge association1 when it is singular.") - // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? - // ~~~~~~~~~~~~~~~~~~~~~~~~ + // TODO: here we see the problem: it should be possible to merge association1 when it is singular. if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) { let relation = relation._joining(optional: association1) XCTAssertEqual(relation.children.count, 2) - // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? - // ~~~~~~~~~~~~~~~~~~~~~~~ XCTAssertEqual(relation.children[0].key, key1.name(singular: cardinality1.isSingular)) XCTAssertEqual(relation.children[0].value.kind, .bridge) XCTAssertEqual(relation.children[0].value.relation.children.count, 1) @@ -666,32 +656,22 @@ class AssociationPrefetchingRelationTests: GRDBTestCase { let relation = relation._including(all: association) do { XCTAssertEqual(relation.children.count, 1) - // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? - // ~~~~~~~~~~~~~~~~~~~~~~~ XCTAssertEqual(relation.children[0].key, key1.name(singular: cardinality1.isSingular)) XCTAssertEqual(relation.children[0].value.kind, .bridge) XCTAssertEqual(relation.children[0].value.relation.children.count, 1) - // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? - // ~~~~~~~~~~~~~~~~~~~~~~~ XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: cardinality2.isSingular)) XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .bridge) XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1) XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].key, key3.name(singular: false)) XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children[0].value.kind, .all) } - #warning("TODO: here we see the problem: it should be possible to merge association1 when it is singular.") - // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? - // ~~~~~~~~~~~~~~~~~~~~~~~~ + // TODO: here we see the problem: it should be possible to merge association1 when it is singular. if !cardinality1.isSingular && key1.name(singular: true) != key1.name(singular: false) { let relation = relation._joining(optional: association1) XCTAssertEqual(relation.children.count, 2) - // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? - // ~~~~~~~~~~~~~~~~~~~~~~~ XCTAssertEqual(relation.children[0].key, key1.name(singular: cardinality1.isSingular)) XCTAssertEqual(relation.children[0].value.kind, .bridge) XCTAssertEqual(relation.children[0].value.relation.children.count, 1) - // TODO: what is the purpose of the name of the `.bridge` children, from the point of view of the user? - // ~~~~~~~~~~~~~~~~~~~~~~~ XCTAssertEqual(relation.children[0].value.relation.children[0].key, key2.name(singular: cardinality2.isSingular)) XCTAssertEqual(relation.children[0].value.relation.children[0].value.kind, .bridge) XCTAssertEqual(relation.children[0].value.relation.children[0].value.relation.children.count, 1) From a681ccf2b9e58a798e951ab4bb24a667eb9298e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 20 Feb 2021 11:53:27 +0100 Subject: [PATCH 18/35] Fix: DatabaseQueue.read is throws, not rethrows --- CHANGELOG.md | 2 ++ GRDB/Core/DatabaseQueue.swift | 2 +- Tests/GRDBTests/DatabaseQueueTests.swift | 4 ++-- Tests/GRDBTests/DatabaseTests.swift | 2 +- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4efb9bb87..e0b29f5fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -82,6 +82,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: The [Common Table Expressions Guide](Documentation/CommonTableExpressions.md) was updated accordingly. +- **Fixed**: `DatabaseQueue.read` is now declared `throws` instead of `rethrows`. + ## 5.4.0 Released February 15, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.3.0...v5.4.0) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 2bc1fab86..b9f622dbc 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -190,7 +190,7 @@ extension DatabaseQueue { /// /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. - public func read(_ block: (Database) throws -> T) rethrows -> T { + public func read(_ block: (Database) throws -> T) throws -> T { try writer.sync { db in try db.readOnly { try block(db) } } diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 6625a718b..3a14dc58c 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -135,7 +135,7 @@ class DatabaseQueueTests: GRDBTestCase { try dbQueue.write { _ in dispatchPrecondition(condition: .onQueue(targetQueue)) } - dbQueue.read { _ in + try dbQueue.read { _ in dispatchPrecondition(condition: .onQueue(targetQueue)) } } @@ -185,7 +185,7 @@ class DatabaseQueueTests: GRDBTestCase { try dbQueue.write { _ in dispatchPrecondition(condition: .onQueue(targetQueue)) } - dbQueue.read { _ in + try dbQueue.read { _ in dispatchPrecondition(condition: .onQueue(targetQueue)) } } diff --git a/Tests/GRDBTests/DatabaseTests.swift b/Tests/GRDBTests/DatabaseTests.swift index 4179a2860..21e91548f 100644 --- a/Tests/GRDBTests/DatabaseTests.swift +++ b/Tests/GRDBTests/DatabaseTests.swift @@ -378,7 +378,7 @@ class DatabaseTests : GRDBTestCase { func testMaximumStatementArgumentCount() throws { let dbQueue = try makeDatabaseQueue() - let count = dbQueue.read { $0.maximumStatementArgumentCount } + let count = try dbQueue.read { $0.maximumStatementArgumentCount } // 999 should be safe: https://www.sqlite.org/limits.html XCTAssertGreaterThanOrEqual(count, 999) } From 64bb63e304f7af8e348e93adc824e731a4f7be9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 20 Feb 2021 12:47:13 +0100 Subject: [PATCH 19/35] CommonTableExpression has an implicit Row RowDecoder --- CHANGELOG.md | 7 ++-- Documentation/CommonTableExpressions.md | 35 ++++--------------- .../Request/CommonTableExpression.swift | 8 ++--- .../Request/QueryInterfaceRequest.swift | 2 +- GRDB/QueryInterface/SQL/SQLSubquery.swift | 2 +- .../SQLInterpolation+QueryInterface.swift | 4 +-- .../TableRecord+Association.swift | 2 +- .../CommonTableExpressionTests.swift | 26 ++++++++------ 8 files changed, 34 insertions(+), 52 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e0b29f5fa..e54fb8509 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -73,11 +73,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Development Branch -- **New**: You can now define common table expressions without the `` generic qualifier: +- **New**: You can now define common table expressions without any generic qualifier (which defaults to `Row`): - ```diff - -let cte = CommonTableExpression(...) - +let cte = CommonTableExpression(...) + ```swift + let cte = CommonTableExpression(...) ``` The [Common Table Expressions Guide](Documentation/CommonTableExpressions.md) was updated accordingly. diff --git a/Documentation/CommonTableExpressions.md b/Documentation/CommonTableExpressions.md index 7f9463516..55da52e63 100644 --- a/Documentation/CommonTableExpressions.md +++ b/Documentation/CommonTableExpressions.md @@ -182,16 +182,19 @@ try Player In the previous chapter, a common table expression was embedded as a subquery, with the `CommonTableExpression.all()` method. -`all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests. +`cte.all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests. -You can also fetch from it, but only as long as it is provided with the definition of the CTE. This will generally give requests of the form `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`: +You can also fetch from `cte.all()`, as long as the request is given the definition of the CTE: `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`: + +This request, of type `QueryInterfaceRequest`, can fetch raw database [rows](../README.md#row-queries): ```swift let cte = CommonTableExpression(...) let request = cte.all().with(cte) +let rows = try request.fetchAll(db) // [Row] ``` -This request, of type `QueryInterfaceRequest`, doesn't quite know what to fetch and how. You must help it so that it can actually fetch database [rows](../README.md#row-queries), simple [values](../README.md#value-queries), or custom [records](../README.md#records). You have two possible options: +In order to fetch something else, such as simple [values](../README.md#value-queries), or custom [records](../README.md#records), you have two possible options: 1. Use the `asRequest(of:)` method: @@ -211,32 +214,6 @@ This request, of type `QueryInterfaceRequest`, doesn't quite know what to let players = try request.fetchAll(db) // [Player] ``` -For example, let's fetch a range of integer: - -```swift -func counterRequest(range: ClosedRange) -> QueryInterfaceRequest { - // WITH RECURSIVE counter(x) AS - // (VALUES(...) UNION ALL SELECT x+1 FROM counter WHERE x<...) - // SELECT * FROM counter - let counter = CommonTableExpression( - recursive: true, - named: "counter", - columns: ["x"], - literal: """ - VALUES(\(range.lowerBound)) \ - UNION ALL \ - SELECT x+1 FROM counter WHERE x < \(range.upperBound) - """) - return counter.all().with(counter) -} - -let values = try dbQueue.read { db in - try counterRequest(range: 3...7).fetchAll(db) -} -print(values) // prints "[3, 4, 5, 6, 7]" -``` - - ## Associations to Common Table Expressions GRDB [associations] define "to-one" and "to-many" relationships between two database tables. Here we will define associations between regular tables and common table expressions. diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index bb9f3d52b..8ace50580 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -147,7 +147,7 @@ extension CommonTableExpression { } } -extension CommonTableExpression where RowDecoder == Void { +extension CommonTableExpression where RowDecoder == Row { /// Creates a common table expression from a request. /// /// For example: @@ -179,7 +179,7 @@ extension CommonTableExpression where RowDecoder == Void { named: tableName, columns: columns, request: request, - type: Void.self) + type: Row.self) } /// Creates a common table expression from an SQL string and @@ -212,7 +212,7 @@ extension CommonTableExpression where RowDecoder == Void { named: tableName, columns: columns, request: SQLRequest(sql: sql, arguments: arguments), - type: Void.self) + type: Row.self) } /// Creates a common table expression from an `SQLLiteral`. @@ -241,7 +241,7 @@ extension CommonTableExpression where RowDecoder == Void { named: tableName, columns: columns, request: SQLRequest(literal: sqlLiteral), - type: Void.self) + type: Row.self) } } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index cc0ea8f6e..631894e2a 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -655,7 +655,7 @@ private func prefetch( .removingChildrenForPrefetchedAssociations() .selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection }) } - let originCTE = CommonTableExpression( + let originCTE = CommonTableExpression( named: "grdb_base", request: SQLSubquery.query(originQuery)) let pivotRowValue = SQLExpression.rowValue(pivotColumns.map(SQLExpression.column))! diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift index 63f8666a9..0cc66a2ae 100644 --- a/GRDB/QueryInterface/SQL/SQLSubquery.swift +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -29,7 +29,7 @@ extension SQLSubquery { /// // SELECT player.*, cte.* /// // FROM player /// // JOIN cte - /// let cte = CommonTableExpression(named: "cte", sql: "SELECT 1 AS a, 2 AS b") + /// let cte = CommonTableExpression(named: "cte", sql: "SELECT 1 AS a, 2 AS b") /// let request = Player /// .with(cte) /// .including(required: Player.association(to: cte)) diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index c4ad4a08d..a52dd9119 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -264,7 +264,7 @@ extension SQLInterpolation { /// Appends the table name of the common table expression. /// /// // WITH "cte" AS (...) SELECT * FROM "cte" - /// let cte = CommonTableExpression(named: "cte", ...) + /// let cte = CommonTableExpression(named: "cte", ...) /// let request: SQLRequest = """ /// WITH \(definitionFor: cte) SELECT * FROM \(cte) /// """ @@ -275,7 +275,7 @@ extension SQLInterpolation { /// Appends the definition of the common table expression. /// /// // WITH "cte" AS (...) SELECT * FROM "cte" - /// let cte = CommonTableExpression(named: "cte", ...) + /// let cte = CommonTableExpression(named: "cte", ...) /// let request: SQLRequest = """ /// WITH \(definitionFor: cte) SELECT * FROM \(cte) /// """ diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 43aa01e01..def776476 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -225,7 +225,7 @@ extension TableRecord { /// .annotated(with: max(Column("date"))) /// .group(Column("chatID")) /// - /// let latestMessageCTE = CommonTableExpression( + /// let latestMessageCTE = CommonTableExpression( /// named: "latestMessage", /// request: latestMessageRequest) /// diff --git a/Tests/GRDBTests/CommonTableExpressionTests.swift b/Tests/GRDBTests/CommonTableExpressionTests.swift index b024203b5..a204b7e07 100644 --- a/Tests/GRDBTests/CommonTableExpressionTests.swift +++ b/Tests/GRDBTests/CommonTableExpressionTests.swift @@ -3,15 +3,20 @@ import GRDB class CommonTableExpressionTests: GRDBTestCase { func testInitializers() { - // Implicit Void - _ = CommonTableExpression(named: "foo", sql: "") - _ = CommonTableExpression(named: "foo", literal: "") - _ = CommonTableExpression(named: "foo", request: SQLRequest("")) - - // Explicit Void - _ = CommonTableExpression(named: "foo", sql: "") - _ = CommonTableExpression(named: "foo", literal: "") - _ = CommonTableExpression(named: "foo", request: SQLRequest("")) + // Implicit generic RowDecoder type is Row + func acceptRowCTE(_ cte: CommonTableExpression) { } + do { + let cte = CommonTableExpression(named: "foo", sql: "") + acceptRowCTE(cte) + } + do { + let cte = CommonTableExpression(named: "foo", literal: "") + acceptRowCTE(cte) + } + do { + let cte = CommonTableExpression(named: "foo", request: SQLRequest("")) + acceptRowCTE(cte) + } // Explicit type struct S { } @@ -361,7 +366,8 @@ class CommonTableExpressionTests: GRDBTestCase { func testFetchFromCTE() throws { try makeDatabaseQueue().read { db in do { - let answer = CommonTableExpression( + // Default row decoder is Row + let answer = CommonTableExpression( named: "answer", sql: "SELECT 42 AS value") let row = try answer.all().with(answer).fetchOne(db) From aceaaf24d2e7ceeeebdf35e3ed3871351e16cebf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 20 Feb 2021 12:59:27 +0100 Subject: [PATCH 20/35] Paranoid: Wrap DatabaseQueue.read in a transaction This guarantees snapshot isolation even in case of external connections --- GRDB/Core/DatabaseQueue.swift | 28 +++++++++++++++++++++++++--- TODO.md | 4 +++- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index b9f622dbc..af826f5a3 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -192,7 +192,14 @@ extension DatabaseQueue { /// - throws: The error thrown by the block. public func read(_ block: (Database) throws -> T) throws -> T { try writer.sync { db in - try db.readOnly { try block(db) } + // The transaction guarantees snapshot isolation against eventual + // external connection. + var result: T? + try db.inTransaction(.deferred) { + result = try db.readOnly { try block(db) } + return .commit + } + return result! } } @@ -214,6 +221,9 @@ extension DatabaseQueue { public func asyncRead(_ block: @escaping (Result) -> Void) { writer.async { db in do { + // The transaction guarantees snapshot isolation against eventual + // external connection. + try db.beginTransaction(.deferred) try db.beginReadOnly() } catch { block(.failure(error)) @@ -224,6 +234,7 @@ extension DatabaseQueue { // Ignore error because we can not notify it. try? db.endReadOnly() + try? db.commit() } } @@ -236,6 +247,9 @@ extension DatabaseQueue { } do { + // The transaction guarantees snapshot isolation against eventual + // external connection. + try db.beginTransaction(.deferred) try db.beginReadOnly() } catch { block(.failure(error)) @@ -246,6 +260,7 @@ extension DatabaseQueue { // Ignore error because we can not notify it. try? db.endReadOnly() + try? db.commit() } } @@ -289,9 +304,14 @@ extension DatabaseQueue { try writer.execute { db in // ... and that no transaction is opened. GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.") - return try db.readOnly { - try block(db) + // The transaction guarantees snapshot isolation against eventual + // external connection. + var result: T? + try db.inTransaction(.deferred) { + result = try db.readOnly { try block(db) } + return .commit } + return result! } }) } @@ -306,6 +326,7 @@ extension DatabaseQueue { GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.") do { + try db.beginTransaction(.deferred) try db.beginReadOnly() } catch { block(.failure(error)) @@ -316,6 +337,7 @@ extension DatabaseQueue { // Ignore error because we can not notify it. try? db.endReadOnly() + try? db.commit() } } diff --git a/TODO.md b/TODO.md index c4967f4e4..81f694299 100644 --- a/TODO.md +++ b/TODO.md @@ -15,7 +15,9 @@ ## Features -- [ ] Paranoid: always assume there are external connections. Wrap DatabaseQueue.read in a transaction, deprecate DatabaseQueue.inDatabase (use unsafeWriteWithoutTransaction or unsafeRead instead). +- [ ] Paranoid: always assume there are external connections. + - [X] Wrap DatabaseQueue.read in a transaction + - [ ] deprecate DatabaseQueue.inDatabase (use unsafeWriteWithoutTransaction or unsafeRead instead). - [ ] GRDB 6: decoding errors - [ ] GRDB 6: conflict resolution in persistence methods - [ ] Long run edition. Use case: user edits the database (CRUD) but the application wants to commmit and the end of the editing session. From 6e8285e4ec66ab84c012795384bf8897afe857f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 20 Feb 2021 13:02:30 +0100 Subject: [PATCH 21/35] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e54fb8509..02097a1aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,6 +81,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: The [Common Table Expressions Guide](Documentation/CommonTableExpressions.md) was updated accordingly. +- **New**: `DatabaseQueue` reading methods are now wrapped in a deferred transaction. This guarantees snapshot isolation in case of concurrent writes performed by external connections, and makes `DatabaseQueue` a type suitable for shared databases. + - **Fixed**: `DatabaseQueue.read` is now declared `throws` instead of `rethrows`. ## 5.4.0 From 4398777f07d15f06d34bc2e4c0d16e21eccfc78d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 20 Feb 2021 17:03:17 +0100 Subject: [PATCH 22/35] TODO --- TODO.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/TODO.md b/TODO.md index 81f694299..93c61b103 100644 --- a/TODO.md +++ b/TODO.md @@ -15,9 +15,7 @@ ## Features -- [ ] Paranoid: always assume there are external connections. - - [X] Wrap DatabaseQueue.read in a transaction - - [ ] deprecate DatabaseQueue.inDatabase (use unsafeWriteWithoutTransaction or unsafeRead instead). +- [ ] Grab all FTS tokens in a string - [ ] GRDB 6: decoding errors - [ ] GRDB 6: conflict resolution in persistence methods - [ ] Long run edition. Use case: user edits the database (CRUD) but the application wants to commmit and the end of the editing session. From cb2405a8b9d897a516f6f38b591654b8b4cd5bc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 21 Feb 2021 12:32:33 +0100 Subject: [PATCH 23/35] RowDecodingError --- GRDB.xcodeproj/project.pbxproj | 10 + GRDB/Core/Database.swift | 2 +- GRDB/Core/DatabaseFunction.swift | 4 +- GRDB/Core/DatabaseValue.swift | 1 + GRDB/Core/DatabaseValueConversion.swift | 323 ++---- GRDB/Core/DatabaseValueConvertible.swift | 12 +- GRDB/Core/Row.swift | 673 ++++++++--- GRDB/Core/RowAdapter.swift | 19 +- GRDB/Core/RowDecodingError.swift | 190 ++++ GRDB/Core/Statement.swift | 4 +- GRDB/Core/StatementColumnConvertible.swift | 26 +- .../Foundation/DatabaseDateComponents.swift | 6 +- GRDB/Core/Support/Foundation/Date.swift | 11 +- GRDB/Core/Support/Foundation/UUID.swift | 8 +- .../StandardLibrary/StandardLibrary.swift | 81 +- GRDB/FTS/FTS5CustomTokenizer.swift | 2 +- GRDB/Record/FetchableRecord+Decodable.swift | 175 +-- GRDB/Utils/Utils.swift | 5 + GRDBCustom.xcodeproj/project.pbxproj | 6 + .../GRDBTests/CompilationProtocolTests.swift | 10 +- .../DatabaseDateDecodingStrategyTests.swift | 167 ++- .../DatabaseValueConversionErrorTests.swift | 1005 ++++++++++++----- ...StatementColumnConvertibleFetchTests.swift | 1 + 23 files changed, 1925 insertions(+), 816 deletions(-) create mode 100644 GRDB/Core/RowDecodingError.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 167cdd330..2857a6677 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -464,6 +464,10 @@ 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; + 566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; }; + 566B9C2125C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; }; + 566B9C2225C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; }; + 566B9C2325C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; }; 566BE71E2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; 566BE71F2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; 566BE7202342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; @@ -1411,6 +1415,7 @@ 566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = ""; }; 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; + 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = ""; }; 566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; }; 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; @@ -2287,6 +2292,7 @@ 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, + 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */, 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */, @@ -2879,6 +2885,7 @@ 5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */, 564CE43321AA901800652B19 /* ValueObserver.swift in Sources */, 563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */, + 566B9C2225C6CC24004542CF /* RowDecodingError.swift in Sources */, 565490B91D5AE236005622CB /* DatabasePool.swift in Sources */, 563B06AD217EF0CC00B38F35 /* ValueObservation.swift in Sources */, 5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, @@ -3109,6 +3116,7 @@ 563B8F93249E6171007A48C9 /* Trace.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, 56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */, + 566B9C2125C6CC24004542CF /* RowDecodingError.swift in Sources */, 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, @@ -3694,6 +3702,7 @@ 563B8F95249E6171007A48C9 /* Trace.swift in Sources */, AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */, AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */, + 566B9C2325C6CC24004542CF /* RowDecodingError.swift in Sources */, AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */, AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */, AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */, @@ -4050,6 +4059,7 @@ 5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */, + 566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */, 5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index f1be5f490..8468ee620 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -449,7 +449,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib }, nil) guard code == SQLITE_OK else { // Assume a GRDB bug: there is no point throwing any error. - fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description) + fatalError(DatabaseError(resultCode: code, message: lastErrorMessage)) } } diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index c46874706..12d847823 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -130,7 +130,7 @@ public final class DatabaseFunction: Hashable { guard code == SQLITE_OK else { // Assume a GRDB bug: there is no point throwing any error. - fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description) + fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage)) } } @@ -146,7 +146,7 @@ public final class DatabaseFunction: Hashable { guard code == SQLITE_OK else { // Assume a GRDB bug: there is no point throwing any error. - fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description) + fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage)) } } diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 60e75ca47..b6545bcda 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -115,6 +115,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon } /// Returns a DatabaseValue initialized from a raw SQLite statement pointer. + @usableFromInline init(sqliteStatement: SQLiteStatement, index: Int32) { switch sqlite3_column_type(sqliteStatement, index) { case SQLITE_NULL: diff --git a/GRDB/Core/DatabaseValueConversion.swift b/GRDB/Core/DatabaseValueConversion.swift index 0bdbbdf0b..cfefa1a28 100644 --- a/GRDB/Core/DatabaseValueConversion.swift +++ b/GRDB/Core/DatabaseValueConversion.swift @@ -1,242 +1,62 @@ -// MARK: - Conversion Context and Errors - -/// A type that helps the user understanding value conversion errors -struct ValueConversionContext: Refinable { - private enum Column { - case columnIndex(Int) - case columnName(String) - } - - var row: Row? - var sql: String? - var arguments: StatementArguments? - private var column: Column? - - func atColumn(_ columnIndex: Int) -> Self { - with(\.column, .columnIndex(columnIndex)) - } - - func atColumn(_ columnName: String) -> Self { - with(\.column, .columnName(columnName)) - } - - var columnIndex: Int? { - guard let column = column else { return nil } - switch column { - case .columnIndex(let index): - return index - case .columnName(let name): - return row?.index(forColumn: name) - } - } - - var columnName: String? { - guard let column = column else { return nil } - switch column { - case .columnIndex(let index): - guard let row = row else { return nil } - return Array(row.columnNames)[index] - case .columnName(let name): - return name - } - } -} - -extension ValueConversionContext { - init(_ statement: SelectStatement) { - self.init( - row: Row(statement: statement).copy(), - sql: statement.sql, - arguments: statement.arguments, - column: nil) - } - - init(_ row: Row) { - if let statement = row.statement { - self.init( - row: row.copy(), - sql: statement.sql, - arguments: statement.arguments, - column: nil) - } else if let sqliteStatement = row.sqliteStatement { - let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators) - self.init( - row: row.copy(), - sql: sql, - arguments: nil, - column: nil) - } else { - self.init( - row: row.copy(), - sql: nil, - arguments: nil, - column: nil) - } - } -} - -/// The canonical conversion error message -/// -/// - parameter dbValue: nil means "missing column" -func conversionErrorMessage( - to: T.Type, - from dbValue: DatabaseValue?, - conversionContext: ValueConversionContext?) --> String -{ - var message: String - var extras: [String] = [] - - if let dbValue = dbValue { - message = "could not convert database value \(dbValue) to \(T.self)" - if let columnName = conversionContext?.columnName { - extras.append("column: `\(columnName)`") - } - if let columnIndex = conversionContext?.columnIndex { - extras.append("column index: \(columnIndex)") - } - } else { - message = "could not read \(T.self) from missing column" - if let columnName = conversionContext?.columnName { - message += " `\(columnName)`" - } - } - - if let row = conversionContext?.row { - extras.append("row: \(row)") - } - - if let sql = conversionContext?.sql { - extras.append("sql: `\(sql)`") - if let arguments = conversionContext?.arguments, arguments.isEmpty == false { - extras.append("arguments: \(arguments)") - } - } - - if extras.isEmpty == false { - message += " (" + extras.joined(separator: ", ") + ")" - } - return message -} - -/// The canonical conversion fatal error -/// -/// - parameter dbValue: nil means "missing column", for consistency with (row["missing"] as DatabaseValue? == nil) -func fatalConversionError( - to: T.Type, - from dbValue: DatabaseValue?, - conversionContext: ValueConversionContext?, - file: StaticString = #file, - line: UInt = #line) --> Never -{ - fatalError( - conversionErrorMessage( - to: T.self, - from: dbValue, - conversionContext: conversionContext), - file: file, - line: line) -} - -@usableFromInline -func fatalConversionError( - to: T.Type, - from dbValue: DatabaseValue?, - in row: Row, - atColumn columnName: String, - file: StaticString = #file, - line: UInt = #line) --> Never -{ - fatalConversionError( - to: T.self, - from: dbValue, - conversionContext: ValueConversionContext(row).atColumn(columnName)) -} - -@usableFromInline -func fatalConversionError( - to: T.Type, - sqliteStatement: SQLiteStatement, - index: Int32, - file: StaticString = #file, - line: UInt = #line) --> Never -{ - let row = Row(sqliteStatement: sqliteStatement) - fatalConversionError( - to: T.self, - from: DatabaseValue(sqliteStatement: sqliteStatement, index: index), - conversionContext: ValueConversionContext(row).atColumn(Int(index))) -} - -@usableFromInline -func fatalConversionError( - to: T.Type, - from dbValue: DatabaseValue?, - sqliteStatement: SQLiteStatement, - index: Int32, - file: StaticString = #file, - line: UInt = #line) --> Never -{ - let row = Row(sqliteStatement: sqliteStatement) - fatalConversionError( - to: T.self, - from: dbValue, - conversionContext: ValueConversionContext(row).atColumn(Int(index))) -} - // MARK: - DatabaseValueConvertible /// Lossless conversions from database values and rows extension DatabaseValueConvertible { @usableFromInline - static func decode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self { + static func decode( + from sqliteStatement: SQLiteStatement, + atUncheckedIndex index: Int32, + context: @autoclosure () -> RowDecodingContext) + throws -> Self + { let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) if let value = fromDatabaseValue(dbValue) { return value } else { - fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index) + throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) } } - + static func decode( from dbValue: DatabaseValue, - conversionContext: @autoclosure () -> ValueConversionContext?) - -> Self + context: @autoclosure () -> RowDecodingContext) + throws -> Self { if let value = fromDatabaseValue(dbValue) { return value } else { - fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext()) + throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) } } - + @usableFromInline - static func decode(from row: Row, atUncheckedIndex index: Int) -> Self { - decode( + static func decode(from row: Row, atUncheckedIndex index: Int) throws -> Self { + try decode( from: row.impl.databaseValue(atUncheckedIndex: index), - conversionContext: ValueConversionContext(row).atColumn(index)) + context: RowDecodingContext(row: row, key: .columnIndex(index))) } - + @usableFromInline - static func decodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? { + static func decodeIfPresent( + from sqliteStatement: SQLiteStatement, + atUncheckedIndex index: Int32, + context: @autoclosure () -> RowDecodingContext) + throws -> Self? + { let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) if let value = fromDatabaseValue(dbValue) { return value } else if dbValue.isNull { return nil } else { - fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index) + throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) } } - + static func decodeIfPresent( from dbValue: DatabaseValue, - conversionContext: @autoclosure () -> ValueConversionContext?) - -> Self? + context: @autoclosure () -> RowDecodingContext) + throws -> Self? { // Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null. if let value = fromDatabaseValue(dbValue) { @@ -244,15 +64,15 @@ extension DatabaseValueConvertible { } else if dbValue.isNull { return nil } else { - fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext()) + throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) } } - + @usableFromInline - static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? { - decodeIfPresent( + static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) throws -> Self? { + try decodeIfPresent( from: row.impl.databaseValue(atUncheckedIndex: index), - conversionContext: ValueConversionContext(row).atColumn(index)) + context: RowDecodingContext(row: row, key: .columnIndex(index))) } } @@ -261,35 +81,70 @@ extension DatabaseValueConvertible { /// Lossless conversions from database values and rows extension DatabaseValueConvertible where Self: StatementColumnConvertible { @inlinable - static func fastDecode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self { - if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { - fatalConversionError(to: Self.self, sqliteStatement: sqliteStatement, index: index) + static func fastDecode( + from sqliteStatement: SQLiteStatement, + atUncheckedIndex index: Int32, + context: @autoclosure () -> RowDecodingContext) + throws -> Self + { + guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL, + let value = self.init(sqliteStatement: sqliteStatement, index: index) + else { + throw RowDecodingError.valueMismatch( + Self.self, + context: context(), + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) } - return self.init(sqliteStatement: sqliteStatement, index: index) + return value } - + @inlinable - static func fastDecode(from row: Row, atUncheckedIndex index: Int) -> Self { + static func fastDecode( + from row: Row, + atUncheckedIndex index: Int) + throws -> Self + { if let sqliteStatement = row.sqliteStatement { - return fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index)) + return try fastDecode( + from: sqliteStatement, + atUncheckedIndex: Int32(index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) } - return row.fastDecode(Self.self, atUncheckedIndex: index) + return try row.fastDecode(Self.self, atUncheckedIndex: index) } - + @inlinable - static func fastDecodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? { + static func fastDecodeIfPresent( + from sqliteStatement: SQLiteStatement, + atUncheckedIndex index: Int32, + context: @autoclosure () -> RowDecodingContext) + throws -> Self? + { if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { return nil } - return self.init(sqliteStatement: sqliteStatement, index: index) - } - - @inlinable - static func fastDecodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? { - if let sqliteStatement = row.sqliteStatement { - return fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index)) + guard let value = self.init(sqliteStatement: sqliteStatement, index: index) else { + throw RowDecodingError.valueMismatch( + Self.self, + context: context(), + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) } - return row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index) + return value + } + + @inlinable + static func fastDecodeIfPresent( + from row: Row, + atUncheckedIndex index: Int) + throws -> Self? + { + if let sqliteStatement = row.sqliteStatement { + return try fastDecodeIfPresent( + from: sqliteStatement, + atUncheckedIndex: Int32(index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } + return try row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index) } } @@ -299,17 +154,17 @@ extension Row { func fastDecode( _ type: Value.Type, atUncheckedIndex index: Int) - -> Value + throws -> Value { - impl.fastDecode(type, atUncheckedIndex: index) + try impl.fastDecode(type, atUncheckedIndex: index) } - + @usableFromInline func fastDecodeIfPresent( _ type: Value.Type, atUncheckedIndex index: Int) - -> Value? + throws -> Value? { - impl.fastDecodeIfPresent(type, atUncheckedIndex: index) + try impl.fastDecodeIfPresent(type, atUncheckedIndex: index) } } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index d0089929e..5a519674e 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -76,7 +76,11 @@ public final class DatabaseValueCursor: Cursor _done = true return nil case SQLITE_ROW: - return Value.decode(from: _sqliteStatement, atUncheckedIndex: _columnIndex) + // TODO GRDB6: don't crash on decoding errors + return try! Value.decode( + from: _sqliteStatement, + atUncheckedIndex: _columnIndex, + context: RowDecodingContext(statement: _statement, index: Int(_columnIndex))) case let code: try _statement.didFail(withResultCode: code) } @@ -131,7 +135,11 @@ public final class NullableDatabaseValueCursor: _done = true return nil case SQLITE_ROW: - return Value.decodeIfPresent(from: _sqliteStatement, atUncheckedIndex: _columnIndex) + // TODO GRDB6: don't crash on decoding errors + return try! Value.decodeIfPresent( + from: _sqliteStatement, + atUncheckedIndex: _columnIndex, + context: RowDecodingContext(statement: _statement, index: Int(_columnIndex))) case let code: try _statement.didFail(withResultCode: code) } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index a73f16977..c13671ad4 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -166,8 +166,9 @@ extension Row { /// Fatal errors if index is out of bounds @inlinable - func _checkIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) { + func checkedIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) -> Int { GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line) + return index } /// Returns true if and only if one column contains a non-null value, or if @@ -202,8 +203,7 @@ extension Row { /// in performance-critical code because it can avoid decoding database /// values. public func hasNull(atIndex index: Int) -> Bool { - _checkIndex(index) - return impl.hasNull(atUncheckedIndex: index) + impl.hasNull(atUncheckedIndex: checkedIndex(index)) } /// Returns Int64, Double, String, Data or nil, depending on the value @@ -212,8 +212,7 @@ extension Row { /// Indexes span from 0 for the leftmost column to (row.count - 1) for the /// righmost column. public subscript(_ index: Int) -> DatabaseValueConvertible? { - _checkIndex(index) - return impl.databaseValue(atUncheckedIndex: index).storage.value + impl.databaseValue(atUncheckedIndex: checkedIndex(index)).storage.value } /// Returns the value at given index, converted to the requested type. @@ -226,8 +225,7 @@ extension Row { /// fail, a fatal error is raised. @inlinable public subscript(_ index: Int) -> Value? { - _checkIndex(index) - return Value.decodeIfPresent(from: self, atUncheckedIndex: index) + try! decodeIfPresent(Value.self, atIndex: index) } /// Returns the value at given index, converted to the requested type. @@ -244,8 +242,7 @@ extension Row { /// (see https://www.sqlite.org/datatype3.html). @inlinable public subscript(_ index: Int) -> Value? { - _checkIndex(index) - return Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index) + try! decodeIfPresent(Value.self, atIndex: index) } /// Returns the value at given index, converted to the requested type. @@ -257,8 +254,7 @@ extension Row { /// SQLite value can not be converted to `Value`. @inlinable public subscript(_ index: Int) -> Value { - _checkIndex(index) - return Value.decode(from: self, atUncheckedIndex: index) + try! decode(Value.self, atIndex: index) } /// Returns the value at given index, converted to the requested type. @@ -274,8 +270,7 @@ extension Row { /// (see https://www.sqlite.org/datatype3.html). @inlinable public subscript(_ index: Int) -> Value { - _checkIndex(index) - return Value.fastDecode(from: self, atUncheckedIndex: index) + try! decode(Value.self, atIndex: index) } /// Returns Int64, Double, String, Data or nil, depending on the value @@ -309,10 +304,7 @@ extension Row { /// `Value`. Should this conversion fail, a fatal error is raised. @inlinable public subscript(_ columnName: String) -> Value? { - guard let index = index(forColumn: columnName) else { - return nil - } - return Value.decodeIfPresent(from: self, atUncheckedIndex: index) + try! decodeIfPresent(Value.self, forKey: columnName) } /// Returns the value at given column, converted to the requested type. @@ -329,10 +321,7 @@ extension Row { /// (see https://www.sqlite.org/datatype3.html). @inlinable public subscript(_ columnName: String) -> Value? { - guard let index = index(forColumn: columnName) else { - return nil - } - return Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index) + try! decodeIfPresent(Value.self, forKey: columnName) } /// Returns the value at given column, converted to the requested type. @@ -346,11 +335,7 @@ extension Row { /// SQLite value can not be converted to `Value`. @inlinable public subscript(_ columnName: String) -> Value { - guard let index = index(forColumn: columnName) else { - // No such column - fatalConversionError(to: Value.self, from: nil, in: self, atColumn: columnName) - } - return Value.decode(from: self, atUncheckedIndex: index) + try! decode(Value.self, forKey: columnName) } /// Returns the value at given column, converted to the requested type. @@ -368,11 +353,7 @@ extension Row { /// (see https://www.sqlite.org/datatype3.html). @inlinable public subscript(_ columnName: String) -> Value { - guard let index = index(forColumn: columnName) else { - // No such column - fatalConversionError(to: Value.self, from: nil, in: self, atColumn: columnName) - } - return Value.fastDecode(from: self, atUncheckedIndex: index) + try! decode(Value.self, forKey: columnName) } /// Returns Int64, Double, String, NSData or nil, depending on the value @@ -397,7 +378,7 @@ extension Row { /// `Value`. Should this conversion fail, a fatal error is raised. @inlinable public subscript(_ column: Column) -> Value? { - self[column.name] + try! decodeIfPresent(Value.self, forKey: column.name) } /// Returns the value at given column, converted to the requested type. @@ -419,7 +400,7 @@ extension Row { Value: DatabaseValueConvertible & StatementColumnConvertible, Column: ColumnExpression { - self[column.name] + try! decodeIfPresent(Value.self, forKey: column.name) } /// Returns the value at given column, converted to the requested type. @@ -433,7 +414,7 @@ extension Row { /// SQLite value can not be converted to `Value`. @inlinable public subscript(_ column: Column) -> Value { - self[column.name] + try! decode(Value.self, forKey: column.name) } /// Returns the value at given column, converted to the requested type. @@ -456,7 +437,7 @@ extension Row { Value: DatabaseValueConvertible & StatementColumnConvertible, Column: ColumnExpression { - self[column.name] + try! decode(Value.self, forKey: column.name) } /// Returns the optional Data at given index. @@ -470,8 +451,7 @@ extension Row { /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. public func dataNoCopy(atIndex index: Int) -> Data? { - _checkIndex(index) - return impl.dataNoCopy(atUncheckedIndex: index) + try! decodeDataNoCopyIfPresent(atIndex: index) } /// Returns the optional Data at given column. @@ -486,10 +466,7 @@ extension Row { /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. public func dataNoCopy(named columnName: String) -> Data? { - guard let index = index(forColumn: columnName) else { - return nil - } - return impl.dataNoCopy(atUncheckedIndex: index) + try! decodeDataNoCopyIfPresent(forKey: columnName) } /// Returns the optional `NSData` at given column. @@ -504,7 +481,7 @@ extension Row { /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. public func dataNoCopy(_ column: Column) -> Data? { - dataNoCopy(named: column.name) + try! decodeDataNoCopyIfPresent(forKey: column.name) } } @@ -557,20 +534,7 @@ extension Row { /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support /// for more information. public subscript(_ scope: String) -> Record { - guard let scopedRow = scopesTree[scope] else { - // Programmer error - let names = scopesTree.names - if names.isEmpty { - fatalError("missing scope `\(scope)` (row: \(self))") - } else { - fatalError("missing scope `\(scope)` (row: \(self), available scopes: \(names.sorted()))") - } - } - guard scopedRow.containsNonNullValue else { - // Programmer error - fatalError("scope `\(scope)` only contains null values (row: \(self))") - } - return Record(row: scopedRow) + try! decode(Record.self, forKey: scope) } /// Returns the eventual record associated with the given scope. @@ -605,10 +569,7 @@ extension Row { /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support /// for more information. public subscript(_ scope: String) -> Record? { - guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else { - return nil - } - return Record(row: scopedRow) + try! decodeIfPresent(Record.self, forKey: scope) } /// Returns the records encoded in the given prefetched rows. @@ -630,21 +591,7 @@ extension Row { Collection: RangeReplaceableCollection, Collection.Element: FetchableRecord { - guard let rows = prefetchedRows[key] else { - // Programmer error - let keys = prefetchedRows.keys - if keys.isEmpty { - fatalError("missing key for prefetched rows `\(key)` (row: \(self))") - } else { - fatalError("missing key for prefetched rows `\(key)` (row: \(self), available keys: \(keys.sorted()))") - } - } - var collection = Collection() - collection.reserveCapacity(rows.count) - for row in rows { - collection.append(Collection.Element(row: row)) - } - return collection + try! decode(Collection.self, forKey: key) } /// Returns the set of records encoded in the given prefetched rows. @@ -661,20 +608,7 @@ extension Row { /// print(books.first!.title) /// // Prints "Moby-Dick" public subscript(_ key: String) -> Set { - guard let rows = prefetchedRows[key] else { - // Programmer error - let keys = prefetchedRows.keys - if keys.isEmpty { - fatalError("missing key for prefetched rows `\(key)` (row: \(self))") - } else { - fatalError("missing key for prefetched rows `\(key)` (row: \(self), available keys: \(keys.sorted()))") - } - } - var set = Set(minimumCapacity: rows.count) - for row in rows { - set.insert(Record(row: row)) - } - return set + try! decode(Set.self, forKey: key) } } @@ -761,6 +695,460 @@ extension Row { } } +// MARK: - Throwing DatabaseValueConvertible Decoding Methods + +extension Row { + /// Returns the value at given index, converted to the requested type. + /// + /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// righmost column. + /// + /// If the SQLite value is NULL, the result is nil. Otherwise the SQLite + /// value is converted to the requested type `Value`. If the conversion + /// fail, a `RowDecodingError` is thrown. + @inlinable + func decodeIfPresent( + _ type: Value.Type = Value.self, + atIndex index: Int) + throws -> Value? + { + try Value.decodeIfPresent(from: self, atUncheckedIndex: checkedIndex(index)) + } + + /// Returns the value at given index, converted to the requested type. + /// + /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// righmost column. + /// + /// If the SQLite value is NULL, or if the conversion fails, a + /// `RowDecodingError` is thrown. + @inlinable + func decode( + _ type: Value.Type = Value.self, + atIndex index: Int) + throws -> Value + { + try Value.decode(from: self, atUncheckedIndex: checkedIndex(index)) + } + + /// Returns the value at given column, converted to the requested type. + /// + /// Column name lookup is case-insensitive, and when several columns have + /// the same name, the leftmost column is considered. + /// + /// If the column is missing or if the SQLite value is NULL, the result is + /// nil. Otherwise the SQLite value is converted to the requested type + /// `Value`. If the conversion fails, a `RowDecodingError` is thrown. + @inlinable + func decodeIfPresent( + _ type: Value.Type = Value.self, + forKey columnName: String) + throws -> Value? + { + guard let index = index(forColumn: columnName) else { + return nil + } + return try Value.decodeIfPresent(from: self, atUncheckedIndex: index) + } + + /// Returns the value at given column, converted to the requested type. + /// + /// Column name lookup is case-insensitive, and when several columns have + /// the same name, the leftmost column is considered. + /// + /// If the row does not contain the column, or if the SQLite value is NULL, + /// or if the SQLite value can not be converted to `Value`, a + /// `RowDecodingError` is thrown. + @inlinable + func decode( + _ type: Value.Type = Value.self, + forKey columnName: String) + throws -> Value + { + guard let index = index(forColumn: columnName) else { + throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self)) + } + return try Value.decode(from: self, atUncheckedIndex: index) + } +} + +// MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods + +extension Row { + /// Returns the value at given index, converted to the requested type. + /// + /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// righmost column. + /// + /// If the SQLite value is NULL, the result is nil. Otherwise the SQLite + /// value is converted to the requested type `Value`. If the conversion + /// fail, a `RowDecodingError` is thrown. + /// + /// This method exists as an optimization opportunity for types that adopt + /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions + /// (see https://www.sqlite.org/datatype3.html). + @inlinable + func decodeIfPresent( + _ type: Value.Type = Value.self, + atIndex index: Int) + throws -> Value? + { + try Value.fastDecodeIfPresent(from: self, atUncheckedIndex: checkedIndex(index)) + } + + /// Returns the value at given index, converted to the requested type. + /// + /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// righmost column. + /// + /// If the SQLite value is NULL, or if the conversion fails, a + /// `RowDecodingError` is thrown. + /// + /// This method exists as an optimization opportunity for types that adopt + /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions + /// (see https://www.sqlite.org/datatype3.html). + @inlinable + func decode( + _ type: Value.Type = Value.self, + atIndex index: Int) + throws -> Value + { + try Value.fastDecode(from: self, atUncheckedIndex: checkedIndex(index)) + } + + /// Returns the value at given column, converted to the requested type. + /// + /// Column name lookup is case-insensitive, and when several columns have + /// the same name, the leftmost column is considered. + /// + /// If the column is missing or if the SQLite value is NULL, the result is + /// nil. Otherwise the SQLite value is converted to the requested type + /// `Value`. If the conversion fails, a `RowDecodingError` is thrown. + /// + /// This method exists as an optimization opportunity for types that adopt + /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions + /// (see https://www.sqlite.org/datatype3.html). + @inlinable + func decodeIfPresent( + _ type: Value.Type = Value.self, + forKey columnName: String) + throws -> Value? + { + guard let index = index(forColumn: columnName) else { + return nil + } + return try Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index) + } + + /// Returns the value at given column, converted to the requested type. + /// + /// Column name lookup is case-insensitive, and when several columns have + /// the same name, the leftmost column is considered. + /// + /// If the row does not contain the column, or if the SQLite value is NULL, + /// or if the SQLite value can not be converted to `Value`, a + /// `RowDecodingError` is thrown. + /// + /// This method exists as an optimization opportunity for types that adopt + /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions + /// (see https://www.sqlite.org/datatype3.html). + @inlinable + func decode( + _ type: Value.Type = Value.self, + forKey columnName: String) + throws -> Value + { + guard let index = index(forColumn: columnName) else { + throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self)) + } + return try Value.fastDecode(from: self, atUncheckedIndex: index) + } +} + +// MARK: - Throwing Data Decoding Methods + +extension Row { + /// Returns the optional Data at given index. + /// + /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// righmost column. + /// + /// If the SQLite value is NULL, the result is nil. If the SQLite value can + /// not be converted to Data, a `RowDecodingError` is thrown. + /// + /// The returned data does not owns its bytes: it must not be used longer + /// than the row's lifetime. + func decodeDataNoCopyIfPresent(atIndex index: Int) throws -> Data? { + try impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: checkedIndex(index)) + } + + /// Returns the Data at given index. + /// + /// Indexes span from 0 for the leftmost column to (row.count - 1) for the + /// righmost column. + /// + /// If the SQLite value is NULL, or if the SQLite value can not be converted + /// to Data, a `RowDecodingError` is thrown. + /// + /// The returned data does not owns its bytes: it must not be used longer + /// than the row's lifetime. + func decodeDataNoCopy(atIndex index: Int) throws -> Data { + try impl.fastDecodeDataNoCopy(atUncheckedIndex: checkedIndex(index)) + } + + /// Returns the optional Data at given column. + /// + /// Column name lookup is case-insensitive, and when several columns have + /// the same name, the leftmost column is considered. + /// + /// If the column is missing or if the SQLite value is NULL, the result is + /// nil. If the SQLite value can not be converted to Data, a + /// `RowDecodingError` is thrown. + /// + /// The returned data does not owns its bytes: it must not be used longer + /// than the row's lifetime. + func decodeDataNoCopyIfPresent(forKey columnName: String) throws -> Data? { + guard let index = index(forColumn: columnName) else { + return nil + } + return try impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index) + } + + /// Returns the Data at given column. + /// + /// Column name lookup is case-insensitive, and when several columns have + /// the same name, the leftmost column is considered. + /// + /// If the column is missing, or if the SQLite value is NULL, or if the + /// SQLite value can not be converted to Data, a + /// `RowDecodingError` is thrown. + /// + /// The returned data does not owns its bytes: it must not be used longer + /// than the row's lifetime. + func decodeDataNoCopy(forKey columnName: String) throws -> Data { + guard let index = index(forColumn: columnName) else { + throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self)) + } + return try impl.fastDecodeDataNoCopy(atUncheckedIndex: index) + } +} + +// MARK: - Throwing Record Decoding Methods + +extension Row { + /// Returns the eventual record associated with the given scope. + /// + /// For example: + /// + /// let request = Book.including(optional: Book.author) + /// let row = try Row.fetchOne(db, request)! + /// + /// print(Book(row: row).title) + /// // Prints "Moby-Dick" + /// + /// let author: Author? = row["author"] + /// print(author.name) + /// // Prints "Herman Melville" + /// + /// Associated records stored in nested associations are available, too: + /// + /// let request = Book.including(optional: Book.author.including(optional: Author.country)) + /// let row = try Row.fetchOne(db, request)! + /// + /// print(Book(row: row).title) + /// // Prints "Moby-Dick" + /// + /// let country: Country? = row["country"] + /// print(country.name) + /// // Prints "United States" + /// + /// Nil is returned if the scope is not available, or contains only + /// null values. + /// + /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support + /// for more information. + func decodeIfPresent( + _ type: Record.Type = Record.self, + forKey scope: String) + throws -> Record? + { + guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else { + return nil + } + return Record(row: scopedRow) + } + + /// Returns the record associated with the given scope. + /// + /// For example: + /// + /// let request = Book.including(required: Book.author) + /// let row = try Row.fetchOne(db, request)! + /// + /// print(Book(row: row).title) + /// // Prints "Moby-Dick" + /// + /// let author: Author = row["author"] + /// print(author.name) + /// // Prints "Herman Melville" + /// + /// Associated records stored in nested associations are available, too: + /// + /// let request = Book.including(required: Book.author.including(required: Author.country)) + /// let row = try Row.fetchOne(db, request)! + /// + /// print(Book(row: row).title) + /// // Prints "Moby-Dick" + /// + /// let country: Country = row["country"] + /// print(country.name) + /// // Prints "United States" + /// + /// A fatal error is raised if the scope is not available, or contains only + /// null values. + /// + /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support + /// for more information. + func decode( + _ type: Record.Type = Record.self, + forKey scope: String) + throws -> Record + { + guard let scopedRow = scopesTree[scope] else { + let availableScopes = scopesTree.names + if availableScopes.isEmpty { + throw RowDecodingError.keyNotFound( + .scope(scope), + RowDecodingError.Context( + decodingContext: RowDecodingContext(row: self), + debugDescription: """ + scope not found: \(String(reflecting: scope)) + """)) + } else { + throw RowDecodingError.keyNotFound( + .scope(scope), + RowDecodingError.Context( + decodingContext: RowDecodingContext(row: self), + debugDescription: """ + scope not found: \(String(reflecting: scope)) - \ + available scopes: \(availableScopes.sorted()) + """)) + } + } + guard scopedRow.containsNonNullValue else { + throw RowDecodingError.valueMismatch( + Record.self, + RowDecodingError.Context( + decodingContext: RowDecodingContext(row: self, key: .scope(scope)), + debugDescription: """ + scope \(String(reflecting: scope)) only contains null values + """)) + } + return Record(row: scopedRow) + } +} + +// MARK: - Throwing Record RangeReplaceableCollection and Set Methods + +extension Row { + /// Returns the records encoded in the given prefetched rows. + /// + /// For example: + /// + /// let request = Author.including(all: Author.books) + /// let row = try Row.fetchOne(db, request)! + /// + /// print(Author(row: row).name) + /// // Prints "Herman Melville" + /// + /// let books: [Book] = row["books"] + /// print(books[0].title) + /// // Prints "Moby-Dick" + func decode( + _ type: Collection.Type = Collection.self, + forKey key: String) + throws -> Collection + where + Collection: RangeReplaceableCollection, + Collection.Element: FetchableRecord + { + guard let rows = prefetchedRows[key] else { + let availableKeys = prefetchedRows.keys + if availableKeys.isEmpty { + throw RowDecodingError.keyNotFound( + .prefetchKey(key), + RowDecodingError.Context( + decodingContext: RowDecodingContext(row: self), + debugDescription: """ + key for prefetched rows not found: \(String(reflecting: key)) + """)) + } else { + throw RowDecodingError.keyNotFound( + .prefetchKey(key), + RowDecodingError.Context( + decodingContext: RowDecodingContext(row: self), + debugDescription: """ + key for prefetched rows not found: \(String(reflecting: key)) \ + - available keys: \(availableKeys.sorted()) + """)) + } + } + + var collection = Collection() + collection.reserveCapacity(rows.count) + for row in rows { + collection.append(Collection.Element(row: row)) + } + return collection + } + + /// Returns the set of records encoded in the given prefetched rows. + /// + /// For example: + /// + /// let request = Author.including(all: Author.books) + /// let row = try Row.fetchOne(db, request)! + /// + /// print(Author(row: row).name) + /// // Prints "Herman Melville" + /// + /// let books: Set = row["books"] + /// print(books.first!.title) + /// // Prints "Moby-Dick" + func decode( + _ type: Set.Type = Set.self, + forKey key: String) + throws -> Set + { + guard let rows = prefetchedRows[key] else { + let availableKeys = prefetchedRows.keys + if availableKeys.isEmpty { + throw RowDecodingError.keyNotFound( + .prefetchKey(key), + RowDecodingError.Context( + decodingContext: RowDecodingContext(row: self), + debugDescription: """ + key for prefetched rows not found: \(String(reflecting: key)) + """)) + } else { + throw RowDecodingError.keyNotFound( + .prefetchKey(key), + RowDecodingError.Context( + decodingContext: RowDecodingContext(row: self), + debugDescription: """ + key for prefetched rows not found: \(String(reflecting: key)) \ + - available keys: \(availableKeys.sorted()) + """)) + } + } + var set = Set(minimumCapacity: rows.count) + for row in rows { + set.insert(Record(row: row)) + } + return set + } +} + // MARK: - RowCursor /// A cursor of database rows. For example: @@ -1218,8 +1606,7 @@ extension Row { /// Accesses the (ColumnName, DatabaseValue) pair at given index. public subscript(position: RowIndex) -> (String, DatabaseValue) { - let index = position.index - _checkIndex(index) + let index = checkedIndex(position.index) return ( impl.columnName(atUncheckedIndex: index), impl.databaseValue(atUncheckedIndex: index)) @@ -1647,15 +2034,20 @@ protocol RowImpl { func columnName(atUncheckedIndex index: Int) -> String func hasNull(atUncheckedIndex index: Int) -> Bool func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue + func fastDecode( _ type: Value.Type, atUncheckedIndex index: Int) - -> Value + throws -> Value + func fastDecodeIfPresent( _ type: Value.Type, atUncheckedIndex index: Int) - -> Value? - func dataNoCopy(atUncheckedIndex index: Int) -> Data? + throws -> Value? + + func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data + + func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? /// Returns the index of the leftmost column that matches *name* (case-insensitive) func index(forColumn name: String) -> Int? @@ -1694,29 +2086,38 @@ extension RowImpl { func fastDecode( _ type: Value.Type, - atUncheckedIndex index: Int) -> Value + atUncheckedIndex index: Int) + throws -> Value { // unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization) - return Value.decode( + return try Value.decode( from: databaseValue(atUncheckedIndex: index), - conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index)) + context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) } func fastDecodeIfPresent( _ type: Value.Type, - atUncheckedIndex index: Int) -> Value? + atUncheckedIndex index: Int) + throws -> Value? { // unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization) - return Value.decodeIfPresent( + return try Value.decodeIfPresent( from: databaseValue(atUncheckedIndex: index), - conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index)) + context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) } - func dataNoCopy(atUncheckedIndex index: Int) -> Data? { + func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization) - return Data.decodeIfPresent( + return try Data.decode( from: databaseValue(atUncheckedIndex: index), - conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index)) + context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) + } + + func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? { + // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization) + return try Data.decodeIfPresent( + from: databaseValue(atUncheckedIndex: index), + context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) } } @@ -1820,9 +2221,35 @@ private struct StatementRowImpl: RowImpl { return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL } - func dataNoCopy(atUncheckedIndex index: Int) -> Data? { + func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { + DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index)) + } + + func fastDecode( + _ type: Value.Type, + atUncheckedIndex index: Int) + throws -> Value + { + try Value.fastDecode( + from: sqliteStatement, + atUncheckedIndex: Int32(index), + context: RowDecodingContext(statement: statement, index: index)) + } + + func fastDecodeIfPresent( + _ type: Value.Type, + atUncheckedIndex index: Int) + throws -> Value? + { + try Value.fastDecodeIfPresent( + from: sqliteStatement, + atUncheckedIndex: Int32(index), + context: RowDecodingContext(statement: statement, index: index)) + } + + func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { - return nil + throw RowDecodingError.valueMismatch(Data.self, statement: statement, index: index) } guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else { return Data() @@ -1831,22 +2258,15 @@ private struct StatementRowImpl: RowImpl { return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) } - func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue { - DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index)) - } - - func fastDecode( - _ type: Value.Type, - atUncheckedIndex index: Int) -> Value - { - Value.fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index)) - } - - func fastDecodeIfPresent( - _ type: Value.Type, - atUncheckedIndex index: Int) -> Value? - { - Value.fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index)) + func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? { + guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { + return nil + } + guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else { + return Data() + } + let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index))) + return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) } func columnName(atUncheckedIndex index: Int) -> String { @@ -1879,17 +2299,6 @@ private struct SQLiteStatementRowImpl: RowImpl { DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index)) } - func dataNoCopy(atUncheckedIndex index: Int) -> Data? { - guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { - return nil - } - guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else { - return Data() - } - let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index))) - return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) - } - func index(forColumn name: String) -> Int? { let name = name.lowercased() for index in 0..( _ type: Value.Type, - atUncheckedIndex index: Int) -> Value + atUncheckedIndex index: Int) + throws -> Value { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) - return Value.fastDecode(from: base, atUncheckedIndex: mappedIndex) + return try Value.fastDecode(from: base, atUncheckedIndex: mappedIndex) } func fastDecodeIfPresent( _ type: Value.Type, - atUncheckedIndex index: Int) -> Value? + atUncheckedIndex index: Int) + throws -> Value? { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) - return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex) + return try Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex) } - func dataNoCopy(atUncheckedIndex index: Int) -> Data? { + func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) - return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex) + return try base.impl.fastDecodeDataNoCopy(atUncheckedIndex: mappedIndex) + } + + func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? { + let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) + return try base.impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: mappedIndex) } func columnName(atUncheckedIndex index: Int) -> String { diff --git a/GRDB/Core/RowDecodingError.swift b/GRDB/Core/RowDecodingError.swift new file mode 100644 index 000000000..ded2d9427 --- /dev/null +++ b/GRDB/Core/RowDecodingError.swift @@ -0,0 +1,190 @@ +/// A key that is used to decode a value in a row +@usableFromInline +enum RowKey: Hashable { + /// A column name + case columnName(String) + + /// A column index + case columnIndex(Int) + + /// A scope + case scope(String) + + /// A key of prefetched rows + case prefetchKey(String) +} + +/// A decoding error +@usableFromInline +enum RowDecodingError: Error { + @usableFromInline + struct Context: CustomDebugStringConvertible { + /// A description of what went wrong, for debugging purposes. + @usableFromInline + let debugDescription: String + + /// The row that could not be decoded + let row: Row + + /// Nil for RowDecodingError.keyNotFound, in order to avoid redundancy + let key: RowKey? + + /// The SQL query + let sql: String? + + /// The SQL query arguments + let statementArguments: StatementArguments? + + @usableFromInline + init(decodingContext: RowDecodingContext, debugDescription: String) { + self.debugDescription = debugDescription + self.row = decodingContext.row + self.key = decodingContext.key + self.sql = decodingContext.sql + self.statementArguments = decodingContext.statementArguments + } + } + + case keyNotFound(RowKey, Context) + case valueMismatch(Any.Type, Context) + + var context: Context { + switch self { + case .keyNotFound(_, let context), + .valueMismatch(_, let context): + return context + } + } + + /// Convenience method that builds the + /// `could not decode from database value ` error message. + @usableFromInline + static func valueMismatch( + _ type: Any.Type, + context: RowDecodingContext, + databaseValue: DatabaseValue) + -> Self + { + valueMismatch( + type, + RowDecodingError.Context(decodingContext: context, debugDescription: """ + could not decode \(type) from database value \(databaseValue) + """)) + } + + /// Convenience method that builds the + /// `could not decode from database value ` error message. + @usableFromInline + static func valueMismatch( + _ type: Any.Type, + statement: SelectStatement, + index: Int) + -> Self + { + valueMismatch( + type, + context: RowDecodingContext(statement: statement, index: index), + databaseValue: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: Int32(index))) + } + + /// Convenience method that builds the `column not found: ` + /// error message. + @usableFromInline + static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self { + keyNotFound( + .columnName(columnName), + RowDecodingError.Context(decodingContext: context, debugDescription: """ + column not found: \(String(reflecting: columnName)) + """)) + } +} + +@usableFromInline +struct RowDecodingContext { + /// The row that is decoded + let row: Row + + let key: RowKey? + + /// The SQL query + let sql: String? + + /// The SQL query arguments + let statementArguments: StatementArguments? + + @usableFromInline + init(row: Row, key: RowKey? = nil) { + if let statement = row.statement { + self.key = key + self.row = row.copy() + self.sql = statement.sql + self.statementArguments = statement.arguments + } else if let sqliteStatement = row.sqliteStatement { + self.key = key + self.row = row.copy() + self.sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators) + self.statementArguments = nil // Can't rebuild them + } else { + self.key = key + self.row = row.copy() + self.sql = nil + self.statementArguments = nil + } + } + + /// Convenience initializer + @usableFromInline + init(statement: SelectStatement, index: Int) { + self.key = .columnIndex(index) + self.row = Row(copiedFromSQLiteStatement: statement.sqliteStatement, statement: statement) + self.sql = statement.sql + self.statementArguments = statement.arguments + } +} + +extension RowDecodingError: CustomStringConvertible { + @usableFromInline + var description: String { + let context = self.context + let row = context.row + var chunks: [String] = [] + + if let key = context.key { + switch key { + case let .columnIndex(columnIndex): + let rowIndex = row.index(row.startIndex, offsetBy: columnIndex) + let columnName = row.columnNames[rowIndex] + chunks.append("column: \(String(reflecting: columnName))") + chunks.append("column index: \(columnIndex)") + + case let .columnName(columnName): + if let columnIndex = row.index(forColumn: columnName) { + chunks.append("column: \(String(reflecting: columnName))") + chunks.append("column index: \(columnIndex)") + } else { + // column name is already mentionned in context.debugDescription + } + + case .prefetchKey: + // key is already mentionned in context.debugDescription + break + + case .scope: + // scope is already mentionned in context.debugDescription + break + } + } + + chunks.append("row: \(row.description)") + + if let sql = context.sql { + chunks.append("sql: `\(sql)`") + } + + if let statementArguments = context.statementArguments { + chunks.append("arguments: \(statementArguments)") + } + + return "\(context.debugDescription) - \(chunks.joined(separator: ", "))" + } +} diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 6e8304333..258b57cc3 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -244,7 +244,7 @@ public class Statement { // It looks like sqlite3_bind_xxx() functions do not access the file system. // They should thus succeed, unless a GRDB bug: there is no point throwing any error. guard code == SQLITE_OK else { - fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description) + fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql)) } } @@ -255,7 +255,7 @@ public class Statement { // no point throwing any error. let code = sqlite3_clear_bindings(sqliteStatement) guard code == SQLITE_OK else { - fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description) + fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql)) } } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 4889d58bb..95673d4b0 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -18,30 +18,28 @@ /// score = row["score"] // there /// } /// } -/// -/// `StatementColumnConvertible` is already adopted by all Swift integer types, -/// `Float`, `Double`, `String`, and `Bool`. public protocol StatementColumnConvertible { - /// Initializes a value from a raw SQLite statement pointer. + /// Initializes a value from a raw SQLite statement pointer, if possible. /// /// For example, here is the how Int64 adopts StatementColumnConvertible: /// /// extension Int64: StatementColumnConvertible { - /// init(sqliteStatement: SQLiteStatement, index: Int32) { + /// init?(sqliteStatement: SQLiteStatement, index: Int32) { /// self = sqlite3_column_int64(sqliteStatement, index) /// } /// } /// - /// This initializer is never called for NULL database values: don't perform - /// any extra check. + /// This initializer is never called for NULL database values. Just return + /// `nil` for failed conversions: GRDB will interpret a nil result as a + /// decoding failure. /// /// See https://www.sqlite.org/c3ref/column_blob.html for more information. /// /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - init(sqliteStatement: SQLiteStatement, index: Int32) + init?(sqliteStatement: SQLiteStatement, index: Int32) } /// A cursor of database values extracted from a single column. @@ -92,7 +90,11 @@ public final class FastDatabaseValueCursor: Decoder { // Don't use DecodingError.keyNotFound: // We need to specifically recognize missing columns in order to // provide correct feedback. - throw MissingColumnError(column: key.stringValue) + throw RowDecodingError.columnNotFound(key.stringValue, context: RowDecodingContext(row: row)) } // TODO: test // See DatabaseValueConversionErrorTests.testDecodableFetchableRecord2 @@ -96,20 +96,22 @@ private struct _RowDecoder: Decoder { } // swiftlint:disable comma - func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { decoder.row[key.stringValue] } - func decode(_ type: Int.Type, forKey key: Key) throws -> Int { decoder.row[key.stringValue] } - func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { decoder.row[key.stringValue] } - func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { decoder.row[key.stringValue] } - func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { decoder.row[key.stringValue] } - func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { decoder.row[key.stringValue] } - func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { decoder.row[key.stringValue] } - func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { decoder.row[key.stringValue] } - func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { decoder.row[key.stringValue] } - func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { decoder.row[key.stringValue] } - func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { decoder.row[key.stringValue] } - func decode(_ type: Float.Type, forKey key: Key) throws -> Float { decoder.row[key.stringValue] } - func decode(_ type: Double.Type, forKey key: Key) throws -> Double { decoder.row[key.stringValue] } - func decode(_ type: String.Type, forKey key: Key) throws -> String { decoder.row[key.stringValue] } + // swiftlint:disable line_length + func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: key.stringValue) } + func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: key.stringValue) } + // swiftlint:enable line_length // swiftlint:enable comma func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T: Decodable { @@ -121,11 +123,11 @@ private struct _RowDecoder: Decoder { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { - return R.databaseDateDecodingStrategy.decodeIfPresent(fromRow: row, columnAtIndex: index) as! T? + return try R.databaseDateDecodingStrategy.decodeIfPresent(fromRow: row, columnAtIndex: index) as! T? } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { - return type.fastDecodeIfPresent(from: row, atUncheckedIndex: index) as! T? + return try type.fastDecodeIfPresent(from: row, atUncheckedIndex: index) as! T? } else if let type = T.self as? DatabaseValueConvertible.Type { - return type.decodeIfPresent(from: row, atUncheckedIndex: index) as! T? + return try type.decodeIfPresent(from: row, atUncheckedIndex: index) as! T? } else if row.impl.hasNull(atUncheckedIndex: index) { return nil } else { @@ -151,11 +153,11 @@ private struct _RowDecoder: Decoder { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { - return R.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: index) as! T + return try R.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: index) as! T } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { - return type.fastDecode(from: row, atUncheckedIndex: index) as! T + return try type.fastDecode(from: row, atUncheckedIndex: index) as! T } else if let type = T.self as? DatabaseValueConvertible.Type { - return type.decode(from: row, atUncheckedIndex: index) as! T + return try type.decode(from: row, atUncheckedIndex: index) as! T } else { return try decode(type, fromRow: row, columnAtIndex: index, key: key) } @@ -246,16 +248,8 @@ private struct _RowDecoder: Decoder { // Prefer FetchableRecord decoding over Decodable. return type.init(row: row) as! T } else { - do { - let decoder = _RowDecoder(row: row, codingPath: codingPath) - return try T(from: decoder) - } catch let error as MissingColumnError { - // Support for DatabaseValueConversionErrorTests.testDecodableFetchableRecord2 - fatalConversionError( - to: type, - from: nil, - conversionContext: ValueConversionContext(row).atColumn(error.column)) - } + let decoder = _RowDecoder(row: row, codingPath: codingPath) + return try T(from: decoder) } } @@ -280,12 +274,7 @@ private struct _RowDecoder: Decoder { return try T(from: columnDecoder) } catch is JSONRequiredError { // Decode from JSON - guard let data = row.dataNoCopy(atIndex: index) else { - fatalConversionError( - to: T.self, - from: row[index], - conversionContext: ValueConversionContext(row).atColumn(index)) - } + let data = try row.decodeDataNoCopy(atIndex: index) return try R .databaseJSONDecoder(for: key.stringValue) .decode(type.self, from: data) @@ -375,30 +364,30 @@ extension ColumnDecoder: SingleValueDecodingContainer { row.hasNull(atIndex: columnIndex) } - func decode(_ type: Bool.Type ) throws -> Bool { row[columnIndex] } - func decode(_ type: Int.Type ) throws -> Int { row[columnIndex] } - func decode(_ type: Int8.Type ) throws -> Int8 { row[columnIndex] } - func decode(_ type: Int16.Type ) throws -> Int16 { row[columnIndex] } - func decode(_ type: Int32.Type ) throws -> Int32 { row[columnIndex] } - func decode(_ type: Int64.Type ) throws -> Int64 { row[columnIndex] } - func decode(_ type: UInt.Type ) throws -> UInt { row[columnIndex] } - func decode(_ type: UInt8.Type ) throws -> UInt8 { row[columnIndex] } - func decode(_ type: UInt16.Type) throws -> UInt16 { row[columnIndex] } - func decode(_ type: UInt32.Type) throws -> UInt32 { row[columnIndex] } - func decode(_ type: UInt64.Type) throws -> UInt64 { row[columnIndex] } - func decode(_ type: Float.Type ) throws -> Float { row[columnIndex] } - func decode(_ type: Double.Type) throws -> Double { row[columnIndex] } - func decode(_ type: String.Type) throws -> String { row[columnIndex] } + func decode(_ type: Bool.Type ) throws -> Bool { try row.decode(atIndex: columnIndex) } + func decode(_ type: Int.Type ) throws -> Int { try row.decode(atIndex: columnIndex) } + func decode(_ type: Int8.Type ) throws -> Int8 { try row.decode(atIndex: columnIndex) } + func decode(_ type: Int16.Type ) throws -> Int16 { try row.decode(atIndex: columnIndex) } + func decode(_ type: Int32.Type ) throws -> Int32 { try row.decode(atIndex: columnIndex) } + func decode(_ type: Int64.Type ) throws -> Int64 { try row.decode(atIndex: columnIndex) } + func decode(_ type: UInt.Type ) throws -> UInt { try row.decode(atIndex: columnIndex) } + func decode(_ type: UInt8.Type ) throws -> UInt8 { try row.decode(atIndex: columnIndex) } + func decode(_ type: UInt16.Type) throws -> UInt16 { try row.decode(atIndex: columnIndex) } + func decode(_ type: UInt32.Type) throws -> UInt32 { try row.decode(atIndex: columnIndex) } + func decode(_ type: UInt64.Type) throws -> UInt64 { try row.decode(atIndex: columnIndex) } + func decode(_ type: Float.Type ) throws -> Float { try row.decode(atIndex: columnIndex) } + func decode(_ type: Double.Type) throws -> Double { try row.decode(atIndex: columnIndex) } + func decode(_ type: String.Type) throws -> String { try row.decode(atIndex: columnIndex) } func decode(_ type: T.Type) throws -> T where T: Decodable { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { - return R.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: columnIndex) as! T + return try R.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: columnIndex) as! T } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { - return type.fastDecode(from: row, atUncheckedIndex: columnIndex) as! T + return try type.fastDecode(from: row, atUncheckedIndex: columnIndex) as! T } else if let type = T.self as? DatabaseValueConvertible.Type { - return type.decode(from: row, atUncheckedIndex: columnIndex) as! T + return try type.decode(from: row, atUncheckedIndex: columnIndex) as! T } else { return try T(from: self) } @@ -408,11 +397,6 @@ extension ColumnDecoder: SingleValueDecodingContainer { /// The error that triggers JSON decoding private struct JSONRequiredError: Error { } -/// The error for missing columns -private struct MissingColumnError: Error { - var column: String -} - @available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) private var iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() @@ -422,36 +406,49 @@ private var iso8601Formatter: ISO8601DateFormatter = { extension DatabaseDateDecodingStrategy { @inline(__always) - fileprivate func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) -> Date? { + fileprivate func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) throws -> Date? { if let sqliteStatement = row.sqliteStatement { - return decodeIfPresent( + return try decodeIfPresent( sqliteStatement: sqliteStatement, - index: Int32(index)) + index: Int32(index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) } else { - return decodeIfPresent( + return try decodeIfPresent( from: row[index], - conversionContext: ValueConversionContext(row).atColumn(index)) + context: RowDecodingContext(row: row, key: .columnIndex(index))) } } @inline(__always) - fileprivate func decode(fromRow row: Row, columnAtIndex index: Int) -> Date { + fileprivate func decode(fromRow row: Row, columnAtIndex index: Int) throws -> Date { if let sqliteStatement = row.sqliteStatement { - return decode( + return try decode( sqliteStatement: sqliteStatement, - index: Int32(index)) + index: Int32(index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) } else { - return decode( + return try decode( from: row[index], - conversionContext: ValueConversionContext(row).atColumn(index)) + context: RowDecodingContext(row: row, key: .columnIndex(index))) } } @inline(__always) - fileprivate func decode(sqliteStatement: SQLiteStatement, index: Int32) -> Date { + fileprivate func decode( + sqliteStatement: SQLiteStatement, + index: Int32, + context: @autoclosure () -> RowDecodingContext) + throws -> Date + { switch self { case .deferredToDate: - return Date(sqliteStatement: sqliteStatement, index: index) + guard let date = Date(sqliteStatement: sqliteStatement, index: index) else { + throw RowDecodingError.valueMismatch( + Date.self, + context: context(), + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) + } + return date case .timeIntervalSinceReferenceDate: let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index) return Date(timeIntervalSinceReferenceDate: timeInterval) @@ -465,7 +462,10 @@ extension DatabaseDateDecodingStrategy { if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) { let string = String(sqliteStatement: sqliteStatement, index: index) guard let date = iso8601Formatter.date(from: string) else { - fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index) + throw RowDecodingError.valueMismatch( + Date.self, + context: context(), + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) } return date } else { @@ -474,51 +474,62 @@ extension DatabaseDateDecodingStrategy { case .formatted(let formatter): let string = String(sqliteStatement: sqliteStatement, index: index) guard let date = formatter.date(from: string) else { - fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index) + throw RowDecodingError.valueMismatch( + Date.self, + context: context(), + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) } return date case .custom(let format): let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) guard let date = format(dbValue) else { - fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index) + throw RowDecodingError.valueMismatch( + Date.self, + context: context(), + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) } return date } } @inline(__always) - fileprivate func decodeIfPresent(sqliteStatement: SQLiteStatement, index: Int32) -> Date? { + fileprivate func decodeIfPresent( + sqliteStatement: SQLiteStatement, + index: Int32, + context: @autoclosure () -> RowDecodingContext) + throws -> Date? + { if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { return nil } - return decode(sqliteStatement: sqliteStatement, index: index) + return try decode(sqliteStatement: sqliteStatement, index: index, context: context()) } @inline(__always) fileprivate func decode( from dbValue: DatabaseValue, - conversionContext: @autoclosure () -> ValueConversionContext?) - -> Date + context: @autoclosure () -> RowDecodingContext) + throws -> Date { if let date = dateFromDatabaseValue(dbValue) { return date } else { - fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext()) + throw RowDecodingError.valueMismatch(Date.self, context: context(), databaseValue: dbValue) } } @inline(__always) fileprivate func decodeIfPresent( from dbValue: DatabaseValue, - conversionContext: @autoclosure () -> ValueConversionContext?) - -> Date? + context: @autoclosure () -> RowDecodingContext) + throws -> Date? { if dbValue.isNull { return nil } else if let date = dateFromDatabaseValue(dbValue) { return date } else { - fatalConversionError(to: Date.self, from: dbValue, conversionContext: conversionContext()) + throw RowDecodingError.valueMismatch(Date.self, context: context(), databaseValue: dbValue) } } diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 64ecfd58b..25eeb027e 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -52,6 +52,11 @@ func GRDBPrecondition( } } +@inlinable +func fatalError(_ error: Error) -> Never { + try! { throw error }() +} + // Workaround Swift inconvenience around factory methods of non-final classes func cast(_ value: T) -> U? { value as? U diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 64ebc63df..6ef912b0c 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -56,6 +56,8 @@ 562205FE1E420EA2005860AC /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; }; 562205FF1E420EA2005860AC /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 562206091E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; }; + 56231E6225CEBF08001DFD2F /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */; }; + 56231E6325CEBF08001DFD2F /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */; }; 5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; }; 5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; }; 562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; @@ -792,6 +794,7 @@ 561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = ""; }; 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = ""; }; 561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = ""; }; + 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; }; @@ -1768,6 +1771,7 @@ 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, + 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */, 56E9FAC32210468500C703A8 /* SQLInterpolation.swift */, @@ -2288,6 +2292,7 @@ F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */, 563B8FBA24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */, 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */, + 56231E6225CEBF08001DFD2F /* RowDecodingError.swift in Sources */, 5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */, 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, 563A4B72242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */, @@ -2646,6 +2651,7 @@ F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */, 563B8FBB24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */, 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */, + 56231E6325CEBF08001DFD2F /* RowDecodingError.swift in Sources */, 5656A8932295BD56001FF3FF /* SQLFunctions.swift in Sources */, 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, 563A4B71242E7CE60075D8CF /* ValueObservationScheduler.swift in Sources */, diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 45166302f..b0bd21231 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -114,10 +114,18 @@ private class UserFetchableRecord2 : FetchableRecord { // MARK: - StatementColumnConvertible private struct UserStatementColumnConvertible1 : StatementColumnConvertible { + init?(sqliteStatement: SQLiteStatement, index: Int32) { } +} + +private struct UserStatementColumnConvertible2 : StatementColumnConvertible { init(sqliteStatement: SQLiteStatement, index: Int32) { } } -private class UserStatementColumnConvertible2 : StatementColumnConvertible { +private class UserStatementColumnConvertible3 : StatementColumnConvertible { + required init?(sqliteStatement: SQLiteStatement, index: Int32) { } +} + +private class UserStatementColumnConvertible4 : StatementColumnConvertible { required init(sqliteStatement: SQLiteStatement, index: Int32) { } } diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift index 30ccd6d47..b390ee7b7 100644 --- a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift @@ -39,7 +39,10 @@ private enum StrategyFormatted: StrategyProvider { } private enum StrategyCustom: StrategyProvider { - static let strategy: DatabaseDateDecodingStrategy = .custom { _ in + static let strategy: DatabaseDateDecodingStrategy = .custom { dbValue in + if dbValue == "invalid".databaseValue { + return nil + } return Date(timeIntervalSinceReferenceDate: 123456) } } @@ -187,6 +190,28 @@ extension DatabaseDateDecodingStrategyTests { XCTAssertEqual(calendar.component(.second, from: date), 3) XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the DateComponents -> Date conversion. Not a big deal. } + + // TODO GRDB6: uncomment test +// // error +// do { +// try test(db, strategy: StrategyDeferredToDate.self, databaseValue: "Yesterday") { date in +// XCTFail("Unexpected Date") +// } +// } catch let error as RowDecodingError { +// switch error { +// case .valueMismatch: +// XCTAssertEqual(error.description, """ +// could not decode Date from database value "Yesterday" - \ +// column: "date", \ +// column index: 0, \ +// row: [date:"Yesterday"], \ +// sql: `SELECT ? AS date`, \ +// arguments: ["Yesterday"] +// """) +// default: +// XCTFail("Unexpected Error") +// } +// } } } } @@ -208,6 +233,30 @@ extension DatabaseDateDecodingStrategyTests { try test(db, strategy: StrategyTimeIntervalSinceReferenceDate.self, databaseValue: 123.456) { date in XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 123.456)) } + + // TODO GRDB6: uncomment test +// // error +// do { +// try test(db, strategy: StrategyTimeIntervalSinceReferenceDate.self, databaseValue: "Yesterday") { date in +// // Decoding from SQLite statement works: +// // "Yesterday" is decoded as 0. +// XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 0)) +// } +// } catch let error as RowDecodingError { +// // Decoding from DatabaseValue does not work: +// // "Yesterday" is not decoded as 0. +// switch error { +// case .valueMismatch: +// XCTAssertEqual(error.description, """ +// could not decode Date from database value "Yesterday" - \ +// column: "date", \ +// column index: 0, \ +// row: [date:"Yesterday"] +// """) +// default: +// XCTFail("Unexpected Error") +// } +// } } } } @@ -229,6 +278,30 @@ extension DatabaseDateDecodingStrategyTests { try test(db, strategy: StrategyTimeIntervalSince1970.self, databaseValue: 123.456) { date in XCTAssertEqual(date, Date(timeIntervalSince1970: 123.456)) } + + // TODO GRDB6: uncomment test +// // error +// do { +// try test(db, strategy: StrategyTimeIntervalSince1970.self, databaseValue: "Yesterday") { date in +// // Decoding from SQLite statement works: +// // "Yesterday" is decoded as 0. +// XCTAssertEqual(date, Date(timeIntervalSince1970: 0)) +// } +// } catch let error as RowDecodingError { +// // Decoding from DatabaseValue does not work: +// // "Yesterday" is not decoded as 0. +// switch error { +// case .valueMismatch: +// XCTAssertEqual(error.description, """ +// could not decode Date from database value "Yesterday" - \ +// column: "date", \ +// column index: 0, \ +// row: [date:"Yesterday"] +// """) +// default: +// XCTFail("Unexpected Error") +// } +// } } } } @@ -260,6 +333,30 @@ extension DatabaseDateDecodingStrategyTests { try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: 123456.789) { date in XCTAssertEqual(date, Date(timeIntervalSince1970: 123456.789 / 1000)) } + + // TODO GRDB6: uncomment test +// // error +// do { +// try test(db, strategy: StrategyMillisecondsSince1970.self, databaseValue: "Yesterday") { date in +// // Decoding from SQLite statement works: +// // "Yesterday" is decoded as 0. +// XCTAssertEqual(date, Date(timeIntervalSince1970: 0)) +// } +// } catch let error as RowDecodingError { +// // Decoding from DatabaseValue does not work: +// // "Yesterday" is not decoded as 0. +// switch error { +// case .valueMismatch: +// XCTAssertEqual(error.description, """ +// could not decode Date from database value "Yesterday" - \ +// column: "date", \ +// column index: 0, \ +// row: [date:"Yesterday"] +// """) +// default: +// XCTFail("Unexpected Error") +// } +// } } } } @@ -287,6 +384,28 @@ extension DatabaseDateDecodingStrategyTests { XCTAssertEqual(calendar.component(.second, from: date), 7) XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) } + + // TODO GRDB6: uncomment test +// // error +// do { +// try test(db, strategy: StrategyIso8601.self, databaseValue: "Yesterday") { date in +// XCTFail("Unexpected Date") +// } +// } catch let error as RowDecodingError { +// switch error { +// case .valueMismatch: +// XCTAssertEqual(error.description, """ +// could not decode Date from database value "Yesterday" - \ +// column: "date", \ +// column index: 0, \ +// row: [date:"Yesterday"], \ +// sql: `SELECT ? AS date`, \ +// arguments: ["Yesterday"] +// """) +// default: +// XCTFail("Unexpected Error") +// } +// } } } } @@ -313,6 +432,28 @@ extension DatabaseDateDecodingStrategyTests { XCTAssertEqual(calendar.component(.second, from: date), 55) XCTAssertEqual(calendar.component(.nanosecond, from: date), 0) } + + // TODO GRDB6: uncomment test +// // error +// do { +// try test(db, strategy: StrategyFormatted.self, databaseValue: "Yesterday") { date in +// XCTFail("Unexpected Date") +// } +// } catch let error as RowDecodingError { +// switch error { +// case .valueMismatch: +// XCTAssertEqual(error.description, """ +// could not decode Date from database value "Yesterday" - \ +// column: "date", \ +// column index: 0, \ +// row: [date:"Yesterday"], \ +// sql: `SELECT ? AS date`, \ +// arguments: ["Yesterday"] +// """) +// default: +// XCTFail("Unexpected Error") +// } +// } } } } @@ -326,9 +467,31 @@ extension DatabaseDateDecodingStrategyTests { try testNullDecoding(db, strategy: StrategyCustom.self) // Date - try test(db, strategy: StrategyCustom.self, databaseValue: "whatever") { date in + try test(db, strategy: StrategyCustom.self, databaseValue: "valid") { date in XCTAssertEqual(date, Date(timeIntervalSinceReferenceDate: 123456)) } + + // TODO GRDB6: uncomment test +// // error +// do { +// try test(db, strategy: StrategyCustom.self, databaseValue: "invalid") { date in +// XCTFail("Unexpected Date") +// } +// } catch let error as RowDecodingError { +// switch error { +// case .valueMismatch: +// XCTAssertEqual(error.description, """ +// could not decode Date from database value "invalid" - \ +// column: "date", \ +// column index: 0, \ +// row: [date:"invalid"], \ +// sql: `SELECT ? AS date`, \ +// arguments: ["invalid"] +// """) +// default: +// XCTFail("Unexpected Error") +// } +// } } } } diff --git a/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift b/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift index 4fcb85eaa..3300ed5e6 100644 --- a/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift @@ -1,15 +1,13 @@ import XCTest @testable import GRDB -// Those tests are tightly coupled to GRDB decoding code. -// Each test comes with the (commented) crashing code snippets that trigger it. class DatabaseValueConversionErrorTests: GRDBTestCase { func testFetchableRecord1() throws { - struct Record: FetchableRecord { + struct Record /* TODO GRDB6: FetchableRecord */ { var name: String - - init(row: Row) { - name = row["name"] + + init(row: Row) throws { + name = try row.decode(forKey: "name") } } @@ -19,25 +17,53 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT ? AS name") statement.arguments = [nil] - let row = try Row.fetchOne(statement)! - // _ = Record(row: row) - XCTAssertEqual( - conversionErrorMessage( - to: String.self, - from: row["name"], - conversionContext: ValueConversionContext(row).atColumn("name")), - "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL])") + do { + let row = try Row.fetchOne(statement)! + _ = try Record(row: row) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["name": nil]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + could not decode String from database value NULL - \ + column: "name", \ + column index: 0, \ + row: [name:NULL] + """) + default: + XCTFail("Unexpected Error") + } + } - // TODO: this test is obsolete since 566f42e8d07e57a0d9c4aec452e3ad7ed15dd59b - // _ = try Record.fetchOne(statement) - try Row.fetchCursor(statement).forEach { row in - XCTAssertEqual( - conversionErrorMessage( - to: String.self, - from: row["name"], - conversionContext: ValueConversionContext(row).atColumn("name")), - "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL], sql: `SELECT ? AS name`, arguments: [NULL])") + do { + // TODO GRDB6: _ = try Record.fetchOne(statement) + _ = try Row.fetchCursor(statement) + .map { try Record(row: $0) } + .next() + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["name": nil]) + XCTAssertEqual(context.sql, "SELECT ? AS name") + XCTAssertEqual(context.statementArguments, [nil]) + XCTAssertEqual(error.description, """ + could not decode String from database value NULL - \ + column: "name", \ + column index: 0, \ + row: [name:NULL], \ + sql: `SELECT ? AS name`, \ + arguments: [NULL] + """) + default: + XCTFail("Unexpected Error") + } } } @@ -45,38 +71,65 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused") statement.arguments = ["ignored"] - let row = try Row.fetchOne(statement)! - // _ = Record(row: row) - XCTAssertEqual( - conversionErrorMessage( - to: String.self, - from: row["name"], - conversionContext: ValueConversionContext(row).atColumn("name")), - "could not read String from missing column `name` (row: [unused:\"ignored\"])") + do { + let row = try Row.fetchOne(statement)! + _ = try Record(row: row) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .keyNotFound(key, context): + XCTAssertEqual(key, .columnName("name")) + XCTAssertEqual(context.key, nil) + XCTAssertEqual(context.row, ["unused": "ignored"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + column not found: "name" - \ + row: [unused:"ignored"] + """) + default: + XCTFail("Unexpected Error") + } + } - // _ = try Record.fetchOne(statement) - try Row.fetchCursor(statement).forEach { row in - XCTAssertEqual( - conversionErrorMessage( - to: String.self, - from: row["name"], - conversionContext: ValueConversionContext(row).atColumn("name")), - "could not read String from missing column `name` (row: [unused:\"ignored\"], sql: `SELECT ? AS unused`, arguments: [\"ignored\"])") + do { + // TODO GRDB6: _ = try Record.fetchOne(statement) + _ = try Row.fetchCursor(statement) + .map { try Record(row: $0) } + .next() + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .keyNotFound(key, context): + XCTAssertEqual(key, .columnName("name")) + XCTAssertEqual(context.key, nil) + XCTAssertEqual(context.row, ["unused": "ignored"]) + XCTAssertEqual(context.sql, "SELECT ? AS unused") + XCTAssertEqual(context.statementArguments, ["ignored"]) + XCTAssertEqual(error.description, """ + column not found: "name" - \ + row: [unused:"ignored"], \ + sql: `SELECT ? AS unused`, \ + arguments: ["ignored"] + """) + default: + XCTFail("Unexpected Error") + } } } } func testFetchableRecord2() throws { - enum Value: String, DatabaseValueConvertible, Decodable { + enum Value: String, DatabaseValueConvertible { case valid } - struct Record: FetchableRecord { + struct Record /* TODO GRDB6: FetchableRecord */ { var value: Value - - init(row: Row) { - value = row["value"] + + init(row: Row) throws { + value = try row.decode(forKey: "value") } } @@ -86,24 +139,53 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT 1, ? AS value") statement.arguments = ["invalid"] - let row = try Row.fetchOne(statement)! - // _ = Record(row: row) - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["value"], - conversionContext: ValueConversionContext(row).atColumn("value")), - "could not convert database value \"invalid\" to \(Value.self) (column: `value`, column index: 1, row: [1:1 value:\"invalid\"])") + do { + let row = try Row.fetchOne(statement)! + _ = try Record(row: row) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(1)) + XCTAssertEqual(context.row, ["1": 1, "value": "invalid"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + could not decode \(Value.self) from database value "invalid" - \ + column: "value", \ + column index: 1, \ + row: [1:1 value:"invalid"] + """) + default: + XCTFail("Unexpected Error") + } + } - // _ = try Record.fetchOne(statement) - try Row.fetchCursor(statement).forEach { row in - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["value"], - conversionContext: ValueConversionContext(row).atColumn("value")), - "could not convert database value \"invalid\" to \(Value.self) (column: `value`, column index: 1, row: [1:1 value:\"invalid\"], sql: `SELECT 1, ? AS value`, arguments: [\"invalid\"])") + do { + // TODO GRDB6: _ = try Record.fetchOne(statement) + _ = try Row.fetchCursor(statement) + .map { try Record(row: $0) } + .next() + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(1)) + XCTAssertEqual(context.row, ["1": 1, "value": "invalid"]) + XCTAssertEqual(context.sql, "SELECT 1, ? AS value") + XCTAssertEqual(context.statementArguments, ["invalid"]) + XCTAssertEqual(error.description, """ + could not decode \(Value.self) from database value "invalid" - \ + column: "value", \ + column index: 1, \ + row: [1:1 value:"invalid"], \ + sql: `SELECT 1, ? AS value`, \ + arguments: ["invalid"] + """) + default: + XCTFail("Unexpected Error") + } } } @@ -111,28 +193,55 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused") statement.arguments = ["ignored"] - let row = try Row.fetchOne(statement)! - // _ = Record(row: row) - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["value"], - conversionContext: ValueConversionContext(row).atColumn("value")), - "could not read \(Value.self) from missing column `value` (row: [unused:\"ignored\"])") + do { + let row = try Row.fetchOne(statement)! + _ = try Record(row: row) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .keyNotFound(key, context): + XCTAssertEqual(key, .columnName("value")) + XCTAssertEqual(context.key, nil) + XCTAssertEqual(context.row, ["unused": "ignored"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + column not found: "value" - \ + row: [unused:"ignored"] + """) + default: + XCTFail("Unexpected Error") + } + } - // _ = try Record.fetchOne(statement) - try Row.fetchCursor(statement).forEach { row in - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["value"], - conversionContext: ValueConversionContext(row).atColumn("value")), - "could not read \(Value.self) from missing column `value` (row: [unused:\"ignored\"], sql: `SELECT ? AS unused`, arguments: [\"ignored\"])") + do { + // TODO GRDB6: _ = try Record.fetchOne(statement) + _ = try Row.fetchCursor(statement) + .map { try Record(row: $0) } + .next() + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .keyNotFound(key, context): + XCTAssertEqual(key, .columnName("value")) + XCTAssertEqual(context.key, nil) + XCTAssertEqual(context.row, ["unused": "ignored"]) + XCTAssertEqual(context.sql, "SELECT ? AS unused") + XCTAssertEqual(context.statementArguments, ["ignored"]) + XCTAssertEqual(error.description, """ + column not found: "value" - \ + row: [unused:"ignored"], \ + sql: `SELECT ? AS unused`, \ + arguments: ["ignored"] + """) + default: + XCTFail("Unexpected Error") + } } } } - + func testDecodableFetchableRecord1() throws { struct Record: Decodable, FetchableRecord { var name: String @@ -145,25 +254,55 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS team") statement.arguments = ["invalid"] - let row = try Row.fetchOne(statement)! - // _ = Record(row: row) - XCTAssertEqual( - conversionErrorMessage( - to: String.self, - from: row["name"], - conversionContext: ValueConversionContext(row).atColumn("name")), - "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"])") + do { + let row = try Row.fetchOne(statement)! + // TODO GRDB6: _ = try Record(row: row) + _ = try RowDecoder().decode(Record.self, from: row) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["name": nil, "team": "invalid"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + could not decode String from database value NULL - \ + column: "name", \ + column index: 0, \ + row: [name:NULL team:"invalid"] + """) + default: + XCTFail("Unexpected Error") + } + } - // TODO: this test is obsolete since 566f42e8d07e57a0d9c4aec452e3ad7ed15dd59b - // _ = try Record.fetchOne(statement) - try Row.fetchCursor(statement).forEach { row in - XCTAssertEqual( - conversionErrorMessage( - to: String.self, - from: row["name"], - conversionContext: ValueConversionContext(row).atColumn("name")), - "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"], sql: `SELECT NULL AS name, ? AS team`, arguments: [\"invalid\"])") + do { + // TODO GRDB6: _ = try Record.fetchOne(statement) + let rows = try Row.fetchCursor(statement) + while let row = try rows.next() { + _ = try RowDecoder().decode(Record.self, from: row) + } + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["name": nil, "team": "invalid"]) + XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team") + XCTAssertEqual(context.statementArguments, ["invalid"]) + XCTAssertEqual(error.description, """ + could not decode String from database value NULL - \ + column: "name", \ + column index: 0, \ + row: [name:NULL team:"invalid"], \ + sql: `SELECT NULL AS name, ? AS team`, \ + arguments: ["invalid"] + """) + default: + XCTFail("Unexpected Error") + } } } @@ -171,24 +310,53 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused") statement.arguments = ["ignored"] - let row = try Row.fetchOne(statement)! - - // _ = Record(row: row) - XCTAssertEqual( - conversionErrorMessage( - to: String.self, - from: row["name"], - conversionContext: ValueConversionContext(row).atColumn("name")), - "could not read String from missing column `name` (row: [unused:\"ignored\"])") - // _ = try Record.fetchOne(statement) - try Row.fetchCursor(statement).forEach { row in - XCTAssertEqual( - conversionErrorMessage( - to: String.self, - from: row["name"], - conversionContext: ValueConversionContext(row).atColumn("name")), - "could not read String from missing column `name` (row: [unused:\"ignored\"], sql: `SELECT ? AS unused`, arguments: [\"ignored\"])") + do { + let row = try Row.fetchOne(statement)! + // TODO GRDB6: _ = try Record(row: row) + _ = try RowDecoder().decode(Record.self, from: row) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .keyNotFound(key, context): + XCTAssertEqual(key, .columnName("name")) + XCTAssertEqual(context.key, nil) + XCTAssertEqual(context.row, ["unused": "ignored"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + column not found: "name" - \ + row: [unused:"ignored"] + """) + default: + XCTFail("Unexpected Error") + } + } + + do { + // TODO GRDB6: _ = try Record.fetchOne(statement) + let rows = try Row.fetchCursor(statement) + while let row = try rows.next() { + _ = try RowDecoder().decode(Record.self, from: row) + } + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .keyNotFound(key, context): + XCTAssertEqual(key, .columnName("name")) + XCTAssertEqual(context.key, nil) + XCTAssertEqual(context.row, ["unused": "ignored"]) + XCTAssertEqual(context.sql, "SELECT ? AS unused") + XCTAssertEqual(context.statementArguments, ["ignored"]) + XCTAssertEqual(error.description, """ + column not found: "name" - \ + row: [unused:"ignored"], \ + sql: `SELECT ? AS unused`, \ + arguments: ["ignored"] + """) + default: + XCTFail("Unexpected Error") + } } } } @@ -201,31 +369,62 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { struct Record: Decodable, FetchableRecord { var value: Value } - + let dbQueue = try makeDatabaseQueue() // conversion error try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS value") statement.arguments = ["invalid"] - let row = try Row.fetchOne(statement)! - // _ = Record(row: row) - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["value"], - conversionContext: ValueConversionContext(row).atColumn("value")), - "could not convert database value \"invalid\" to \(Value.self) (column: `value`, column index: 1, row: [name:NULL value:\"invalid\"])") + do { + let row = try Row.fetchOne(statement)! + // TODO GRDB6: _ = try Record(row: row) + _ = try RowDecoder().decode(Record.self, from: row) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(1)) + XCTAssertEqual(context.row, ["name": nil, "value": "invalid"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + could not decode \(Value.self) from database value "invalid" - \ + column: "value", \ + column index: 1, \ + row: [name:NULL value:"invalid"] + """) + default: + XCTFail("Unexpected Error") + } + } - // _ = try Record.fetchOne(statement) - try Row.fetchCursor(statement).forEach { row in - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["value"], - conversionContext: ValueConversionContext(row).atColumn("value")), - "could not convert database value \"invalid\" to \(Value.self) (column: `value`, column index: 1, row: [name:NULL value:\"invalid\"], sql: `SELECT NULL AS name, ? AS value`, arguments: [\"invalid\"])") + do { + // TODO GRDB6: _ = try Record.fetchOne(statement) + let rows = try Row.fetchCursor(statement) + while let row = try rows.next() { + _ = try RowDecoder().decode(Record.self, from: row) + } + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(1)) + XCTAssertEqual(context.row, ["name": nil, "value": "invalid"]) + XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS value") + XCTAssertEqual(context.statementArguments, ["invalid"]) + XCTAssertEqual(error.description, """ + could not decode \(Value.self) from database value "invalid" - \ + column: "value", \ + column index: 1, \ + row: [name:NULL value:"invalid"], \ + sql: `SELECT NULL AS name, ? AS value`, \ + arguments: ["invalid"] + """) + default: + XCTFail("Unexpected Error") + } } } @@ -233,24 +432,53 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused") statement.arguments = ["ignored"] - let row = try Row.fetchOne(statement)! - - // _ = Record(row: row) - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["value"], - conversionContext: ValueConversionContext(row).atColumn("value")), - "could not read \(Value.self) from missing column `value` (row: [unused:\"ignored\"])") - // _ = try Record.fetchOne(statement) - try Row.fetchCursor(statement).forEach { row in - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["value"], - conversionContext: ValueConversionContext(row).atColumn("value")), - "could not read \(Value.self) from missing column `value` (row: [unused:\"ignored\"], sql: `SELECT ? AS unused`, arguments: [\"ignored\"])") + do { + let row = try Row.fetchOne(statement)! + // TODO GRDB6: _ = try Record(row: row) + _ = try RowDecoder().decode(Record.self, from: row) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .keyNotFound(key, context): + XCTAssertEqual(key, .columnName("value")) + XCTAssertEqual(context.key, nil) + XCTAssertEqual(context.row, ["unused": "ignored"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + column not found: "value" - \ + row: [unused:"ignored"] + """) + default: + XCTFail("Unexpected Error") + } + } + + do { + // TODO GRDB6: _ = try Record.fetchOne(statement) + let rows = try Row.fetchCursor(statement) + while let row = try rows.next() { + _ = try RowDecoder().decode(Record.self, from: row) + } + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .keyNotFound(key, context): + XCTAssertEqual(key, .columnName("value")) + XCTAssertEqual(context.key, nil) + XCTAssertEqual(context.row, ["unused": "ignored"]) + XCTAssertEqual(context.sql, "SELECT ? AS unused") + XCTAssertEqual(context.statementArguments, ["ignored"]) + XCTAssertEqual(error.description, """ + column not found: "value" - \ + row: [unused:"ignored"], \ + sql: `SELECT ? AS unused`, \ + arguments: ["ignored"] + """) + default: + XCTFail("Unexpected Error") + } } } } @@ -270,26 +498,53 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS value") statement.arguments = ["invalid"] - let row = try Row.fetchOne(statement)! - // TODO: this test is obsolete since 566f42e8d07e57a0d9c4aec452e3ad7ed15dd59b - // _ = Record(row: row) - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["value"], - conversionContext: ValueConversionContext(row).atColumn("value")), - "could not convert database value \"invalid\" to \(Value.self) (column: `value`, column index: 1, row: [name:NULL value:\"invalid\"])") + do { + let row = try Row.fetchOne(statement)! + // TODO GRDB6: _ = try Record(row: row) + _ = try RowDecoder().decode(Record.self, from: row) + XCTFail("Expected error") + } catch let error as DecodingError { + switch error { + case .dataCorrupted: + break + default: + XCTFail("Unexpected Error") + } + } - // TODO: this test is obsolete since 566f42e8d07e57a0d9c4aec452e3ad7ed15dd59b - // _ = try Record.fetchOne(statement) - try Row.fetchCursor(statement).forEach { row in - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["value"], - conversionContext: ValueConversionContext(row).atColumn("value")), - "could not convert database value \"invalid\" to \(Value.self) (column: `value`, column index: 1, row: [name:NULL value:\"invalid\"], sql: `SELECT NULL AS name, ? AS value`, arguments: [\"invalid\"])") + do { + // TODO GRDB6: _ = try Record.fetchOne(statement) + let rows = try Row.fetchCursor(statement) + while let row = try rows.next() { + _ = try RowDecoder().decode(Record.self, from: row) + } + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["name": nil, "team": "invalid"]) + XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team") + XCTAssertEqual(context.statementArguments, ["invalid"]) + XCTAssertEqual(error.description, """ + could not decode \(Value.self) from database value NULL - \ + column: "name", \ + column index: 0, \ + row: [name:NULL team:"invalid"], \ + sql: `SELECT NULL AS name, ? AS team`, \ + arguments: ["invalid"] + """) + default: + XCTFail("Unexpected Error") + } + } catch let error as DecodingError { + switch error { + case .dataCorrupted: + break + default: + XCTFail("Unexpected Error") + } } } @@ -297,111 +552,234 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT ? AS unused") statement.arguments = ["ignored"] - let row = try Row.fetchOne(statement)! - - // _ = Record(row: row) - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["value"], - conversionContext: ValueConversionContext(row).atColumn("value")), - "could not read \(Value.self) from missing column `value` (row: [unused:\"ignored\"])") - // _ = try Record.fetchOne(statement) - try Row.fetchCursor(statement).forEach { row in - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["value"], - conversionContext: ValueConversionContext(row).atColumn("value")), - "could not read \(Value.self) from missing column `value` (row: [unused:\"ignored\"], sql: `SELECT ? AS unused`, arguments: [\"ignored\"])") + do { + let row = try Row.fetchOne(statement)! + // TODO GRDB6: _ = try Record(row: row) + _ = try RowDecoder().decode(Record.self, from: row) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .keyNotFound(key, context): + XCTAssertEqual(key, .columnName("value")) + XCTAssertEqual(context.key, nil) + XCTAssertEqual(context.row, ["unused": "ignored"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + column not found: "value" - \ + row: [unused:"ignored"] + """) + default: + XCTFail("Unexpected Error") + } + } + + do { + // TODO GRDB6: _ = try Record.fetchOne(statement) + let rows = try Row.fetchCursor(statement) + while let row = try rows.next() { + _ = try RowDecoder().decode(Record.self, from: row) + } + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .keyNotFound(key, context): + XCTAssertEqual(key, .columnName("value")) + XCTAssertEqual(context.key, nil) + XCTAssertEqual(context.row, ["unused": "ignored"]) + XCTAssertEqual(context.sql, "SELECT ? AS unused") + XCTAssertEqual(context.statementArguments, ["ignored"]) + XCTAssertEqual(error.description, """ + column not found: "value" - \ + row: [unused:"ignored"], \ + sql: `SELECT ? AS unused`, \ + arguments: ["ignored"] + """) + default: + XCTFail("Unexpected Error") + } } } } func testStatementColumnConvertible1() throws { - // Those tests are tightly coupled to GRDB decoding code. - // Each test comes with one or several commented crashing code snippets that trigger it. let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS team") statement.arguments = ["invalid"] - let row = try Row.fetchOne(statement)! - // TODO: this test is obsolete since 566f42e8d07e57a0d9c4aec452e3ad7ed15dd59b - // _ = try String.fetchAll(statement) - try statement.makeCursor().forEach { - XCTAssertEqual( - conversionErrorMessage( - to: String.self, - from: .null, - conversionContext: ValueConversionContext(statement).atColumn(0)), - "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"], sql: `SELECT NULL AS name, ? AS team`, arguments: [\"invalid\"])") + do { + // TODO GRDB6: _ = try String.fetchAll(statement) + _ = try Row.fetchCursor(statement) + .map { try $0.fastDecode(String.self, atUncheckedIndex: 0) } + .next() + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["name": nil, "team": "invalid"]) + XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team") + XCTAssertEqual(context.statementArguments, ["invalid"]) + XCTAssertEqual(error.description, """ + could not decode String from database value NULL - \ + column: "name", \ + column index: 0, \ + row: [name:NULL team:"invalid"], \ + sql: `SELECT NULL AS name, ? AS team`, \ + arguments: ["invalid"] + """) + default: + XCTFail("Unexpected Error") + } } - // _ = row["name"] as String - XCTAssertEqual( - conversionErrorMessage( - to: String.self, - from: row["name"], - conversionContext: ValueConversionContext(row).atColumn("name")), - "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"])") + do { + let row = try Row.fetchOne(statement)! + _ = try row.decode(String.self, forKey: "name") + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["name": nil, "team": "invalid"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + could not decode String from database value NULL - \ + column: "name", \ + column index: 0, \ + row: [name:NULL team:"invalid"] + """) + default: + XCTFail("Unexpected Error") + } + } - // _ = row[0] as String - XCTAssertEqual( - conversionErrorMessage( - to: String.self, - from: row[0], - conversionContext: ValueConversionContext(row).atColumn(0)), - "could not convert database value NULL to String (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"])") + do { + let row = try Row.fetchOne(statement)! + _ = try row.decode(String.self, atIndex: 0) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["name": nil, "team": "invalid"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + could not decode String from database value NULL - \ + column: "name", \ + column index: 0, \ + row: [name:NULL team:"invalid"] + """) + default: + XCTFail("Unexpected Error") + } + } } } func testStatementColumnConvertible2() throws { - // Those tests are tightly coupled to GRDB decoding code. - // Each test comes with one or several commented crashing code snippets that trigger it. let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT ? AS foo") statement.arguments = [1000] - let row = try Row.fetchOne(statement)! - // _ = try Row.fetchCursor(statement).map { $0["missing"] as Int8 }.next() - try Row.fetchCursor(statement).forEach { row in - XCTAssertEqual( - conversionErrorMessage( - to: Int8.self, - from: nil, - conversionContext: ValueConversionContext(row).atColumn("missing")), - "could not read Int8 from missing column `missing` (row: [foo:1000], sql: `SELECT ? AS foo`, arguments: [1000])") + do { + _ = try Row.fetchCursor(statement) + .map { try $0.decode(Int8.self, forKey: "missing") } + .next() + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .keyNotFound(key, context): + XCTAssertEqual(key, .columnName("missing")) + XCTAssertEqual(context.key, nil) + XCTAssertEqual(context.row, ["foo": 1000]) + XCTAssertEqual(context.sql, "SELECT ? AS foo") + XCTAssertEqual(context.statementArguments, [1000]) + XCTAssertEqual(error.description, """ + column not found: "missing" - \ + row: [foo:1000], \ + sql: `SELECT ? AS foo`, \ + arguments: [1000] + """) + default: + XCTFail("Unexpected Error") + } } - // _ = try Int8.fetchAll(statement) - try statement.makeCursor().forEach { - let sqliteStatement = statement.sqliteStatement - XCTAssertEqual( - conversionErrorMessage( - to: Int8.self, - from: DatabaseValue(sqliteStatement: sqliteStatement, index: 0), - conversionContext: ValueConversionContext(Row(sqliteStatement: sqliteStatement)).atColumn(0)), - "could not convert database value 1000 to Int8 (column: `foo`, column index: 0, row: [foo:1000], sql: `SELECT ? AS foo`)") + do { + // TODO GRDB6: _ = try Int8.fetchAll(statement) + _ = try Row.fetchCursor(statement) + .map { try $0.fastDecode(Int8.self, atUncheckedIndex: 0) } + .next() + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["foo": 1000]) + XCTAssertEqual(context.sql, "SELECT ? AS foo") + XCTAssertEqual(context.statementArguments, [1000]) + XCTAssertEqual(error.description, """ + could not decode Int8 from database value 1000 - \ + column: "foo", \ + column index: 0, \ + row: [foo:1000], \ + sql: `SELECT ? AS foo`, \ + arguments: [1000] + """) + default: + XCTFail("Unexpected Error") + } } - // _ = row["foo"] as Int8 - XCTAssertEqual( - conversionErrorMessage( - to: Int8.self, - from: row["foo"], - conversionContext: ValueConversionContext(row).atColumn("foo")), - "could not convert database value 1000 to Int8 (column: `foo`, column index: 0, row: [foo:1000])") + do { + let row = try Row.fetchOne(statement)! + _ = try row.decode(Int8.self, forKey: "foo") + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["foo": 1000]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + could not decode Int8 from database value 1000 - \ + column: "foo", \ + column index: 0, \ + row: [foo:1000] + """) + default: + XCTFail("Unexpected Error") + } + } - // _ = row[0] as Int8 - XCTAssertEqual( - conversionErrorMessage( - to: Int8.self, - from: row[0], - conversionContext: ValueConversionContext(row).atColumn(0)), - "could not convert database value 1000 to Int8 (column: `foo`, column index: 0, row: [foo:1000])") + do { + let row = try Row.fetchOne(statement)! + _ = try row.decode(Int8.self, atIndex: 0) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["foo": 1000]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + could not decode Int8 from database value 1000 - \ + column: "foo", \ + column index: 0, \ + row: [foo:1000] + """) + default: + XCTFail("Unexpected Error") + } + } } } @@ -410,51 +788,128 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { case valid } - // Those tests are tightly coupled to GRDB decoding code. - // Each test comes with one or several commented crashing code snippets that trigger it. let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let statement = try db.makeSelectStatement(sql: "SELECT NULL AS name, ? AS team") statement.arguments = ["invalid"] - let row = try Row.fetchOne(statement)! - // _ = try Value.fetchAll(statement) - try statement.makeCursor().forEach { - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: 0), - conversionContext: ValueConversionContext(statement).atColumn(0)), - "could not convert database value NULL to \(Value.self) (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"], sql: `SELECT NULL AS name, ? AS team`, arguments: [\"invalid\"])") + do { + // TODO GRDB6: _ = try Value.fetchAll(statement) + _ = try Row.fetchCursor(statement) + .map { try $0.decode(Value.self, atIndex: 0) } + .next() + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["name": nil, "team": "invalid"]) + XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team") + XCTAssertEqual(context.statementArguments, ["invalid"]) + XCTAssertEqual(error.description, """ + could not decode \(Value.self) from database value NULL - \ + column: "name", \ + column index: 0, \ + row: [name:NULL team:"invalid"], \ + sql: `SELECT NULL AS name, ? AS team`, \ + arguments: ["invalid"] + """) + default: + XCTFail("Unexpected Error") + } } - // _ = try Value.fetchOne(statement, adapter: SuffixRowAdapter(fromIndex: 1)) - let adapter = SuffixRowAdapter(fromIndex: 1) - let columnIndex = try adapter.baseColumnIndex(atIndex: 0, layout: statement) - try statement.makeCursor().forEach { _ in - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: Int32(columnIndex)), - conversionContext: ValueConversionContext(statement).atColumn(columnIndex)), - "could not convert database value \"invalid\" to \(Value.self) (column: `team`, column index: 1, row: [name:NULL team:\"invalid\"], sql: `SELECT NULL AS name, ? AS team`, arguments: [\"invalid\"])") + do { + // TODO GRDB6: _ = try Value.fetchOne(statement, adapter: SuffixRowAdapter(fromIndex: 1)) + _ = try Row.fetchCursor(statement) + .map { try $0.decode(Value.self, atIndex: 1) } + .next() + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(1)) + XCTAssertEqual(context.row, ["name": nil, "team": "invalid"]) + XCTAssertEqual(context.sql, "SELECT NULL AS name, ? AS team") + XCTAssertEqual(context.statementArguments, ["invalid"]) + XCTAssertEqual(error.description, """ + could not decode \(Value.self) from database value "invalid" - \ + column: "team", \ + column index: 1, \ + row: [name:NULL team:"invalid"], \ + sql: `SELECT NULL AS name, ? AS team`, \ + arguments: ["invalid"] + """) + default: + XCTFail("Unexpected Error") + } } - // _ = row["name"] as Value - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row["name"], - conversionContext: ValueConversionContext(row).atColumn("name")), - "could not convert database value NULL to \(Value.self) (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"])") + do { + let row = try Row.fetchOne(statement)! + _ = try row.decode(Value.self, forKey: "name") + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["name": nil, "team": "invalid"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + could not decode \(Value.self) from database value NULL - \ + column: "name", \ + column index: 0, \ + row: [name:NULL team:"invalid"] + """) + default: + XCTFail("Unexpected Error") + } + } - // _ = row[0] as Value - XCTAssertEqual( - conversionErrorMessage( - to: Value.self, - from: row[0], - conversionContext: ValueConversionContext(row).atColumn(0)), - "could not convert database value NULL to \(Value.self) (column: `name`, column index: 0, row: [name:NULL team:\"invalid\"])") + do { + let row = try Row.fetchOne(statement)! + _ = try row.decode(Value.self, atIndex: 0) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["name": nil, "team": "invalid"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + could not decode \(Value.self) from database value NULL - \ + column: "name", \ + column index: 0, \ + row: [name:NULL team:"invalid"] + """) + default: + XCTFail("Unexpected Error") + } + } + + do { + let row = try Row.fetchOne(statement, adapter: SuffixRowAdapter(fromIndex: 1))! + _ = try row.decode(Value.self, atIndex: 0) + XCTFail("Expected error") + } catch let error as RowDecodingError { + switch error { + case let .valueMismatch(_, context): + XCTAssertEqual(context.key, .columnIndex(0)) + XCTAssertEqual(context.row, ["team": "invalid"]) + XCTAssertEqual(context.sql, nil) + XCTAssertEqual(context.statementArguments, nil) + XCTAssertEqual(error.description, """ + could not decode \(Value.self) from database value "invalid" - \ + column: "team", \ + column index: 0, \ + row: [team:"invalid"] + """) + default: + XCTFail("Unexpected Error") + } + } } } } diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index c105cd726..b3ec3726e 100644 --- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift +++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift @@ -1,6 +1,7 @@ import XCTest import GRDB +#warning("TODO: test decoding error") // A type that adopts DatabaseValueConvertible and StatementColumnConvertible private struct Fetched: DatabaseValueConvertible, StatementColumnConvertible, Hashable { let int: Int From b7c57dc7f2c30003dc127b6a717a36491fc8c49e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 25 Feb 2021 20:45:12 +0100 Subject: [PATCH 24/35] Attempt at clarifying the (complex) decoding api The difficulty is due to fast decoding of StatementColumnConvertible, and non-copied Data, from raw SQLite statement. We want it to be inlinable, and possible in nested rows. Added missing tests for nested rows --- .../xcschemes/GRDBDemoWatchOS.xcscheme | 25 ++- GRDB.xcodeproj/project.pbxproj | 10 -- GRDB/Core/DatabaseValueConversion.swift | 170 ------------------ GRDB/Core/DatabaseValueConvertible.swift | 79 +++++++- GRDB/Core/Row.swift | 60 +++++-- GRDB/Core/RowAdapter.swift | 4 +- GRDB/Core/StatementColumnConvertible.swift | 81 ++++++++- GRDB/Core/Support/Foundation/Data.swift | 73 ++++++++ GRDB/Record/FetchableRecord+Decodable.swift | 50 +++--- GRDBCustom.xcodeproj/project.pbxproj | 6 - Tests/GRDBTests/DataMemoryTests.swift | 108 +++++++---- .../DatabaseValueConversionErrorTests.swift | 8 +- ...StatementColumnConvertibleFetchTests.swift | 36 ++++ 13 files changed, 430 insertions(+), 280 deletions(-) delete mode 100644 GRDB/Core/DatabaseValueConversion.swift diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme index 237e9f7b3..4fbad19f2 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme @@ -78,8 +78,10 @@ debugDocumentVersioning = "YES" debugServiceExtension = "internal" allowLocationSimulation = "YES"> - + - + - + - + + + + + diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 2857a6677..85df6e3db 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -267,9 +267,6 @@ 564390D52414FC2C00BA61E6 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AAA4DCFE230F1E0600C74B15 /* GRDB.framework */; }; 564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; - 5644DE6D20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; }; - 5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; }; - 5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; }; 564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; }; 564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; 564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; }; @@ -984,7 +981,6 @@ AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; }; AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; - AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; }; AAA4DCD8230F1E0600C74B15 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1511C672E4000235C62 /* NSNumber.swift */; }; AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */; }; @@ -1342,7 +1338,6 @@ 56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = ""; }; 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; - 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = ""; }; 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = ""; }; @@ -2286,7 +2281,6 @@ 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A84192041146100E50BFD /* DatabaseSnapshot.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, - 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, @@ -2974,7 +2968,6 @@ 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */, - 5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */, 56A2FA3C24424F4800E97D23 /* Export.swift in Sources */, 565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */, 563EF42F2161180D007DAACD /* AssociationAggregate.swift in Sources */, @@ -3108,7 +3101,6 @@ 5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 568ECB1925D9161600B71526 /* SQLSubquery.swift in Sources */, 56FBFED92210731A00945324 /* SQLRequest.swift in Sources */, - 5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */, C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, @@ -3694,7 +3686,6 @@ AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */, 568ECB1B25D9161600B71526 /* SQLSubquery.swift in Sources */, AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */, - AAA4DCD7230F1E0600C74B15 /* DatabaseValueConversion.swift in Sources */, AAA4DCD8230F1E0600C74B15 /* SQLiteDateParser.swift in Sources */, AAA4DCD9230F1E0600C74B15 /* NSNumber.swift in Sources */, AAA4DCDB230F1E0600C74B15 /* DatabaseRegionObservation.swift in Sources */, @@ -4073,7 +4064,6 @@ 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */, - 5644DE6D20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */, 5657AAB91D107001006283EF /* NSData.swift in Sources */, 560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */, diff --git a/GRDB/Core/DatabaseValueConversion.swift b/GRDB/Core/DatabaseValueConversion.swift deleted file mode 100644 index cfefa1a28..000000000 --- a/GRDB/Core/DatabaseValueConversion.swift +++ /dev/null @@ -1,170 +0,0 @@ -// MARK: - DatabaseValueConvertible - -/// Lossless conversions from database values and rows -extension DatabaseValueConvertible { - @usableFromInline - static func decode( - from sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, - context: @autoclosure () -> RowDecodingContext) - throws -> Self - { - let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) - if let value = fromDatabaseValue(dbValue) { - return value - } else { - throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) - } - } - - static func decode( - from dbValue: DatabaseValue, - context: @autoclosure () -> RowDecodingContext) - throws -> Self - { - if let value = fromDatabaseValue(dbValue) { - return value - } else { - throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) - } - } - - @usableFromInline - static func decode(from row: Row, atUncheckedIndex index: Int) throws -> Self { - try decode( - from: row.impl.databaseValue(atUncheckedIndex: index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - - @usableFromInline - static func decodeIfPresent( - from sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, - context: @autoclosure () -> RowDecodingContext) - throws -> Self? - { - let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) - if let value = fromDatabaseValue(dbValue) { - return value - } else if dbValue.isNull { - return nil - } else { - throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) - } - } - - static func decodeIfPresent( - from dbValue: DatabaseValue, - context: @autoclosure () -> RowDecodingContext) - throws -> Self? - { - // Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null. - if let value = fromDatabaseValue(dbValue) { - return value - } else if dbValue.isNull { - return nil - } else { - throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) - } - } - - @usableFromInline - static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) throws -> Self? { - try decodeIfPresent( - from: row.impl.databaseValue(atUncheckedIndex: index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } -} - -// MARK: - DatabaseValueConvertible & StatementColumnConvertible - -/// Lossless conversions from database values and rows -extension DatabaseValueConvertible where Self: StatementColumnConvertible { - @inlinable - static func fastDecode( - from sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, - context: @autoclosure () -> RowDecodingContext) - throws -> Self - { - guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL, - let value = self.init(sqliteStatement: sqliteStatement, index: index) - else { - throw RowDecodingError.valueMismatch( - Self.self, - context: context(), - databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) - } - return value - } - - @inlinable - static func fastDecode( - from row: Row, - atUncheckedIndex index: Int) - throws -> Self - { - if let sqliteStatement = row.sqliteStatement { - return try fastDecode( - from: sqliteStatement, - atUncheckedIndex: Int32(index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - return try row.fastDecode(Self.self, atUncheckedIndex: index) - } - - @inlinable - static func fastDecodeIfPresent( - from sqliteStatement: SQLiteStatement, - atUncheckedIndex index: Int32, - context: @autoclosure () -> RowDecodingContext) - throws -> Self? - { - if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { - return nil - } - guard let value = self.init(sqliteStatement: sqliteStatement, index: index) else { - throw RowDecodingError.valueMismatch( - Self.self, - context: context(), - databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) - } - return value - } - - @inlinable - static func fastDecodeIfPresent( - from row: Row, - atUncheckedIndex index: Int) - throws -> Self? - { - if let sqliteStatement = row.sqliteStatement { - return try fastDecodeIfPresent( - from: sqliteStatement, - atUncheckedIndex: Int32(index), - context: RowDecodingContext(row: row, key: .columnIndex(index))) - } - return try row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index) - } -} - -// Support for @inlinable decoding -extension Row { - @usableFromInline - func fastDecode( - _ type: Value.Type, - atUncheckedIndex index: Int) - throws -> Value - { - try impl.fastDecode(type, atUncheckedIndex: index) - } - - @usableFromInline - func fastDecodeIfPresent( - _ type: Value.Type, - atUncheckedIndex index: Int) - throws -> Value? - { - try impl.fastDecodeIfPresent(type, atUncheckedIndex: index) - } -} diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 5a519674e..ae0ad6445 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -28,6 +28,81 @@ extension DatabaseValueConvertible { } } +// MARK: - Conversions + +extension DatabaseValueConvertible { + static func decode( + fromDatabaseValue dbValue: DatabaseValue, + context: @autoclosure () -> RowDecodingContext) + throws -> Self + { + if let value = fromDatabaseValue(dbValue) { + return value + } else { + throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) + } + } + + @usableFromInline + static func decode( + fromStatement sqliteStatement: SQLiteStatement, + atUncheckedIndex index: Int32, + context: @autoclosure () -> RowDecodingContext) + throws -> Self + { + let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) + return try decode(fromDatabaseValue: dbValue, context: context()) + } + + @usableFromInline + static func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self { + try decode( + fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } + + static func decodeIfPresent( + fromDatabaseValue dbValue: DatabaseValue, + context: @autoclosure () -> RowDecodingContext) + throws -> Self? + { + // Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null. + if let value = fromDatabaseValue(dbValue) { + return value + } else if dbValue.isNull { + return nil + } else { + throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) + } + } + + @usableFromInline + static func decodeIfPresent( + fromStatement sqliteStatement: SQLiteStatement, + atUncheckedIndex index: Int32, + context: @autoclosure () -> RowDecodingContext) + throws -> Self? + { + let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) + if let value = fromDatabaseValue(dbValue) { + return value + } else if dbValue.isNull { + return nil + } else { + throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue) + } + } + + @usableFromInline + static func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self? { + try decodeIfPresent( + fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } +} + +// MARK: - Cursors + /// A cursor of database values extracted from a single column. /// For example: /// @@ -78,7 +153,7 @@ public final class DatabaseValueCursor: Cursor case SQLITE_ROW: // TODO GRDB6: don't crash on decoding errors return try! Value.decode( - from: _sqliteStatement, + fromStatement: _sqliteStatement, atUncheckedIndex: _columnIndex, context: RowDecodingContext(statement: _statement, index: Int(_columnIndex))) case let code: @@ -137,7 +212,7 @@ public final class NullableDatabaseValueCursor: case SQLITE_ROW: // TODO GRDB6: don't crash on decoding errors return try! Value.decodeIfPresent( - from: _sqliteStatement, + fromStatement: _sqliteStatement, atUncheckedIndex: _columnIndex, context: RowDecodingContext(statement: _statement, index: Int(_columnIndex))) case let code: diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index c13671ad4..8b098994e 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -712,7 +712,7 @@ extension Row { atIndex index: Int) throws -> Value? { - try Value.decodeIfPresent(from: self, atUncheckedIndex: checkedIndex(index)) + try Value.decodeIfPresent(fromRow: self, atUncheckedIndex: checkedIndex(index)) } /// Returns the value at given index, converted to the requested type. @@ -728,7 +728,7 @@ extension Row { atIndex index: Int) throws -> Value { - try Value.decode(from: self, atUncheckedIndex: checkedIndex(index)) + try Value.decode(fromRow: self, atUncheckedIndex: checkedIndex(index)) } /// Returns the value at given column, converted to the requested type. @@ -748,7 +748,7 @@ extension Row { guard let index = index(forColumn: columnName) else { return nil } - return try Value.decodeIfPresent(from: self, atUncheckedIndex: index) + return try Value.decodeIfPresent(fromRow: self, atUncheckedIndex: index) } /// Returns the value at given column, converted to the requested type. @@ -768,7 +768,7 @@ extension Row { guard let index = index(forColumn: columnName) else { throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self)) } - return try Value.decode(from: self, atUncheckedIndex: index) + return try Value.decode(fromRow: self, atUncheckedIndex: index) } } @@ -793,7 +793,7 @@ extension Row { atIndex index: Int) throws -> Value? { - try Value.fastDecodeIfPresent(from: self, atUncheckedIndex: checkedIndex(index)) + try Value.fastDecodeIfPresent(fromRow: self, atUncheckedIndex: checkedIndex(index)) } /// Returns the value at given index, converted to the requested type. @@ -813,7 +813,7 @@ extension Row { atIndex index: Int) throws -> Value { - try Value.fastDecode(from: self, atUncheckedIndex: checkedIndex(index)) + try Value.fastDecode(fromRow: self, atUncheckedIndex: checkedIndex(index)) } /// Returns the value at given column, converted to the requested type. @@ -837,7 +837,7 @@ extension Row { guard let index = index(forColumn: columnName) else { return nil } - return try Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index) + return try Value.fastDecodeIfPresent(fromRow: self, atUncheckedIndex: index) } /// Returns the value at given column, converted to the requested type. @@ -861,7 +861,27 @@ extension Row { guard let index = index(forColumn: columnName) else { throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self)) } - return try Value.fastDecode(from: self, atUncheckedIndex: index) + return try Value.fastDecode(fromRow: self, atUncheckedIndex: index) + } + + // Support for fast decoding in scoped rows + @usableFromInline + func fastDecode( + _ type: Value.Type, + atUncheckedIndex index: Int) + throws -> Value + { + try impl.fastDecode(type, atUncheckedIndex: index) + } + + // Support for fast decoding in scoped rows + @usableFromInline + func fastDecodeIfPresent( + _ type: Value.Type, + atUncheckedIndex index: Int) + throws -> Value? + { + try impl.fastDecodeIfPresent(type, atUncheckedIndex: index) } } @@ -931,6 +951,18 @@ extension Row { } return try impl.fastDecodeDataNoCopy(atUncheckedIndex: index) } + + // Support for fast decoding in scoped rows + @usableFromInline + func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { + try impl.fastDecodeDataNoCopy(atUncheckedIndex: index) + } + + // Support for fast decoding in scoped rows + @usableFromInline + func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? { + try impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index) + } } // MARK: - Throwing Record Decoding Methods @@ -2091,7 +2123,7 @@ extension RowImpl { { // unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization) return try Value.decode( - from: databaseValue(atUncheckedIndex: index), + fromDatabaseValue: databaseValue(atUncheckedIndex: index), context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) } @@ -2102,21 +2134,21 @@ extension RowImpl { { // unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization) return try Value.decodeIfPresent( - from: databaseValue(atUncheckedIndex: index), + fromDatabaseValue: databaseValue(atUncheckedIndex: index), context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) } func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization) return try Data.decode( - from: databaseValue(atUncheckedIndex: index), + fromDatabaseValue: databaseValue(atUncheckedIndex: index), context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) } func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? { // unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization) return try Data.decodeIfPresent( - from: databaseValue(atUncheckedIndex: index), + fromDatabaseValue: databaseValue(atUncheckedIndex: index), context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index))) } } @@ -2231,7 +2263,7 @@ private struct StatementRowImpl: RowImpl { throws -> Value { try Value.fastDecode( - from: sqliteStatement, + fromStatement: sqliteStatement, atUncheckedIndex: Int32(index), context: RowDecodingContext(statement: statement, index: index)) } @@ -2242,7 +2274,7 @@ private struct StatementRowImpl: RowImpl { throws -> Value? { try Value.fastDecodeIfPresent( - from: sqliteStatement, + fromStatement: sqliteStatement, atUncheckedIndex: Int32(index), context: RowDecodingContext(statement: statement, index: index)) } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index 8aadc42cd..a7c85d3de 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -498,7 +498,7 @@ struct AdaptedRowImpl: RowImpl { throws -> Value { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) - return try Value.fastDecode(from: base, atUncheckedIndex: mappedIndex) + return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex) } func fastDecodeIfPresent( @@ -507,7 +507,7 @@ struct AdaptedRowImpl: RowImpl { throws -> Value? { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) - return try Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex) + return try Value.fastDecodeIfPresent(fromRow: base, atUncheckedIndex: mappedIndex) } func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data { diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 95673d4b0..e5a75f490 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -42,6 +42,82 @@ public protocol StatementColumnConvertible { init?(sqliteStatement: SQLiteStatement, index: Int32) } +// MARK: - Conversions + +extension DatabaseValueConvertible where Self: StatementColumnConvertible { + @inlinable + static func fastDecode( + fromStatement sqliteStatement: SQLiteStatement, + atUncheckedIndex index: Int32, + context: @autoclosure () -> RowDecodingContext) + throws -> Self + { + guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL, + let value = self.init(sqliteStatement: sqliteStatement, index: index) + else { + throw RowDecodingError.valueMismatch( + Self.self, + context: context(), + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) + } + return value + } + + @inlinable + static func fastDecode( + fromRow row: Row, + atUncheckedIndex index: Int) + throws -> Self + { + if let sqliteStatement = row.sqliteStatement { + return try fastDecode( + fromStatement: sqliteStatement, + atUncheckedIndex: Int32(index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } + // Support for fast decoding from adapted rows + return try row.fastDecode(Self.self, atUncheckedIndex: index) + } + + @inlinable + static func fastDecodeIfPresent( + fromStatement sqliteStatement: SQLiteStatement, + atUncheckedIndex index: Int32, + context: @autoclosure () -> RowDecodingContext) + throws -> Self? + { + if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { + return nil + } + guard let value = self.init(sqliteStatement: sqliteStatement, index: index) else { + #warning("TODO: don't put the DatabaseValue in the inlined code") + throw RowDecodingError.valueMismatch( + Self.self, + context: context(), + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) + } + return value + } + + @inlinable + static func fastDecodeIfPresent( + fromRow row: Row, + atUncheckedIndex index: Int) + throws -> Self? + { + if let sqliteStatement = row.sqliteStatement { + return try fastDecodeIfPresent( + fromStatement: sqliteStatement, + atUncheckedIndex: Int32(index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } + // Support for fast decoding from adapted rows + return try row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index) + } +} + +// MARK: - Cursors + /// A cursor of database values extracted from a single column. /// For example: /// @@ -92,7 +168,7 @@ public final class FastDatabaseValueCursor RowDecodingContext) + throws -> Data + { + guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { + throw RowDecodingError.valueMismatch( + Data.self, + context: context(), + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) + } + guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else { + return Data() + } + let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index))) + return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) + } + + @inlinable + static func fastDecodeNoCopy( + fromRow row: Row, + atUncheckedIndex index: Int) + throws -> Data + { + if let sqliteStatement = row.sqliteStatement { + return try fastDecodeNoCopy( + fromStatement: sqliteStatement, + atUncheckedIndex: Int32(index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } + // Support for fast decoding from adapted rows + return try row.fastDecodeDataNoCopy(atUncheckedIndex: index) + } + + @inlinable + static func fastDecodeNoCopyIfPresent( + fromStatement sqliteStatement: SQLiteStatement, + atUncheckedIndex index: Int32, + context: @autoclosure () -> RowDecodingContext) + throws -> Data? + { + guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { + return nil + } + guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else { + return Data() + } + let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index))) + return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none) + } + + @inlinable + static func fastDecodeNoCopyIfPresent( + fromRow row: Row, + atUncheckedIndex index: Int) + throws -> Data? + { + if let sqliteStatement = row.sqliteStatement { + return try fastDecodeNoCopyIfPresent( + fromStatement: sqliteStatement, + atUncheckedIndex: Int32(index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } + // Support for fast decoding from adapted rows + return try row.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index) + } +} diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index c29df30aa..bdfd96c45 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -123,11 +123,13 @@ private struct _RowDecoder: Decoder { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { - return try R.databaseDateDecodingStrategy.decodeIfPresent(fromRow: row, columnAtIndex: index) as! T? + return try R.databaseDateDecodingStrategy.decodeIfPresent( + fromRow: row, + atUncheckedIndex: index) as! T? } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { - return try type.fastDecodeIfPresent(from: row, atUncheckedIndex: index) as! T? + return try type.fastDecodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T? } else if let type = T.self as? DatabaseValueConvertible.Type { - return try type.decodeIfPresent(from: row, atUncheckedIndex: index) as! T? + return try type.decodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T? } else if row.impl.hasNull(atUncheckedIndex: index) { return nil } else { @@ -153,11 +155,11 @@ private struct _RowDecoder: Decoder { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { - return try R.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: index) as! T + return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { - return try type.fastDecode(from: row, atUncheckedIndex: index) as! T + return try type.fastDecode(fromRow: row, atUncheckedIndex: index) as! T } else if let type = T.self as? DatabaseValueConvertible.Type { - return try type.decode(from: row, atUncheckedIndex: index) as! T + return try type.decode(fromRow: row, atUncheckedIndex: index) as! T } else { return try decode(type, fromRow: row, columnAtIndex: index, key: key) } @@ -383,11 +385,11 @@ extension ColumnDecoder: SingleValueDecodingContainer { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Date.self { - return try R.databaseDateDecodingStrategy.decode(fromRow: row, columnAtIndex: columnIndex) as! T + return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T } else if let type = T.self as? (DatabaseValueConvertible & StatementColumnConvertible).Type { - return try type.fastDecode(from: row, atUncheckedIndex: columnIndex) as! T + return try type.fastDecode(fromRow: row, atUncheckedIndex: columnIndex) as! T } else if let type = T.self as? DatabaseValueConvertible.Type { - return try type.decode(from: row, atUncheckedIndex: columnIndex) as! T + return try type.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T } else { return try T(from: self) } @@ -406,37 +408,37 @@ private var iso8601Formatter: ISO8601DateFormatter = { extension DatabaseDateDecodingStrategy { @inline(__always) - fileprivate func decodeIfPresent(fromRow row: Row, columnAtIndex index: Int) throws -> Date? { + fileprivate func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date? { if let sqliteStatement = row.sqliteStatement { return try decodeIfPresent( - sqliteStatement: sqliteStatement, - index: Int32(index), + fromStatement: sqliteStatement, + atUncheckedIndex: Int32(index), context: RowDecodingContext(row: row, key: .columnIndex(index))) } else { return try decodeIfPresent( - from: row[index], + fromDatabaseValue: row[index], context: RowDecodingContext(row: row, key: .columnIndex(index))) } } @inline(__always) - fileprivate func decode(fromRow row: Row, columnAtIndex index: Int) throws -> Date { + fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date { if let sqliteStatement = row.sqliteStatement { return try decode( - sqliteStatement: sqliteStatement, - index: Int32(index), + fromStatement: sqliteStatement, + atUncheckedIndex: Int32(index), context: RowDecodingContext(row: row, key: .columnIndex(index))) } else { return try decode( - from: row[index], + fromDatabaseValue: row[index], context: RowDecodingContext(row: row, key: .columnIndex(index))) } } @inline(__always) fileprivate func decode( - sqliteStatement: SQLiteStatement, - index: Int32, + fromStatement sqliteStatement: SQLiteStatement, + atUncheckedIndex index: Int32, context: @autoclosure () -> RowDecodingContext) throws -> Date { @@ -494,20 +496,20 @@ extension DatabaseDateDecodingStrategy { @inline(__always) fileprivate func decodeIfPresent( - sqliteStatement: SQLiteStatement, - index: Int32, + fromStatement sqliteStatement: SQLiteStatement, + atUncheckedIndex index: Int32, context: @autoclosure () -> RowDecodingContext) throws -> Date? { if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL { return nil } - return try decode(sqliteStatement: sqliteStatement, index: index, context: context()) + return try decode(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context()) } @inline(__always) fileprivate func decode( - from dbValue: DatabaseValue, + fromDatabaseValue dbValue: DatabaseValue, context: @autoclosure () -> RowDecodingContext) throws -> Date { @@ -520,7 +522,7 @@ extension DatabaseDateDecodingStrategy { @inline(__always) fileprivate func decodeIfPresent( - from dbValue: DatabaseValue, + fromDatabaseValue dbValue: DatabaseValue, context: @autoclosure () -> RowDecodingContext) throws -> Date? { diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 6ef912b0c..fe3bea6c9 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -154,8 +154,6 @@ 56419C9B24A51D7F004967E1 /* PublisherExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A8124A51614004967E1 /* PublisherExpectation.swift */; }; 564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; - 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */; }; - 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */; }; 5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; 5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; }; 564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; }; @@ -857,7 +855,6 @@ 56419A8024A51614004967E1 /* Inverted.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inverted.swift; sourceTree = ""; }; 56419A8124A51614004967E1 /* PublisherExpectation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PublisherExpectation.swift; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; - 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = ""; }; 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = ""; }; @@ -1765,7 +1762,6 @@ 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */, 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */, 56A238751B9C75030082EB20 /* DatabaseValue.swift */, - 5644DE7620F8C8E9001FFDDE /* DatabaseValueConversion.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, @@ -2329,7 +2325,6 @@ 568ECB0E25D904CA00B71526 /* SQLSelection.swift in Sources */, 5657AB141D10899D006283EF /* URL.swift in Sources */, 56F34FF224B0F0D8007513FC /* SQLCollatedExpression.swift in Sources */, - 5644DE7920F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */, F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, 5656A8782295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */, @@ -2688,7 +2683,6 @@ 568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */, 5657AB111D10899D006283EF /* URL.swift in Sources */, 56F34FF124B0F0D8007513FC /* SQLCollatedExpression.swift in Sources */, - 5644DE7820F8C8EA001FFDDE /* DatabaseValueConversion.swift in Sources */, 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */, F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, 5656A8772295BD56001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */, diff --git a/Tests/GRDBTests/DataMemoryTests.swift b/Tests/GRDBTests/DataMemoryTests.swift index 3e98ce2e6..159a48a36 100644 --- a/Tests/GRDBTests/DataMemoryTests.swift +++ b/Tests/GRDBTests/DataMemoryTests.swift @@ -11,55 +11,85 @@ class DataMemoryTests: GRDBTestCase { // https://forums.swift.org/t/swift-5-how-to-test-data-bytesnocopydeallocator/20299/2?u=gwendal.roue let data = Data(repeating: 0xaa, count: 15) - let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data]) - while let row = try rows.next() { - let blobPointer = sqlite3_column_blob(row.sqliteStatement, 0) - - do { - // This data should be copied: - let copiedData: Data = row[0] - XCTAssertEqual(copiedData, data) - copiedData.withUnsafeBytes { - XCTAssertNotEqual($0.baseAddress, blobPointer) - } - } - - do { - // This data should not be copied - let nonCopiedData = row.dataNoCopy(atIndex: 0)! - XCTAssertEqual(nonCopiedData, data) - nonCopiedData.withUnsafeBytes { - XCTAssertEqual($0.baseAddress, blobPointer) - } - } - } - - let row = try Row.fetchOne(db, sql: "SELECT ?", arguments: [data])! - let dbValue = row.first!.1 // TODO: think about exposing a (column:,databaseValue:) tuple - switch dbValue.storage { - case .blob(let data): - data.withUnsafeBytes { buffer in + do { + let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data]) + while let row = try rows.next() { + let blobPointer = sqlite3_column_blob(row.sqliteStatement, 0) + do { - // This data should not be copied: - let nonCopiedData: Data = row[0] - XCTAssertEqual(nonCopiedData, data) - nonCopiedData.withUnsafeBytes { nonCopiedBuffer in - XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress - ) + // This data should be copied: + let copiedData: Data = row[0] + XCTAssertEqual(copiedData, data) + copiedData.withUnsafeBytes { + XCTAssertNotEqual($0.baseAddress, blobPointer) } } do { - // This data should not be copied: + // This data should not be copied let nonCopiedData = row.dataNoCopy(atIndex: 0)! XCTAssertEqual(nonCopiedData, data) - nonCopiedData.withUnsafeBytes { nonCopiedBuffer in - XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress) + nonCopiedData.withUnsafeBytes { + XCTAssertEqual($0.baseAddress, blobPointer) } } } - default: - XCTFail("Not a blob") + } + + do { + let adapter = ScopeAdapter(["nested": SuffixRowAdapter(fromIndex: 0)]) + let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data], adapter: adapter) + while let row = try rows.next() { + let blobPointer = sqlite3_column_blob(row.unadapted.sqliteStatement, 0) + let nestedRow = row.scopes["nested"]! + + do { + // This data should be copied: + let copiedData: Data = nestedRow[0] + XCTAssertEqual(copiedData, data) + copiedData.withUnsafeBytes { + XCTAssertNotEqual($0.baseAddress, blobPointer) + } + } + + do { + // This data should not be copied + let nonCopiedData = nestedRow.dataNoCopy(atIndex: 0)! + XCTAssertEqual(nonCopiedData, data) + nonCopiedData.withUnsafeBytes { + XCTAssertEqual($0.baseAddress, blobPointer) + } + } + } + } + + do { + let row = try Row.fetchOne(db, sql: "SELECT ?", arguments: [data])! + let dbValue = row.first!.1 // TODO: think about exposing a (column:,databaseValue:) tuple + switch dbValue.storage { + case .blob(let data): + data.withUnsafeBytes { buffer in + do { + // This data should not be copied: + let nonCopiedData: Data = row[0] + XCTAssertEqual(nonCopiedData, data) + nonCopiedData.withUnsafeBytes { nonCopiedBuffer in + XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress) + } + } + + do { + // This data should not be copied: + let nonCopiedData = row.dataNoCopy(atIndex: 0)! + XCTAssertEqual(nonCopiedData, data) + nonCopiedData.withUnsafeBytes { nonCopiedBuffer in + XCTAssertEqual(nonCopiedBuffer.baseAddress, buffer.baseAddress) + } + } + } + default: + XCTFail("Not a blob") + } } } } diff --git a/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift b/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift index 3300ed5e6..aede3116f 100644 --- a/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift +++ b/Tests/GRDBTests/DatabaseValueConversionErrorTests.swift @@ -612,7 +612,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { do { // TODO GRDB6: _ = try String.fetchAll(statement) _ = try Row.fetchCursor(statement) - .map { try $0.fastDecode(String.self, atUncheckedIndex: 0) } + .map { try String.fastDecode(fromRow: $0, atUncheckedIndex: 0) } .next() XCTFail("Expected error") } catch let error as RowDecodingError { @@ -714,7 +714,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { do { // TODO GRDB6: _ = try Int8.fetchAll(statement) _ = try Row.fetchCursor(statement) - .map { try $0.fastDecode(Int8.self, atUncheckedIndex: 0) } + .map { try Int8.fastDecode(fromRow: $0, atUncheckedIndex: 0) } .next() XCTFail("Expected error") } catch let error as RowDecodingError { @@ -796,7 +796,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { do { // TODO GRDB6: _ = try Value.fetchAll(statement) _ = try Row.fetchCursor(statement) - .map { try $0.decode(Value.self, atIndex: 0) } + .map { try Value.decode(fromRow: $0, atUncheckedIndex: 0) } .next() XCTFail("Expected error") } catch let error as RowDecodingError { @@ -822,7 +822,7 @@ class DatabaseValueConversionErrorTests: GRDBTestCase { do { // TODO GRDB6: _ = try Value.fetchOne(statement, adapter: SuffixRowAdapter(fromIndex: 1)) _ = try Row.fetchCursor(statement) - .map { try $0.decode(Value.self, atIndex: 1) } + .map { try Value.decode(fromRow: $0, atUncheckedIndex: 1) } .next() XCTFail("Expected error") } catch let error as RowDecodingError { diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index b3ec3726e..2555a1c44 100644 --- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift +++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift @@ -68,6 +68,42 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { } } } + + func testScopedRowExtraction() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let adapter = ScopeAdapter(["nested": SuffixRowAdapter(fromIndex: 0)]) + var rows = try Row.fetchCursor(db, sql: "SELECT NULL", adapter: adapter) + while let row = try rows.next() { + let one: Fetched? = row.scopes["nested"]![0] + XCTAssertTrue(one == nil) + } + rows = try Row.fetchCursor(db, sql: "SELECT 1", adapter: adapter) + while let row = try rows.next() { + let one: Fetched? = row.scopes["nested"]![0] + XCTAssertEqual(one!.int, 1) + XCTAssertEqual(one!.fast, true) + } + rows = try Row.fetchCursor(db, sql: "SELECT 1 AS int", adapter: adapter) + while let row = try rows.next() { + let one: Fetched? = row.scopes["nested"]!["int"] + XCTAssertEqual(one!.int, 1) + XCTAssertEqual(one!.fast, true) + } + rows = try Row.fetchCursor(db, sql: "SELECT 1", adapter: adapter) + while let row = try rows.next() { + let one: Fetched = row.scopes["nested"]![0] + XCTAssertEqual(one.int, 1) + XCTAssertEqual(one.fast, true) + } + rows = try Row.fetchCursor(db, sql: "SELECT 1 AS int", adapter: adapter) + while let row = try rows.next() { + let one: Fetched = row.scopes["nested"]!["int"] + XCTAssertEqual(one.int, 1) + XCTAssertEqual(one.fast, true) + } + } + } // MARK: - StatementColumnConvertible.fetch From 7f48e66fdc2e7e5afbb3c8be0f23890d250eba95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 26 Feb 2021 18:50:47 +0100 Subject: [PATCH 25/35] Reduce inlined code --- GRDB/Core/RowDecodingError.swift | 17 ++++++++++++++++- GRDB/Core/StatementColumnConvertible.swift | 11 ++++++----- GRDB/Core/Support/Foundation/Data.swift | 5 +++-- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/GRDB/Core/RowDecodingError.swift b/GRDB/Core/RowDecodingError.swift index ded2d9427..6392886ec 100644 --- a/GRDB/Core/RowDecodingError.swift +++ b/GRDB/Core/RowDecodingError.swift @@ -58,7 +58,6 @@ enum RowDecodingError: Error { /// Convenience method that builds the /// `could not decode from database value ` error message. - @usableFromInline static func valueMismatch( _ type: Any.Type, context: RowDecodingContext, @@ -72,6 +71,22 @@ enum RowDecodingError: Error { """)) } + /// Convenience method that builds the + /// `could not decode from database value ` error message. + @usableFromInline + static func valueMismatch( + _ type: Any.Type, + sqliteStatement: SQLiteStatement, + index: Int32, + context: RowDecodingContext) + -> Self + { + valueMismatch( + type, + context: context, + databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) + } + /// Convenience method that builds the /// `could not decode from database value ` error message. @usableFromInline diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index e5a75f490..50a2d6835 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -57,8 +57,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { else { throw RowDecodingError.valueMismatch( Self.self, - context: context(), - databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) + sqliteStatement: sqliteStatement, + index: index, + context: context()) } return value } @@ -90,11 +91,11 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { return nil } guard let value = self.init(sqliteStatement: sqliteStatement, index: index) else { - #warning("TODO: don't put the DatabaseValue in the inlined code") throw RowDecodingError.valueMismatch( Self.self, - context: context(), - databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) + sqliteStatement: sqliteStatement, + index: index, + context: context()) } return value } diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index 4be05988c..42a853466 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -46,8 +46,9 @@ extension Data { guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { throw RowDecodingError.valueMismatch( Data.self, - context: context(), - databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index)) + sqliteStatement: sqliteStatement, + index: index, + context: context()) } guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else { return Data() From b834b9876d1f5d88eca792d638ead0a93e50663d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 26 Feb 2021 18:51:14 +0100 Subject: [PATCH 26/35] Data.fastDecodeNoCopyIfPresent can not fail --- GRDB/Core/Support/Foundation/Data.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index 42a853466..7e50947b3 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -78,7 +78,7 @@ extension Data { fromStatement sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32, context: @autoclosure () -> RowDecodingContext) - throws -> Data? + -> Data? { guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else { return nil @@ -97,7 +97,7 @@ extension Data { throws -> Data? { if let sqliteStatement = row.sqliteStatement { - return try fastDecodeNoCopyIfPresent( + return fastDecodeNoCopyIfPresent( fromStatement: sqliteStatement, atUncheckedIndex: Int32(index), context: RowDecodingContext(row: row, key: .columnIndex(index))) From 37dfd95ae1158c1f98a65a0eb09e79794ff9d908 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 26 Feb 2021 19:31:41 +0100 Subject: [PATCH 27/35] Symmetry with StatementColumnConvertible --- GRDB/Core/DatabaseValueConvertible.swift | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index ae0ad6445..5183169ee 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -56,7 +56,13 @@ extension DatabaseValueConvertible { @usableFromInline static func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self { - try decode( + if let sqliteStatement = row.sqliteStatement { + return try decode( + fromStatement: sqliteStatement, + atUncheckedIndex: Int32(index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } + return try decode( fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index), context: RowDecodingContext(row: row, key: .columnIndex(index))) } @@ -95,7 +101,13 @@ extension DatabaseValueConvertible { @usableFromInline static func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self? { - try decodeIfPresent( + if let sqliteStatement = row.sqliteStatement { + return try decodeIfPresent( + fromStatement: sqliteStatement, + atUncheckedIndex: Int32(index), + context: RowDecodingContext(row: row, key: .columnIndex(index))) + } + return try decodeIfPresent( fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index), context: RowDecodingContext(row: row, key: .columnIndex(index))) } From 96df69b3fb2ed37058282d4588cf381663a286a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 2 Mar 2021 19:06:18 +0100 Subject: [PATCH 28/35] Add fundamental test for #929 --- Tests/GRDBTests/QueryInterfaceExpressionsTests.swift | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 0a5ffe28c..62cfc8631 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -165,6 +165,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { func testContainsWithCollation() throws { let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + // Reminder of the SQLite behavior + // https://sqlite.org/datatype3.html#assigning_collating_sequences_from_sql + // > If an explicit collating sequence is required on an IN operator + // > it should be applied to the left operand, like this: + // > "x COLLATE nocase IN (y,z, ...)". + try XCTAssertFalse(Bool.fetchOne(db, sql: "SELECT 'arthur' IN ('ARTHUR') COLLATE NOCASE")!) + try XCTAssertTrue(Bool.fetchOne(db, sql: "SELECT 'arthur' COLLATE NOCASE IN ('ARTHUR')")!) + } + // Array.contains(): IN operator XCTAssertEqual( sql(dbQueue, tableRequest.filter(["arthur", "barbara"].contains(Col.name.collating(.nocase)))), From 01d71d6f3557c3b7b5761b7330bbb56649e44800 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 2 Mar 2021 20:02:46 +0100 Subject: [PATCH 29/35] Failing tests for #929 --- Tests/GRDBTests/QueryInterfaceExpressionsTests.swift | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 62cfc8631..bb02b37f3 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -178,22 +178,26 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { // Array.contains(): IN operator XCTAssertEqual( sql(dbQueue, tableRequest.filter(["arthur", "barbara"].contains(Col.name.collating(.nocase)))), - "SELECT * FROM \"readers\" WHERE \"name\" IN ('arthur', 'barbara') COLLATE NOCASE") + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [SQLExpressible]).contains(Col.name.collating(.nocase)))), + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") // Sequence.contains(): IN operator XCTAssertEqual( sql(dbQueue, tableRequest.filter(AnySequence(["arthur", "barbara"]).contains(Col.name.collating(.nocase)))), - "SELECT * FROM \"readers\" WHERE \"name\" IN ('arthur', 'barbara') COLLATE NOCASE") + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") // Sequence.contains(): = operator XCTAssertEqual( sql(dbQueue, tableRequest.filter(AnySequence([Col.name]).contains(Col.name.collating(.nocase)))), - "SELECT * FROM \"readers\" WHERE \"name\" = \"name\" COLLATE NOCASE") + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) = \"name\"") // Sequence.contains(): false XCTAssertEqual( sql(dbQueue, tableRequest.filter(EmptyCollection().contains(Col.name.collating(.nocase)))), - "SELECT * FROM \"readers\" WHERE 0 COLLATE NOCASE") + "SELECT * FROM \"readers\" WHERE 0") // ClosedInterval: BETWEEN operator let closedInterval = "A"..."z" From 279b00f890f5d075c2ffb271fc1af3281215ad56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 2 Mar 2021 20:03:19 +0100 Subject: [PATCH 30/35] Fix failing tests for #929 --- GRDB/QueryInterface/SQL/SQLOperators.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index 25f088f79..204716c44 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -506,7 +506,7 @@ extension Sequence where Self.Iterator.Element: SQLExpressible { /// // name IN ('A', 'B') COLLATE NOCASE /// ["A", "B"].contains(Column("name").collating(.nocase)) public func contains(_ element: SQLCollatedExpression) -> SQLExpression { - .collated(contains(element.expression), element.collationName) + SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) } } @@ -526,7 +526,7 @@ extension Sequence where Self.Iterator.Element == SQLExpressible { /// // name IN ('A', 'B') COLLATE NOCASE /// ["A", "B"].contains(Column("name").collating(.nocase)) public func contains(_ element: SQLCollatedExpression) -> SQLExpression { - .collated(contains(element.expression), element.collationName) + SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) } } From 5ea7296e7ab31c9af1f408e6efa2300916f7a4d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 2 Mar 2021 20:09:24 +0100 Subject: [PATCH 31/35] Add support for subquery.contains(collated expression) --- GRDB/QueryInterface/SQL/SQLSubquery.swift | 14 ++++++++++++-- Tests/GRDBTests/FetchRequestTests.swift | 17 +++++++++++++---- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift index 0cc66a2ae..c0d474158 100644 --- a/GRDB/QueryInterface/SQL/SQLSubquery.swift +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -110,7 +110,17 @@ extension SQLSubqueryable { /// // 1000 IN (SELECT score FROM player) /// let request = Player.select(Column("score"), as: Int.self) /// let condition = request.contains(1000) - public func contains(_ value: SQLExpressible) -> SQLExpression { - SQLCollection.subquery(sqlSubquery).contains(value.sqlExpression) + public func contains(_ element: SQLExpressible) -> SQLExpression { + SQLCollection.subquery(sqlSubquery).contains(element.sqlExpression) + } + + /// Returns an expression that checks the inclusion of the expression in + /// the subquery. + /// + /// // name COLLATE NOCASE IN (SELECT name FROM player) + /// let request = Player.select(Column("name"), as: String.self) + /// let condition = request.contains(Column("name").collating(.nocase)) + public func contains(_ element: SQLCollatedExpression) -> SQLExpression { + SQLCollection.subquery(sqlSubquery).contains(element.sqlExpression) } } diff --git a/Tests/GRDBTests/FetchRequestTests.swift b/Tests/GRDBTests/FetchRequestTests.swift index f1aa6c987..4c36f1872 100644 --- a/Tests/GRDBTests/FetchRequestTests.swift +++ b/Tests/GRDBTests/FetchRequestTests.swift @@ -44,10 +44,19 @@ class FetchRequestTests: GRDBTestCase { t.column("id", .integer).primaryKey() } - let derivedExpression = request.contains(0) - let sqlRequest: SQLRequest = "SELECT \(derivedExpression)" - let statement = try sqlRequest.makePreparedRequest(db, forSingleResult: false).statement - XCTAssertEqual(statement.sql, "SELECT ? IN (SELECT id FROM table1)") + do { + let derivedExpression = request.contains(0) + let sqlRequest: SQLRequest = "SELECT \(derivedExpression)" + let statement = try sqlRequest.makePreparedRequest(db, forSingleResult: false).statement + XCTAssertEqual(statement.sql, "SELECT ? IN (SELECT id FROM table1)") + } + + do { + let derivedExpression = request.contains("arthur".databaseValue.collating(.nocase)) + let sqlRequest: SQLRequest = "SELECT \(derivedExpression)" + let statement = try sqlRequest.makePreparedRequest(db, forSingleResult: false).statement + XCTAssertEqual(statement.sql, "SELECT (? COLLATE NOCASE) IN (SELECT id FROM table1)") + } } } From 7b81fd1bffd30ec070115f66197146178dd8ff2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 2 Mar 2021 20:12:38 +0100 Subject: [PATCH 32/35] Fix documentation for #929 --- GRDB/QueryInterface/SQL/SQLOperators.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLOperators.swift b/GRDB/QueryInterface/SQL/SQLOperators.swift index 204716c44..3411aa0e2 100644 --- a/GRDB/QueryInterface/SQL/SQLOperators.swift +++ b/GRDB/QueryInterface/SQL/SQLOperators.swift @@ -503,7 +503,7 @@ extension Sequence where Self.Iterator.Element: SQLExpressible { /// An SQL expression that checks the inclusion of an expression in /// a sequence. /// - /// // name IN ('A', 'B') COLLATE NOCASE + /// // (name COLLATE NOCASE) IN ('A', 'B') /// ["A", "B"].contains(Column("name").collating(.nocase)) public func contains(_ element: SQLCollatedExpression) -> SQLExpression { SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) @@ -523,7 +523,7 @@ extension Sequence where Self.Iterator.Element == SQLExpressible { /// An SQL expression that checks the inclusion of an expression in /// a sequence. /// - /// // name IN ('A', 'B') COLLATE NOCASE + /// // (name COLLATE NOCASE) IN ('A', 'B') /// ["A", "B"].contains(Column("name").collating(.nocase)) public func contains(_ element: SQLCollatedExpression) -> SQLExpression { SQLCollection.array(map(\.sqlExpression)).contains(element.sqlExpression) From 72123494caf67f4e79f90c130611f5d666ec93a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 2 Mar 2021 20:16:15 +0100 Subject: [PATCH 33/35] Add test for NOT IN and collated expressions --- Tests/GRDBTests/QueryInterfaceExpressionsTests.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index bb02b37f3..0643c9f81 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -180,6 +180,10 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { sql(dbQueue, tableRequest.filter(["arthur", "barbara"].contains(Col.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!["arthur", "barbara"].contains(Col.name.collating(.nocase)))), + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) NOT IN ('arthur', 'barbara')") + XCTAssertEqual( sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [SQLExpressible]).contains(Col.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") From d2d515658e705675799d0803fcee0b1ccb39e9b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 2 Mar 2021 20:21:51 +0100 Subject: [PATCH 34/35] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02097a1aa..fea085d8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -85,6 +85,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **Fixed**: `DatabaseQueue.read` is now declared `throws` instead of `rethrows`. +- **Fixed**: [#930](https://github.com/groue/GRDB.swift/pull/930): Fix SQL generation for `COLLATE`, `IN`, `NOT IN` + ## 5.4.0 Released February 15, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.3.0...v5.4.0) From 2329a5c7b4ddc37cb1627a55b17c487989999704 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 3 Mar 2021 13:00:21 +0100 Subject: [PATCH 35/35] v5.5.0 --- CHANGELOG.md | 6 +++-- Documentation/FullTextSearch.md | 4 ++-- Documentation/Migrations.md | 2 +- GRDB.swift.podspec | 2 +- Makefile | 6 ++--- README.md | 40 ++++++++++++++++----------------- Support/Info.plist | 2 +- 7 files changed, 32 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fea085d8b..4e17f9527 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases -- [Development Branch](#development-branch) +- `5.5.x` Releases - [5.5.0](#550) - `5.4.x` Releases - [5.4.0](#540) - `5.3.x` Releases - [5.3.0](#530) - `5.2.x` Releases - [5.2.0](#520) @@ -71,7 +71,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [0.110.0](#01100), ... -## Development Branch +## 5.5.0 + +Released March 3, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.4.0...v5.5.0) - **New**: You can now define common table expressions without any generic qualifier (which defaults to `Row`): diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index c41178de5..641a637ba 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.4/Structs/StatementArguments.html): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.4/Structs/StatementArguments.html): +FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index f29cf656f..532631aaf 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -68,7 +68,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.4/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.5/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 823a9449b..319b5ad68 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '5.4.0' + s.version = '5.5.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/Makefile b/Makefile index adfeb5f6b..4275bd3ff 100644 --- a/Makefile +++ b/Makefile @@ -431,10 +431,10 @@ ifdef JAZZY --author 'Gwendal Roué' \ --author_url https://github.com/groue \ --github_url https://github.com/groue/GRDB.swift \ - --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.4.0 \ - --module-version 5.4.0 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.5.0 \ + --module-version 5.5.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.4/ \ + --root-url http://groue.github.io/GRDB.swift/docs/5.5/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index ce60e884b..f3080e9fa 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: February 15, 2021 • version 5.4.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: March 3, 2021 • version 5.5.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) **Requirements**: iOS 10.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.2+ / Xcode 11.4+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.2+** | **v5.4.0** | +| **Swift 5.2+** | **v5.5.0** | | Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | | Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) | @@ -278,7 +278,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.4/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.5/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -472,7 +472,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.4/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html) for more details. ## Database Pools @@ -552,7 +552,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.4/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -612,7 +612,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.4/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details. @@ -815,7 +815,7 @@ try dbQueue.read { db in - **Cursors are granted with direct access to SQLite,** unlike arrays and sets that have to take the time to copy database values. If you look after extra performance, you may prefer cursors. -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.4/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.5/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // Prints all Github links @@ -898,7 +898,7 @@ let rows = try Row.fetchAll(db, arguments: ["name": "Arthur"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.4/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care: @@ -1183,7 +1183,7 @@ GRDB ships with built-in support for the following value types: - Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. -Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.4/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1592,7 +1592,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } ``` -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.4/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1706,7 +1706,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.4/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). +The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift updateStatement.arguments = ["name": "Arthur", "score": 1000] @@ -2483,7 +2483,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.4/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html) for more information about the query arguments. > :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`. @@ -2864,7 +2864,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.4/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.4/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.4/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.5/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.5/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.5/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. > :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings). @@ -4329,7 +4329,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.4/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -5016,7 +5016,7 @@ try Player.customRequest().fetchAll(db) // [Player] - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.4/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.5/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -6190,7 +6190,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan ### DatabaseRegion -**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.4/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. +**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.5/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**. A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion. @@ -6200,7 +6200,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table. -For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.4/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). +For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.5/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF). #### The DatabaseRegionConvertible Protocol @@ -7320,7 +7320,7 @@ try snapshot2.read { db in ### DatabaseWriter and DatabaseReader Protocols -Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.4/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.4/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.5/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.5/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example: @@ -7995,7 +7995,7 @@ When this is the case, there are two possible explanations: try db.execute(sql: "UPDATE player SET name = ?", arguments: [name]) ``` -For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.4/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). +For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). @@ -8157,4 +8157,4 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq [Database Observation]: #database-changes-observation -[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.4/Structs/SQLRequest.html +[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.5/Structs/SQLRequest.html diff --git a/Support/Info.plist b/Support/Info.plist index c7ec34e3a..dfcf4dcd8 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.4.0 + 5.5.0 CFBundleSignature ???? CFBundleVersion