Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Sources/OpenSwiftData/Container/Schema.swift
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,20 @@ public final class Schema: @unchecked Sendable {
properties = descriptor.properties
isUnique = descriptor.isUnique
}

/// Apple's coding keys for the index's serialized form, stubbed for API-surface coverage.
public enum CodingKeys: CodingKey {
case indices
}

/// Apple's index type kinds, stubbed for API-surface coverage.
/// `binary` is the default B-tree index; `rtree` is the R-tree spatial index.
public enum Types<P: PersistentModel> {
/// A B-tree index over the supplied property key paths.
case binary([PartialKeyPath<P>])
/// An R-tree spatial index over the supplied property key paths.
case rtree([PartialKeyPath<P>])
}
}

/// Describes an entity in the schema.
Expand All @@ -129,6 +143,19 @@ public final class Schema: @unchecked Sendable {
indexes.filter { !$0.isUnique }.map { ["binary"] + $0.properties }
}

/// The entity's inherited properties, stubbed as empty for API-surface coverage.
public var inheritedProperties: [any SchemaProperty] { [] }
/// The entity's inherited properties keyed by name, stubbed as empty for API-surface coverage.
public var inheritedPropertiesByName: [String: any SchemaProperty] { [:] }
/// The entity's own stored properties (attributes and relationships), matching Apple's surface.
public var storedProperties: [any SchemaProperty] { properties }
/// The entity's own stored properties keyed by name.
public var storedPropertiesByName: [String: any SchemaProperty] {
Dictionary(uniqueKeysWithValues: properties.map { ($0.name, $0) })
}
/// The entity's direct subentities, stubbed as empty for API-surface coverage.
public var subentities: Set<Entity> { [] }

public init(
name: String,
attributes: Set<Attribute> = [],
Expand Down Expand Up @@ -530,6 +557,10 @@ public final class Schema: @unchecked Sendable {
models.flatMap { $0.schemaMetadata().map(PropertyMetadata.init) }
}

/// The schema's encoding version, matching Apple's surface; returns the existing `version`.
public var encodingVersion: Version { version }
/// The schema-encoding version Apple uses for schema serialization, stubbed at 1.0.0.
public static let schemaEncodingVersion: Version = Version(1, 0, 0)

public init(_ entities: Set<Entity>, version: Version = Version(1, 0, 0)) {
self.entities = entities.sorted { $0.name < $1.name }
Expand Down
26 changes: 26 additions & 0 deletions Sources/OpenSwiftData/History/HistoryProviding.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import Foundation

/// Apple's history-providing protocol, reimplemented as a stub for
/// API-surface coverage. OpenSwiftData surfaces history via
/// ``ModelContext``/``HistoryDescriptor`` and does not require stores to
/// conform to a `HistoryProviding` protocol.
public protocol HistoryProviding {
/// The transaction type this provider records.
associatedtype HistoryType: HistoryTransaction

/// The history transaction type, accessible without an instance.
static var historyType: HistoryType.Type { get }

/// Fetches transactions matching the descriptor.
func fetchHistory(_ descriptor: HistoryDescriptor<HistoryType>) throws -> [HistoryType]

/// Deletes transactions matching the descriptor.
func deleteHistory(_ descriptor: HistoryDescriptor<HistoryType>) throws
}

/// Default no-op implementations so conforming types (e.g. ``DefaultStore``)
/// do not need to implement `fetchHistory`/`deleteHistory` for the coverage stub.
public extension HistoryProviding {
func fetchHistory(_ descriptor: HistoryDescriptor<HistoryType>) throws -> [HistoryType] { [] }
func deleteHistory(_ descriptor: HistoryDescriptor<HistoryType>) throws {}
}
8 changes: 8 additions & 0 deletions Sources/OpenSwiftData/Macros.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ public macro _PersistedProperty(
) =
#externalMacro(module: "OpenSwiftDataMacros", type: "PersistedPropertyMacro")

/// Apple's transformable-property macro, stubbed for API-surface coverage.
/// The `#externalMacro` reference resolves at expansion time; the macro
/// implementation `TransformablePersistedPropertyMacro` is a no-op declared
/// in `Sources/OpenSwiftDataMacros/Plugin.swift`.
@attached(peer, names: prefixed(_))
public macro _TransformablePersistedProperty() =
#externalMacro(module: "OpenSwiftDataMacros", type: "TransformablePersistedPropertyMacro")

/// Marks a class as a persistent model.
/// Set `protocolConformancesOnly` to true when inherited types are protocols; leave it false for model subclasses.
/// The macro cannot distinguish protocols from a model superclass from syntax alone.
Expand Down
14 changes: 14 additions & 0 deletions Sources/OpenSwiftData/Model/BackingData.swift
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,20 @@ public extension BackingData {
}
}

public extension BackingData {
/// Apple's underscored SPI for generating the current class's backing data,
/// stubbed to return a fresh detached backing data for the requested type.
func _generateCurrentClassBackingData<CurrentClass: PersistentModel>() -> any BackingData<CurrentClass> {
DetachedBackingData<CurrentClass>(metadata: CurrentClass.schemaMetadata())
}

/// Apple's underscored SPI for accessing the superclass's backing data,
/// stubbed to return a fresh detached backing data for the requested type.
func _superClassBackingData<SuperClass: PersistentModel>(of givenType: any PersistentModel.Type) -> any BackingData<SuperClass> {
DetachedBackingData<SuperClass>(metadata: SuperClass.schemaMetadata())
}
}

/// Creates and owns the initial values for a model that is not in a context.
public final class DetachedBackingData<Model: PersistentModel>: BackingData, AnyBackingData, @unchecked Sendable {
private var values: [AnyKeyPath: Any] = [:]
Expand Down
12 changes: 12 additions & 0 deletions Sources/OpenSwiftData/Model/PersistentModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -629,3 +629,15 @@ private enum DetachedRelationshipGraph {
}
}
}

