mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-24 04:07:47 +00:00
DatabaseSchemaSource customizes the primary key of database views
This commit is contained in:
1 parent
d040588849
commit
d7d61add23
6 files changed
+188
-23
No files matched your search
@@ -81,6 +81,7 @@
|
||||
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */; };
|
||||
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; };
|
||||
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
|
||||
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
|
||||
@@ -503,6 +504,7 @@
|
||||
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
|
||||
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
|
||||
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
|
||||
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSource.swift; sourceTree = "<group>"; };
|
||||
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
|
||||
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
|
||||
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1592,6 +1594,7 @@
|
||||
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */,
|
||||
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
|
||||
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
@@ -2208,6 +2211,7 @@
|
||||
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */,
|
||||
56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
|
||||
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
|
||||
|
||||
@@ -421,6 +421,16 @@ public struct Configuration: Sendable {
|
||||
/// reveals that a lot of time is spent opening new SQLite connections.
|
||||
public var persistentReadOnlyConnections = false
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// A custom schema source.
|
||||
///
|
||||
/// The use case for a custom schema source is enabling GRDB features that
|
||||
/// would not work with the built-in schema introspection that is provided
|
||||
/// by SQLite. For example, a custom schema source can help record types
|
||||
/// that read or write in a database view.
|
||||
public var schemaSource: (any DatabaseSchemaSource)?
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration.
|
||||
|
||||
+102
-23
@@ -331,6 +331,9 @@ extension Database {
|
||||
/// SQLite resolution order, and the first matching result is returned.
|
||||
/// For more information, see <https://www.sqlite.org/lang_naming.html>.
|
||||
///
|
||||
/// Database views are supported, if the connection is configured with
|
||||
/// a schema source. See ``Configuration/schemaSource``.
|
||||
///
|
||||
/// - 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.
|
||||
@@ -385,7 +388,20 @@ extension Database {
|
||||
return primaryKey.value
|
||||
}
|
||||
|
||||
if let primaryKey = try fetchPrimitivePrimaryKey(forTable: table) {
|
||||
var primaryKey: PrimaryKeyInfo?
|
||||
|
||||
if let schemaSource = configuration.schemaSource,
|
||||
try viewExists(table.name, in: table.schemaID.name),
|
||||
let primaryKeyColumns = try schemaSource.columnsForPrimaryKey(self, inView: table)
|
||||
{
|
||||
primaryKey = try fetchPrimitivePrimaryKey(forView: table, columns: primaryKeyColumns)
|
||||
}
|
||||
|
||||
if primaryKey == nil {
|
||||
primaryKey = try fetchPrimitivePrimaryKey(forTable: table)
|
||||
}
|
||||
|
||||
if let primaryKey {
|
||||
schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name)
|
||||
return primaryKey
|
||||
} else {
|
||||
@@ -471,15 +487,55 @@ extension Database {
|
||||
if pkColumn.type.uppercased() == "INTEGER" {
|
||||
return .rowID(pkColumn)
|
||||
} else {
|
||||
return try .regular([pkColumn], tableHasRowID: tableHasRowID(table))
|
||||
return try .regular([pkColumn], tableHasRowID: fetchTableHasRowID(table))
|
||||
}
|
||||
|
||||
default:
|
||||
// Multi-columns primary key
|
||||
return try .regular(pkColumns, tableHasRowID: tableHasRowID(table))
|
||||
return try .regular(pkColumns, tableHasRowID: fetchTableHasRowID(table))
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches a customized primary key for the database view identified
|
||||
/// by `view`.
|
||||
///
|
||||
/// Nil is returned in the view does not exist, or if `columns` is empty.
|
||||
///
|
||||
/// - precondition: If the view exists, columns must exist, must
|
||||
/// identify a unique row, and must be not null.
|
||||
func fetchPrimitivePrimaryKey(
|
||||
forView view: DatabaseObjectID,
|
||||
columns: [String]
|
||||
) throws -> PrimaryKeyInfo? {
|
||||
if columns.isEmpty {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let infos = try fetchPrimitiveColumns(in: view) else {
|
||||
// View does not exist
|
||||
return nil
|
||||
}
|
||||
|
||||
let pkInfos = columns.enumerated().map { index, column in
|
||||
guard var info = infos.first(where: { $0.name.lowercased() == column.lowercased() }) else {
|
||||
// The requested column does not exist in the database schema.
|
||||
// Is it a programmer error, or a runtime error?
|
||||
// Let's make it a programmer error to start with.
|
||||
fatalError("""
|
||||
No such column in \(view.schemaID.viewNameInErrorMessages(view.name)): \(column)
|
||||
""")
|
||||
}
|
||||
|
||||
// Rewrite primaryKeyIndex, and use a 1-based index, as
|
||||
// documented in https://www.sqlite.org/pragma.html#pragma_table_info
|
||||
info.primaryKeyIndex = index + 1
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
return .regular(pkInfos, tableHasRowID: false /* views have no rowid */)
|
||||
}
|
||||
|
||||
/// Returns whether the column identifies the rowid column
|
||||
func columnIsRowID(_ column: String, of tableName: String) throws -> Bool {
|
||||
let pk = try primaryKey(tableName)
|
||||
@@ -489,19 +545,16 @@ extension Database {
|
||||
/// Returns whether the table has a rowid column.
|
||||
///
|
||||
/// - precondition: table exists.
|
||||
private func tableHasRowID(_ table: DatabaseObjectID) throws -> Bool {
|
||||
// No need to cache the result, because this information feeds
|
||||
// `PrimaryKeyInfo`, which is cached.
|
||||
|
||||
private func fetchTableHasRowID(_ table: DatabaseObjectID) throws -> Bool {
|
||||
// Prefer PRAGMA table_list if available
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Maybe SQLCipher is too old: check actual version
|
||||
if sqlite3_libversion_number() >= 3037000 {
|
||||
return try self.table(for: table)!.hasRowID
|
||||
return try self.table(for: table)!.isWithoutRowIDTable == false
|
||||
}
|
||||
#else
|
||||
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
|
||||
return try self.table(for: table)!.hasRowID
|
||||
return try self.table(for: table)!.isWithoutRowIDTable == false
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -927,6 +980,30 @@ extension Database {
|
||||
return columns.value
|
||||
}
|
||||
|
||||
if var columns = try fetchPrimitiveColumns(in: table) {
|
||||
// Discard hidden columns, so that the result of this method
|
||||
// matches the columns in `SELECT *`, and avoids surprises.
|
||||
columns = columns.filter {
|
||||
// https://www.sqlite.org/pragma.html#pragma_table_xinfo
|
||||
$0.hidden != 1
|
||||
}
|
||||
schemaCache[table.schemaID].set(columns: .value(columns), forTable: table.name)
|
||||
return columns
|
||||
} else {
|
||||
// Table does not exist
|
||||
schemaCache[table.schemaID].set(columns: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches the columns in the database table identified by `table`, or
|
||||
/// returns nil if the database schema does not contain that table.
|
||||
///
|
||||
/// This method relies entirely on SQLite schema introspection. Starting
|
||||
/// SQLite 3.26.0, it returns all columns, including
|
||||
/// [generated columns](https://www.sqlite.org/gencol.html) and
|
||||
/// [hidden columns](https://www.sqlite.org/vtab.html#hiddencol).
|
||||
func fetchPrimitiveColumns(in table: DatabaseObjectID) throws -> [ColumnInfo]? {
|
||||
// https://www.sqlite.org/pragma.html
|
||||
//
|
||||
// > PRAGMA database.table_info(table-name);
|
||||
@@ -976,23 +1053,13 @@ extension Database {
|
||||
}
|
||||
let columns = try ColumnInfo
|
||||
.fetchAll(self, sql: columnInfoQuery)
|
||||
.filter {
|
||||
// Purpose: keep generated columns, but discard hidden ones.
|
||||
// The "hidden" column magic numbers come from the SQLite
|
||||
// source code. The values 2 and 3 refer to virtual and stored
|
||||
// generated columns, respectively, and 1 refer to hidden one.
|
||||
// Search for COLFLAG_HIDDEN in
|
||||
// https://www.sqlite.org/cgi/src/file?name=src/pragma.c&ci=fca8dc8b578f215a
|
||||
$0.hidden != 1
|
||||
}
|
||||
.sorted(by: { $0.cid < $1.cid })
|
||||
|
||||
if columns.isEmpty {
|
||||
// Table does not exist
|
||||
schemaCache[table.schemaID].set(columns: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
|
||||
schemaCache[table.schemaID].set(columns: .value(columns), forTable: table.name)
|
||||
return columns
|
||||
}
|
||||
|
||||
@@ -1138,6 +1205,17 @@ public struct DatabaseSchemaID: Hashable, Sendable {
|
||||
case .temp: return "sqlite_temp_master"
|
||||
}
|
||||
}
|
||||
|
||||
func viewNameInErrorMessages(_ viewName: String) -> String {
|
||||
switch impl {
|
||||
case .main:
|
||||
return "view \(viewName)"
|
||||
case .temp:
|
||||
return "temporary view \(viewName)"
|
||||
case .attached(let schemaName):
|
||||
return "view \(schemaName).\(viewName)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier of an object in the database (table, view, etc.)
|
||||
@@ -1242,7 +1320,7 @@ public struct ColumnInfo: FetchableRecord, Sendable {
|
||||
/// The one-based index of the column in the primary key.
|
||||
///
|
||||
/// For columns that are not part of the primary key, it is zero.
|
||||
public let primaryKeyIndex: Int
|
||||
public fileprivate(set) var primaryKeyIndex: Int
|
||||
|
||||
public init(row: Row) {
|
||||
cid = row["cid"]
|
||||
@@ -1650,7 +1728,8 @@ struct TableInfo: FetchableRecord {
|
||||
var name: String
|
||||
var kind: Kind
|
||||
var columnCount: Int
|
||||
var hasRowID: Bool
|
||||
/// False for tables with a rowid, and for views.
|
||||
var isWithoutRowIDTable: Bool
|
||||
var strict: Bool
|
||||
|
||||
init(row: Row) throws {
|
||||
@@ -1658,7 +1737,7 @@ struct TableInfo: FetchableRecord {
|
||||
name = row[1]
|
||||
kind = Kind(rawValue: row[2])
|
||||
columnCount = row[3]
|
||||
hasRowID = !row[4]
|
||||
isWithoutRowIDTable = row[4]
|
||||
strict = row[5]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
/// A type that provides information about the database schema.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// The use case for a custom schema source is enabling GRDB features that
|
||||
/// would not work with the built-in schema introspection that is provided
|
||||
/// by SQLite. For example, a custom schema source can help record types
|
||||
/// that read or write in a database view.
|
||||
///
|
||||
/// You do not interact directly with values of such a type. Instead, you
|
||||
/// configure a database connection with ``Configuration/schemaSource``, and
|
||||
/// you call <doc:DatabaseSchemaIntrospection> methods on a
|
||||
/// ``Database`` connection.
|
||||
public protocol DatabaseSchemaSource: Sendable {
|
||||
/// Returns the names of the columns for the primary key in the
|
||||
/// provided database view.
|
||||
///
|
||||
/// Return nil if no customization should happen. Return an empty array
|
||||
/// to specify that the view has no primary key. The default
|
||||
/// implementation returns nil.
|
||||
///
|
||||
/// In your implementation, make sure that:
|
||||
///
|
||||
/// - The returned columns exist in the database schema.
|
||||
/// - The returned columns identify unique rows.
|
||||
/// - The returned columns do not contain NULL values.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct MySchemaSource: DatabaseSchemaSource {
|
||||
/// func columnsForPrimaryKey(
|
||||
/// _ db: Database,
|
||||
/// inView view: DatabaseObjectID
|
||||
/// ) throws -> [String]? {
|
||||
/// switch table.name {
|
||||
/// case "player":
|
||||
/// // Use the email column as the primary key of this view.
|
||||
/// return ["email"]
|
||||
///
|
||||
/// default:
|
||||
/// // Do not customize.
|
||||
/// return nil
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
func columnsForPrimaryKey(
|
||||
_ db: Database,
|
||||
inView view: DatabaseObjectID
|
||||
) throws -> [String]?
|
||||
}
|
||||
|
||||
extension DatabaseSchemaSource {
|
||||
public func columnsForPrimaryKey(
|
||||
_ db: Database,
|
||||
inView view: DatabaseObjectID
|
||||
) throws -> [String]? {
|
||||
nil
|
||||
}
|
||||
}
|
||||
@@ -96,6 +96,7 @@ do {
|
||||
- ``persistentReadOnlyConnections``
|
||||
- ``prepareDatabase(_:)``
|
||||
- ``publicStatementArguments``
|
||||
- ``schemaSource``
|
||||
- ``transactionClock``
|
||||
- ``TransactionClock``
|
||||
|
||||
@@ -106,3 +107,7 @@ do {
|
||||
- ``writeQoS``
|
||||
- ``targetQueue``
|
||||
- ``writeTargetQueue``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseSchemaSource``
|
||||
@@ -60,6 +60,7 @@
|
||||
5623B61A2AED39C300436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6182AED39C200436239 /* DatabaseQueueTemporaryCopyTests.swift */; };
|
||||
56256EDE25D1BC07008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256EDD25D1BC07008C2BDD /* ForeignKey.swift */; };
|
||||
562756461E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
562822FC2E631F3200B5A627 /* DatabaseSchemaSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */; };
|
||||
562B58CE2A29BC0700E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */; };
|
||||
562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
|
||||
562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
|
||||
@@ -516,6 +517,7 @@
|
||||
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
|
||||
56256EDD25D1BC07008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
|
||||
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
|
||||
562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSource.swift; sourceTree = "<group>"; };
|
||||
562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
|
||||
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
|
||||
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1597,6 +1599,7 @@
|
||||
569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */,
|
||||
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */,
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */,
|
||||
566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */,
|
||||
568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
@@ -2029,6 +2032,7 @@
|
||||
566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
562822FC2E631F3200B5A627 /* DatabaseSchemaSource.swift in Sources */,
|
||||
5656A8732295BD56001FF3FF /* QueryInterfaceRequest.swift in Sources */,
|
||||
566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */,
|
||||
|
||||
Reference in new issue
Block a user