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.
This commit is contained in:
Gwendal Roué authored and Gwendal Roué committed 2025-09-23 17:12:27 +02:00
1 parent eb2378a741
commit 1095d21abd
1 file changed
+34
+34
View File
@@ -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<Source1, Source2>: 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
}
}