From dcc2d211b281137f5159ec3393bce959d1200bb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 12 Dec 2021 16:14:25 +0100 Subject: [PATCH] Database.primaryKey() fails for views --- GRDB/Core/Database+Schema.swift | 6 +++++ Tests/GRDBTests/PrimaryKeyInfoTests.swift | 29 +++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 2cc3513de..96a8b0b91 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -199,6 +199,12 @@ extension Database { return primaryKey.value } + if try !tableExists(table) { + // Views, CTEs, etc. + schemaCache[table.schemaID].set(primaryKey: .missing, forTable: table.name) + return nil + } + // https://www.sqlite.org/pragma.html // // > PRAGMA database.table_info(table-name); diff --git a/Tests/GRDBTests/PrimaryKeyInfoTests.swift b/Tests/GRDBTests/PrimaryKeyInfoTests.swift index 7ea6f075a..e6e8fd271 100644 --- a/Tests/GRDBTests/PrimaryKeyInfoTests.swift +++ b/Tests/GRDBTests/PrimaryKeyInfoTests.swift @@ -3,6 +3,35 @@ import XCTest class PrimaryKeyInfoTests: GRDBTestCase { + func testMissingTable() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + _ = try db.primaryKey("items") + XCTFail("Expected Error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "no such table: items") + XCTAssertEqual(error.description, "SQLite error 1: no such table: items") + } + } + } + + func testView() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE VIEW items AS SELECT 1") + do { + _ = try db.primaryKey("items") + XCTFail("Expected Error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "no such table: items") + XCTAssertEqual(error.description, "SQLite error 1: no such table: items") + } + } + } + func testHiddenRowID() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in