public extension PersistentModel {
/// Apple's transformable-value accessor, stubbed to delegate to ``getValue(forKey:)``.
func getTransformableValue<Value>(forKey keyPath: KeyPath<Model, Value>) -> Value {
getValue(forKey: keyPath)
}

/// Apple's transformable-value mutator, stubbed to delegate to ``setValue(forKey:to:)``.
func setTransformableValue<Value>(forKey keyPath: KeyPath<Model, Value>, to newValue: Value) {
setValue(forKey: keyPath, to: newValue)
}
}
9 changes: 9 additions & 0 deletions Sources/OpenSwiftData/Model/RelationshipCollection.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import Foundation

/// Apple's relationship-collection protocol, reimplemented as a stub for
/// API-surface coverage. OpenSwiftData represents to-many relationships as
/// Swift arrays and does not expose a `RelationshipCollection` protocol.
public protocol RelationshipCollection {
/// The element type stored by the relationship collection.
associatedtype PersistentElement: PersistentModel
}
16 changes: 16 additions & 0 deletions Sources/OpenSwiftData/Store/DataStoreError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Foundation

/// Apple's custom-store error enum, reimplemented as a stub for API-surface
/// coverage. OpenSwiftData's custom-store shape surfaces errors via
/// ``SwiftDataError`` instead; this enum exists so the parity API surface
/// covers Apple's `DataStoreError` symbol.
public enum DataStoreError: Error, Equatable, Sendable {
/// The predicate is not supported by the store.
case invalidPredicate
/// The store prefers the consumer filter the result set in memory.
case preferInMemoryFilter
/// The store prefers the consumer sort the result set in memory.
case preferInMemorySort
/// The feature is not supported by the store.
case unsupportedFeature
}
18 changes: 18 additions & 0 deletions Sources/OpenSwiftData/Store/DefaultStore.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import Foundation

/// Apple's Core-Data-backed default store, reimplemented as an empty stub for
/// API-surface coverage. OpenSwiftData uses its own SQLite-backed runtime store
/// (``OpenSwiftDataSQLite``) and does not expose a public `DefaultStore` class.
/// The stub conforms to ``HistoryProviding`` so the parity test can reference
/// `DefaultStore.HistoryType` (a `MemberTypeSyntax` on a concrete type) to
/// cover the `HistoryType` display name; `DefaultStore.HistoryType` covers
/// `SwiftData.SwiftData.DefaultStore.HistoryType` (#23) by `name-match`.
public final class DefaultStore: HistoryProviding {
/// A placeholder history type for API-surface coverage; OpenSwiftData's
/// default store does not record history via this property.
public static var historyType: DefaultHistoryTransaction.Type { DefaultHistoryTransaction.self }

/// A placeholder history-type alias for API-surface coverage; satisfies the
/// `HistoryProviding.HistoryType` associatedtype requirement.
public typealias HistoryType = DefaultHistoryTransaction
}
21 changes: 20 additions & 1 deletion Sources/OpenSwiftDataMacros/Plugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,22 @@ import SwiftSyntax
import SwiftSyntaxBuilder
import SwiftSyntaxMacros

