From 4e8d129162d72ebbacec2848b84bee2f4e9dc94f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 8 Dec 2020 20:47:21 +0100 Subject: [PATCH] Only use the CTE technique if foreign key columns are not null --- GRDB/Core/Database+Schema.swift | 10 +++++ .../SQLPreparedRequestGenerator.swift | 41 +++++++++++++++---- 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 3cd5fc7c9..05641e969 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -245,6 +245,16 @@ extension Database { try columnsForUniqueKey(Array(columns), in: tableName) != nil } + // Internal onvenience. Not robust enough for public use. + func table(_ tableName: String, hasNotNullConstraintOnColumns columnNames: [String]) throws -> Bool { + let columnNames = columnNames.map { $0.lowercased() } + let columns = try self + .columns(in: tableName) + .filter { columnNames.contains($0.name.lowercased()) } + assert(columns.count == columnNames.count, "columns not found") + return columns.allSatisfy(\.isNotNull) + } + /// The foreign keys defined on table named `tableName`. public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] { if let foreignKeys = schemaCache.foreignKeys(on: tableName) { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift index 4431c6ba0..bec6a9036 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift @@ -167,17 +167,42 @@ private func prefetch( let leftColumns = pivotMapping.map(\.left) // We want to avoid the "Expression tree is too large" SQLite error - // when there are many base rows: + // when the foreign key contains several columns, and there are many + // base rows that overflow SQLITE_LIMIT_EXPR_DEPTH: // https://github.com/groue/GRDB.swift/issues/871 // - // To this end, we do not inject any value from the base rows in - // the prefetch request. Instead, we directly inject the base - // request as a common table expression (CTE). + // -- May be too complex for the SQLite engine + // SELECT * FROM child + // WHERE (a = ? AND b = ?) + // OR (a = ? AND b = ?) + // OR ... // - // This is only useful for compound foreign keys. And we need - // row values (https://www.sqlite.org/rowvalue.html). So we have - // a backup plan which does not use any CTE. - let usesCommonTableExpression = pivotMapping.count > 1 && _SQLRowValue.isAvailable + // Instead, we do not inject any value from the base rows in + // the prefetch request. Instead, we directly inject the base + // request as a common table expression (CTE): + // + // WITH grdb_base AS (SELECT a, b FROM parent) + // SELECT * FROM child + // WHERE (a, b) IN grdb_base + // + // This technique works well, but there are two preconditions: + // + // 1. Row values must be available (https://www.sqlite.org/rowvalue.html) + // This is the case of almost all our target platforms. + // + // 2. There must be no null values in the foreign key. That is + // because the `WHERE (a, b) IN grdb_base` snippet does not find + // foreign keys that contain a null value, when we do want to + // find them. We thus look for NOT NULL constraints, and reward + // database schemas that define "proper" foreign keys. + // + // If any of those precondition is not met, we fallback to the + // `(a = ? AND b = ?) OR ...` condition (the one that may fail if + // there are too many base rows). + let usesCommonTableExpression = try pivotMapping.count > 1 + && _SQLRowValue.isAvailable + && (db.table(baseRequest.query.relation.source.tableName, hasNotNullConstraintOnColumns: leftColumns) + || db.table(association.pivot.relation.source.tableName, hasNotNullConstraintOnColumns: pivotColumns)) let prefetchRequest: QueryInterfaceRequest if usesCommonTableExpression {