From 1095d21abde154ea6793a148cec19b78854f018d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 5 Sep 2025 07:58:27 +0200 Subject: [PATCH] Default implementation for schema source chaining. When GRDB eventually adds methods to the DatabaseSchemaSource protocol, our chained schema source will implement chaining on those new methods. When users write their own custom chaining schema source, the compiler will not tell them that they have to chain the new methods when they upgrade GRDB. The built-in (and correct) implementation of chaining helps avoiding this scenario. --- GRDB/Core/DatabaseSchemaSource.swift | 34 ++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/GRDB/Core/DatabaseSchemaSource.swift b/GRDB/Core/DatabaseSchemaSource.swift index 163e83f4f..828de1b05 100644 --- a/GRDB/Core/DatabaseSchemaSource.swift +++ b/GRDB/Core/DatabaseSchemaSource.swift @@ -42,6 +42,10 @@ /// ### Customizing the Database Schema /// /// - ``columnsForPrimaryKey(_:inView:)`` +/// +/// ### Chaining Schema Sources +/// +/// - ``then(_:)`` public protocol DatabaseSchemaSource: Sendable { /// Returns the names of the columns for the primary key in the /// provided database view. @@ -118,3 +122,33 @@ extension DatabaseSchemaSource { nil } } + +// MARK: - Combined2SchemaSource + +extension DatabaseSchemaSource { + /// Returns a schema source that queries `other` when this source does + /// not perform customization. + public func then(_ other: some DatabaseSchemaSource) -> some DatabaseSchemaSource { + Chained2SchemaSource(first: self, second: other) + } +} + +// TODO: move to parameter packs eventually. Parameter packs in generic types +// are only available in macOS 14.0.0 or newer. +// This schema source is designed to tame bad citizens that customize tables +// and views they do not own (such as insufficienly robust schema sources +// exposed by external libraries). We should NEVER MERGE the results of the +// schema sources. +struct Chained2SchemaSource: DatabaseSchemaSource +where Source1: DatabaseSchemaSource, + Source2: DatabaseSchemaSource +{ + var first: Source1 + var second: Source2 + + func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? { + if let result = try first.columnsForPrimaryKey(db, inView: view) { return result } + if let result = try second.columnsForPrimaryKey(db, inView: view) { return result } + return nil + } +}