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 + } +}