From ac475cc158dc707d79f28022e4b0b011b6dbf4cc Mon Sep 17 00:00:00 2001 From: Ben Barnett Date: Wed, 6 Dec 2023 20:27:32 +0000 Subject: [PATCH] Add schemaName parameter to primaryKey(_:) --- GRDB/Core/Database+Schema.swift | 35 +++++++-- GRDB/Core/DatabaseError.swift | 4 + GRDB/Documentation.docc/DatabaseSchema.md | 2 +- Tests/GRDBTests/PrimaryKeyInfoTests.swift | 96 +++++++++++++++++++++++ 4 files changed, 131 insertions(+), 6 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index a8d92fae8..2e5311aed 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -154,6 +154,19 @@ extension Database { return schemaIdentifiers } + /// The `SchemaIdentifier` named `schemaName` if it exists. + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or + /// if no such schema exists. + private func schemaIdentifier(named schemaName: String) throws -> SchemaIdentifier { + let allIdentifiers = try schemaIdentifiers() + if let result = allIdentifiers.first(where: { $0.sql.lowercased() == schemaName.lowercased() }) { + return result + } else { + throw DatabaseError.noSuchSchema(schemaName) + } + } + #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Returns information about a table or a view func table(_ tableName: String) throws -> TableInfo? { @@ -272,10 +285,22 @@ extension Database { /// table has no explicit primary key, the result is the hidden /// "rowid" column. /// - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no - /// such table exists in the main or temp schema, or in an - /// attached database. - public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo { + /// When `schemaName` is not specified, known schemas are iterated in + /// SQLite resolution order and the first matching result is returned. + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if + /// the specified schema does not exist, or if no such table exists in + /// the main or temp schema, or in an attached database. + public func primaryKey(_ tableName: String, in schemaName: String? = nil) throws -> PrimaryKeyInfo { + if let schemaName { + let schemaIdentifier = try schemaIdentifier(named: schemaName) + if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { + return result + } else { + throw DatabaseError.noSuchTable(tableName) + } + } + for schemaIdentifier in try schemaIdentifiers() { if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) { return result @@ -1129,7 +1154,7 @@ extension ForeignKeyViolation: CustomStringConvertible { /// Information about a primary key. /// -/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:)`` +/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:in:)`` /// `Database` method. /// /// When the table's primary key is the rowid: diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 5695eb12b..53eb009b3 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -396,6 +396,10 @@ public struct DatabaseError: Error { static func noSuchTable(_ tableName: String) -> Self { DatabaseError(message: "no such table: \(tableName)") } + + static func noSuchSchema(_ schemaName: String) -> Self { + DatabaseError(message: "no such schema: \(schemaName)") + } } extension DatabaseError { diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index f45afc6bb..f3c19d1e3 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -396,7 +396,7 @@ extension Team: TableRecord { - ``Database/indexes(on:)`` - ``Database/isGRDBInternalTable(_:)`` - ``Database/isSQLiteInternalTable(_:)`` -- ``Database/primaryKey(_:)`` +- ``Database/primaryKey(_:in:)`` - ``Database/schemaVersion()`` - ``Database/table(_:hasUniqueKey:)`` - ``Database/tableExists(_:)`` diff --git a/Tests/GRDBTests/PrimaryKeyInfoTests.swift b/Tests/GRDBTests/PrimaryKeyInfoTests.swift index 5fb96d506..2a464a488 100644 --- a/Tests/GRDBTests/PrimaryKeyInfoTests.swift +++ b/Tests/GRDBTests/PrimaryKeyInfoTests.swift @@ -128,4 +128,100 @@ class PrimaryKeyInfoTests: GRDBTestCase { XCTAssertFalse(primaryKey.tableHasRowID) } } + + func testUnknownSchema() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE items (name TEXT)") + do { + _ = try db.primaryKey("items", in: "invalid") + XCTFail("Expected Error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "no such schema: invalid") + XCTAssertEqual(error.description, "SQLite error 1: no such schema: invalid") + } + } + } + + func testSpecifiedMainSchema() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE items (name TEXT)") + let primaryKey = try db.primaryKey("items", in: "main") + XCTAssertNil(primaryKey.columnInfos) + XCTAssertEqual(primaryKey.columns, [Column.rowID.name]) + XCTAssertNil(primaryKey.rowIDColumn) + XCTAssertTrue(primaryKey.isRowID) + XCTAssertTrue(primaryKey.tableHasRowID) + } + } + + func testSpecifiedSchemaWithTableNameCollisions() throws { + let attached = try makeDatabaseQueue(filename: "attached1") + try attached.inDatabase { db in + try db.execute(sql: "CREATE TABLE items (id2 INTEGER PRIMARY KEY)") + } + let main = try makeDatabaseQueue(filename: "main") + try main.inDatabase { db in + try db.execute(sql: "CREATE TABLE items (id1 INTEGER PRIMARY KEY)") + try db.execute(literal: "ATTACH DATABASE \(attached.path) AS attached") + + let primaryKeyMain = try db.primaryKey("items", in: "main") + XCTAssertEqual(primaryKeyMain.columnInfos?.map(\.name), ["id1"]) + XCTAssertEqual(primaryKeyMain.columnInfos?.map(\.type), ["INTEGER"]) + XCTAssertEqual(primaryKeyMain.columns, ["id1"]) + XCTAssertEqual(primaryKeyMain.rowIDColumn, "id1") + XCTAssertTrue(primaryKeyMain.isRowID) + XCTAssertTrue(primaryKeyMain.tableHasRowID) + + let primaryKeyAttached = try db.primaryKey("items", in: "attached") + XCTAssertEqual(primaryKeyAttached.columnInfos?.map(\.name), ["id2"]) + XCTAssertEqual(primaryKeyAttached.columnInfos?.map(\.type), ["INTEGER"]) + XCTAssertEqual(primaryKeyAttached.columns, ["id2"]) + XCTAssertEqual(primaryKeyAttached.rowIDColumn, "id2") + XCTAssertTrue(primaryKeyAttached.isRowID) + XCTAssertTrue(primaryKeyAttached.tableHasRowID) + } + } + + // The `items` table in the attached database should never + // be found unless explicitly specified as it is after + // `main.items` in resolution order. + func testUnspecifiedSchemaWithTableNameCollisions() throws { + let attached = try makeDatabaseQueue(filename: "attached1") + try attached.inDatabase { db in + try db.execute(sql: "CREATE TABLE items (id2 INTEGER PRIMARY KEY)") + } + let main = try makeDatabaseQueue(filename: "main") + try main.inDatabase { db in + try db.execute(sql: "CREATE TABLE items (id1 INTEGER PRIMARY KEY)") + try db.execute(literal: "ATTACH DATABASE \(attached.path) AS attached") + let primaryKey = try db.primaryKey("items") + XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["id1"]) + XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"]) + XCTAssertEqual(primaryKey.columns, ["id1"]) + XCTAssertEqual(primaryKey.rowIDColumn, "id1") + XCTAssertTrue(primaryKey.isRowID) + XCTAssertTrue(primaryKey.tableHasRowID) + } + } + + func testUnspecifiedSchemaFindsAttachedDatabase() throws { + let attached = try makeDatabaseQueue(filename: "attached1") + try attached.inDatabase { db in + try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") + } + let main = try makeDatabaseQueue(filename: "main") + try main.inDatabase { db in + try db.execute(literal: "ATTACH DATABASE \(attached.path) AS attached") + let primaryKey = try db.primaryKey("items") + XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["id"]) + XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"]) + XCTAssertEqual(primaryKey.columns, ["id"]) + XCTAssertEqual(primaryKey.rowIDColumn, "id") + XCTAssertTrue(primaryKey.isRowID) + XCTAssertTrue(primaryKey.tableHasRowID) + } + } }