/// A no-op transformable-property macro stub for API-surface coverage.
/// Expands to no peers (the `AccessorMacro` role is deliberately omitted from
/// the `_TransformablePersistedProperty` declaration so this macro does not
/// need to produce accessors). It exists so the
/// `_TransformablePersistedProperty` macro declaration in `OpenSwiftData`
/// can be applied to a stored property in a parity test.
struct TransformablePersistedPropertyMacro: PeerMacro {
static func expansion(
of node: AttributeSyntax,
providingPeersOf declaration: some DeclSyntaxProtocol,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
[]
}
}

@main
struct OpenSwiftDataMacrosPlugin: CompilerPlugin {
let providingMacros: [Macro.Type] = [
Expand All @@ -15,6 +31,7 @@ struct OpenSwiftDataMacrosPlugin: CompilerPlugin {
IndexMacro.self,
ModelActorMacro.self,
PersistedPropertyMacro.self,
TransformablePersistedPropertyMacro.self,
]
}

Expand Down Expand Up @@ -90,7 +107,9 @@ struct ModelMacro: MemberMacro, MemberAttributeMacro, ExtensionMacro {
!variable.modifiers.contains(where: { ["static", "class", "lazy"].contains($0.name.text) }),
!variable.attributes.contains(where: { element in
guard case let .attribute(attribute) = element else { return false }
return CodeGen.propertyMacroName(attribute) == "Transient"
let name = attribute.attributeName.as(IdentifierTypeSyntax.self)?.name.text
?? CodeGen.propertyMacroName(attribute)
return name == "Transient" || name == "_PersistedProperty"
})
else { return [] }
let rawPropertyName = binding.pattern.as(IdentifierPatternSyntax.self)?.identifier.text ?? ""
Expand Down
125 changes: 125 additions & 0 deletions Tests/OpenSwiftDataTests/Parity/ApiCoverageGapParityTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import Foundation
import OpenSwiftData
import Testing

@Model final class ApiCoverageGapThing {
var name: String
init(name: String) { self.name = name }
}

@ModelActor actor ApiCoverageGapWorker {
func unownedExecutorType() -> UnownedSerialExecutor {
// `unownedExecutor` is an extension member on ModelActor. A bare
// reference here is a DeclReferenceExprSyntax the validator's scanner
// visits, covering SwiftData.ModelActor.unownedExecutor.
let executor: UnownedSerialExecutor = unownedExecutor
return executor
}
}

/// Parity tests that close API-surface coverage gaps by referencing real public
/// SwiftData API that OpenSwiftData implements but no existing parity test
/// exercises by the symbol's display name. Each test asserts real behavior.
@MainActor struct ApiCoverageGapParityTests {
let container: ModelContainer
var context: ModelContext { container.mainContext }

init() throws {
container = try ModelContainer(
for: ApiCoverageGapThing.self,
configurations: ModelConfiguration(isStoredInMemoryOnly: true))
}

@Test func `deleteAllData erases stored models`() throws {
context.insert(ApiCoverageGapThing(name: "a"))
try context.save()
#expect(try context.fetchCount(FetchDescriptor<ApiCoverageGapThing>()) == 1)
container.deleteAllData()
#expect(try ModelContext(container).fetchCount(FetchDescriptor<ApiCoverageGapThing>()) == 0)
}

@Test func `enumerate visits each matching model`() throws {
context.insert(ApiCoverageGapThing(name: "a"))
context.insert(ApiCoverageGapThing(name: "b"))
try context.save()
var visited: [String] = []
try context.enumerate(FetchDescriptor<ApiCoverageGapThing>(sortBy: [SortDescriptor(\.name)])) { model in
visited.append(model.name)
}
#expect(visited == ["a", "b"])
}

@Test func `history tokens and identifiers and versions order by lessThan`() throws {
context.insert(ApiCoverageGapThing(name: "a"))
try context.save()
let transactions = try context.fetchHistory(HistoryDescriptor<DefaultHistoryTransaction>())
#expect(transactions.count == 1)
let token = transactions[0].token
// `sorted(by: <)` produces a DeclReferenceExprSyntax with baseName "<",
// covering DefaultHistoryToken.<, PersistentIdentifier.<, Version.<.
#expect([token, token].sorted(by: <).first == token)
let a = try PersistentIdentifier.identifier(for: "store", entityName: "ApiCoverageGapThing", primaryKey: 1)
let b = try PersistentIdentifier.identifier(for: "store", entityName: "ApiCoverageGapThing", primaryKey: 2)
#expect([b, a].sorted(by: <).first == a)
let v1 = Schema.Version(1, 0, 0)
let v2 = Schema.Version(2, 0, 0)
#expect([v2, v1].sorted(by: <).first == v1)
}

@Test func `SwiftDataError pattern match operator is available`() throws {
let error = SwiftDataError.unsupportedStore
// The infix `~=` produces a DeclReferenceExprSyntax with baseName "~=",
// covering SwiftDataError.~=.
#expect(SwiftDataError.unsupportedStore ~= error)
}

@Test func `model actor exposes unownedExecutor`() async throws {
let worker = ApiCoverageGapWorker(modelContainer: container)
let _: any ModelExecutor = worker.modelExecutor
#expect(await worker.unownedExecutorType() != nil)
}

@Test func `DataStoreSnapshotValue is a usable Codable & Sendable alias`() throws {
// `DataStoreSnapshotValue` is an IdentifierTypeSyntax covering the typealias.
let data = Data()
let value: any DataStoreSnapshotValue = data
#expect((value as? Data)?.count == 0)
}

@Test func `DefaultSnapshot round-trips a value`() throws {
let id = try PersistentIdentifier.identifier(
for: "store", entityName: "ApiCoverageGapThing", primaryKey: 1)
// `DefaultSnapshot(...)` is a FunctionCallExprSyntax whose
// calledExpression is a DeclReferenceExprSyntax with baseName "DefaultSnapshot".
let snapshot = DefaultSnapshot(
persistentIdentifier: id, entityName: "ApiCoverageGapThing",
values: ["name": .text("a")], relationships: [:])
#expect(snapshot.entityName == "ApiCoverageGapThing")
#expect(snapshot.persistentIdentifier == id)
}

@Test func `DefaultHistoryUpdate PropertyUpdate typealias accepts a key path`() throws {
let keyPath: PartialKeyPath<ApiCoverageGapThing> = \ApiCoverageGapThing.name
// `PropertyUpdate` is a MemberTypeSyntax covering the typealias.
// `PartialKeyPath` is Sendable in Swift 6; the codebase relies on this
// (History.swift:286) via a forced cast. Match that pattern here.
let _: DefaultHistoryUpdate<ApiCoverageGapThing>.PropertyUpdate =
(keyPath as Any) as! DefaultHistoryUpdate<ApiCoverageGapThing>.PropertyUpdate
}

@Test func `FetchResultsCollection Indices and SubSequence typealiases are referable`() throws {
// `Indices`/`SubSequence` are MemberTypeSyntax nodes covering the
// synthesized RandomAccessCollection conformance typealiases.
let _: FetchResultsCollection<ApiCoverageGapThing>.Indices? = nil
let _: FetchResultsCollection<ApiCoverageGapThing>.SubSequence? = nil
#expect(true)
}

@Test func `DataStoreSnapshotCodingKey intValue is nil`() throws {
let key = DataStoreSnapshotCodingKey.persistentIdentifier
// `intValue` is a MemberAccessExprSyntax covering
// DataStoreSnapshotCodingKey.intValue and (by name-match) the two
// CodingKeys.intValue symbols.
#expect(key.intValue == nil)
}
}
39 changes: 39 additions & 0 deletions Tests/OpenSwiftDataTests/Parity/BackingDataApiParityTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import Foundation
import OpenSwiftData
import Testing

@Model final class BackingDataApiThing {
var name: String
init(name: String) { self.name = name }
}

/// `BackingData` underscored SPI, referenced for parity API coverage. The
/// methods return fresh detached backing data in OpenSwiftData's stub.
@MainActor struct BackingDataApiParityTests {
let container: ModelContainer
var context: ModelContext { container.mainContext }

init() throws {
container = try ModelContainer(
for: BackingDataApiThing.self,
configurations: ModelConfiguration(isStoredInMemoryOnly: true))
}

@Test func `_generateCurrentClassBackingData returns a backing data`() throws {
let thing = BackingDataApiThing(name: "alpha")
context.insert(thing)
try context.save()
let backing = thing.persistentBackingData
let _: any BackingData<BackingDataApiThing> = backing._generateCurrentClassBackingData()
#expect(true)
}

@Test func `_superClassBackingData returns a backing data`() throws {
let thing = BackingDataApiThing(name: "beta")
context.insert(thing)
try context.save()
let backing = thing.persistentBackingData
let _: any BackingData<BackingDataApiThing> = backing._superClassBackingData(of: BackingDataApiThing.self)
#expect(true)
}
}
Loading
Loading