├── .devcontainer └── devcontainer.json ├── .github └── workflows │ ├── DataThespian.yml │ └── codeql.yml ├── .gitignore ├── .periphery.yml ├── .spi.yml ├── .swift-format ├── .swiftlint.yml ├── Example ├── Sources │ ├── Assets.xcassets │ │ ├── AccentColor.colorset │ │ │ └── Contents.json │ │ ├── AppIcon.appiconset │ │ │ └── Contents.json │ │ └── Contents.json │ ├── ChildViewModel.swift │ ├── ContentObject.swift │ ├── ContentView.swift │ ├── DataThespianExample.entitlements │ ├── DataThespianExampleApp.swift │ ├── Item.swift │ ├── ItemChild.swift │ ├── ItemChildView.swift │ ├── ItemViewModel.swift │ └── Preview Content │ │ └── Preview Assets.xcassets │ │ └── Contents.json └── Support │ ├── .gitkeep │ └── Info.plist ├── LICENSE ├── Mintfile ├── Package.resolved ├── Package.swift ├── README.md ├── Scripts ├── gh-md-toc ├── header.sh ├── lint.sh └── swift-doc.sh ├── Sources └── DataThespian │ ├── Assert.swift │ ├── Databases │ ├── BackgroundDatabase.swift │ ├── Database+Extras.swift │ ├── Database+Queryable.swift │ ├── Database.swift │ ├── EnvironmentValues+Database.swift │ ├── ModelActor+Database.swift │ ├── ModelActorDatabase.swift │ ├── QueryError.swift │ ├── Queryable+Extensions.swift │ ├── Queryable.swift │ ├── Selector.swift │ ├── Unique.swift │ ├── UniqueKey.swift │ ├── UniqueKeyPath.swift │ └── UniqueKeys.swift │ ├── Documentation.docc │ └── DataThespian.md │ ├── Model.swift │ ├── Notification │ ├── AgentRegister.swift │ ├── Combine │ │ ├── DatabaseChangePublicist.swift │ │ ├── EnvironmentValues+DatabaseChangePublicist.swift │ │ ├── PublishingAgent.swift │ │ └── PublishingRegister.swift │ ├── DataAgent.swift │ ├── DataMonitor.swift │ ├── DatabaseChangeSet.swift │ ├── DatabaseChangeType.swift │ ├── DatabaseMonitoring.swift │ ├── ManagedObjectMetadata.swift │ ├── Notification.swift │ ├── NotificationDataUpdate.swift │ └── RegistrationCollection.swift │ ├── SwiftData │ ├── FetchDescriptor.swift │ ├── ModelContext+Extension.swift │ ├── ModelContext+Queryable.swift │ ├── ModelContext.swift │ ├── NSManagedObjectID.swift │ └── PersistentIdentifier.swift │ ├── Synchronization │ ├── CollectionDifference.swift │ ├── CollectionSynchronizer.swift │ ├── ModelDifferenceSynchronizer.swift │ ├── ModelSynchronizer.swift │ └── SynchronizationDifference.swift │ └── ThespianLogging.swift ├── Tests └── DataThespianTests │ ├── Child.swift │ ├── DatabaseTests.swift │ ├── Parent.swift │ ├── SwiftDataIsAvailable.swift │ └── TestingDatabase.swift ├── codecov.yml ├── macros.json └── project.yml /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Swift", 3 | "image": "swift:6.0", 4 | "features": { 5 | "ghcr.io/devcontainers/features/common-utils:2": { 6 | "installZsh": "false", 7 | "username": "vscode", 8 | "upgradePackages": "false" 9 | }, 10 | "ghcr.io/devcontainers/features/git:1": { 11 | "version": "os-provided", 12 | "ppa": "false" 13 | } 14 | }, 15 | "runArgs": [ 16 | "--cap-add=SYS_PTRACE", 17 | "--security-opt", 18 | "seccomp=unconfined" 19 | ], 20 | // Configure tool-specific properties. 21 | "customizations": { 22 | // Configure properties specific to VS Code. 23 | "vscode": { 24 | // Set *default* container specific settings.json values on container create. 25 | "settings": { 26 | "lldb.library": "/usr/lib/liblldb.so" 27 | }, 28 | // Add the IDs of extensions you want installed when the container is created. 29 | "extensions": [ 30 | "sswg.swift-lang" 31 | ] 32 | } 33 | }, 34 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 35 | // "forwardPorts": [], 36 | 37 | // Set `remoteUser` to `root` to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 38 | "remoteUser": "vscode" 39 | } 40 | -------------------------------------------------------------------------------- /.github/workflows/DataThespian.yml: -------------------------------------------------------------------------------- 1 | name: DataThespian 2 | on: 3 | push: 4 | branches-ignore: 5 | - '*WIP' 6 | env: 7 | PACKAGE_NAME: DataThespian 8 | jobs: 9 | build-ubuntu: 10 | name: Build on Ubuntu 11 | env: 12 | SWIFT_VER: 6.0 13 | if: "!contains(github.event.head_commit.message, 'ci skip')" 14 | runs-on: ubuntu-latest 15 | container: 16 | image: swift:6.0 17 | steps: 18 | - uses: actions/checkout@v4 19 | - name: Cache swift package modules 20 | id: cache-spm-linux 21 | uses: actions/cache@v4 22 | env: 23 | cache-name: cache-spm 24 | with: 25 | path: .build 26 | key: ${{ runner.os }}-${{ env.cache-name }}-${{ matrix.swift-version }}-${{ hashFiles('Package.resolved') }} 27 | restore-keys: | 28 | ${{ runner.os }}-${{ env.cache-name }}-${{ matrix.swift-version }}- 29 | ${{ runner.os }}-${{ env.cache-name }}- 30 | - name: Test 31 | run: swift test --enable-code-coverage 32 | - uses: sersoft-gmbh/swift-coverage-action@v4 33 | id: coverage-files 34 | with: 35 | fail-on-empty-output: true 36 | - name: Upload coverage to Codecov 37 | uses: codecov/codecov-action@v4 38 | with: 39 | fail_ci_if_error: true 40 | flags: swift-${{ matrix.swift-version }},ubuntu 41 | verbose: true 42 | token: ${{ secrets.CODECOV_TOKEN }} 43 | files: ${{ join(fromJSON(steps.coverage-files.outputs.files), ',') }} 44 | build-macos: 45 | name: Build on macOS 46 | runs-on: ${{ matrix.os }} 47 | if: "!contains(github.event.head_commit.message, 'ci skip')" 48 | strategy: 49 | matrix: 50 | include: 51 | - xcode: "/Applications/Xcode_16.2.app" 52 | os: macos-15 53 | iOSVersion: "18.2" 54 | watchOSVersion: "11.2" 55 | watchName: "Apple Watch Series 10 (42mm)" 56 | iPhoneName: "iPhone 16" 57 | steps: 58 | - uses: actions/checkout@v4 59 | - name: Cache swift package modules 60 | id: cache-spm-macos 61 | uses: actions/cache@v4 62 | env: 63 | cache-name: cache-spm 64 | with: 65 | path: .build 66 | key: ${{ matrix.os }}-build-${{ env.cache-name }}-${{ matrix.xcode }}-${{ hashFiles('Package.resolved') }} 67 | restore-keys: | 68 | ${{ matrix.os }}-build-${{ env.cache-name }}-${{ matrix.xcode }}- 69 | - name: Cache mint 70 | if: startsWith(matrix.xcode,'/Applications/Xcode_16.2') 71 | id: cache-mint 72 | uses: actions/cache@v4 73 | env: 74 | cache-name: cache-mint 75 | with: 76 | path: .mint 77 | key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('Mintfile') }} 78 | restore-keys: | 79 | ${{ runner.os }}-build-${{ env.cache-name }}- 80 | ${{ runner.os }}-build- 81 | ${{ runner.os }}- 82 | - name: Set Xcode Name 83 | run: echo "XCODE_NAME=$(basename -- ${{ matrix.xcode }} | sed 's/\.[^.]*$//' | cut -d'_' -f2)" >> $GITHUB_ENV 84 | - name: Setup Xcode 85 | run: sudo xcode-select -s ${{ matrix.xcode }}/Contents/Developer || (sudo ls -1 /Applications | grep "Xcode") 86 | - name: Enable Swift Testing 87 | run: | 88 | mkdir -p ~/Library/org.swift.swiftpm/security/ 89 | cp macros.json ~/Library/org.swift.swiftpm/security/ 90 | - name: Install mint 91 | if: startsWith(matrix.xcode,'/Applications/Xcode_16.2') 92 | run: | 93 | brew update 94 | brew install mint 95 | - name: Build 96 | run: swift build 97 | - name: Run Swift Package tests 98 | run: swift test --enable-code-coverage 99 | - uses: sersoft-gmbh/swift-coverage-action@v4 100 | id: coverage-files-spm 101 | with: 102 | fail-on-empty-output: true 103 | - name: Upload coverage reports to Codecov 104 | uses: codecov/codecov-action@v4 105 | with: 106 | files: ${{ join(fromJSON(steps.coverage-files-spm.outputs.files), ',') }} 107 | token: ${{ secrets.CODECOV_TOKEN }} 108 | flags: macOS,${{ env.XCODE_NAME }},${{ matrix.runs-on }} 109 | - name: Clean up spm build directory 110 | run: rm -rf .build 111 | - name: Lint 112 | run: ./scripts/lint.sh 113 | if: startsWith(matrix.xcode,'/Applications/Xcode_16.2') 114 | - name: Run iOS target tests 115 | run: xcodebuild test -scheme ${{ env.PACKAGE_NAME }} -destination 'platform=iOS Simulator,name=${{ matrix.iPhoneName }},OS=${{ matrix.iOSVersion }}' -enableCodeCoverage YES build test 116 | - uses: sersoft-gmbh/swift-coverage-action@v4 117 | id: coverage-files-iOS 118 | with: 119 | fail-on-empty-output: true 120 | - name: Upload coverage to Codecov 121 | uses: codecov/codecov-action@v4 122 | with: 123 | fail_ci_if_error: true 124 | verbose: true 125 | token: ${{ secrets.CODECOV_TOKEN }} 126 | files: ${{ join(fromJSON(steps.coverage-files-iOS.outputs.files), ',') }} 127 | flags: iOS,iOS${{ matrix.iOSVersion }},macOS,${{ env.XCODE_NAME }} 128 | - name: Run watchOS target tests 129 | run: xcodebuild test -scheme ${{ env.PACKAGE_NAME }} -destination 'platform=watchOS Simulator,name=${{ matrix.watchName }},OS=${{ matrix.watchOSVersion }}' -enableCodeCoverage YES build test 130 | - uses: sersoft-gmbh/swift-coverage-action@v4 131 | id: coverage-files-watchOS 132 | with: 133 | fail-on-empty-output: true 134 | - name: Upload coverage to Codecov 135 | uses: codecov/codecov-action@v4 136 | with: 137 | fail_ci_if_error: true 138 | verbose: true 139 | token: ${{ secrets.CODECOV_TOKEN }} 140 | files: ${{ join(fromJSON(steps.coverage-files-watchOS.outputs.files), ',') }} 141 | flags: watchOS,watchOS${{ matrix.watchOSVersion }},macOS,${{ env.XCODE_NAME }} 142 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches-ignore: 17 | - '*WIP' 18 | pull_request: 19 | # The branches below must be a subset of the branches above 20 | branches: [ "main" ] 21 | schedule: 22 | - cron: '20 11 * * 3' 23 | 24 | jobs: 25 | analyze: 26 | if: false 27 | name: Analyze 28 | # Runner size impacts CodeQL analysis time. To learn more, please see: 29 | # - https://gh.io/recommended-hardware-resources-for-running-codeql 30 | # - https://gh.io/supported-runners-and-hardware-resources 31 | # - https://gh.io/using-larger-runners 32 | # Consider using larger runners for possible analysis time improvements. 33 | runs-on: ${{ (matrix.language == 'swift' && 'macos-13') || 'ubuntu-latest' }} 34 | timeout-minutes: ${{ (matrix.language == 'swift' && 120) || 360 }} 35 | permissions: 36 | actions: read 37 | contents: read 38 | security-events: write 39 | 40 | strategy: 41 | fail-fast: false 42 | matrix: 43 | language: [ 'swift' ] 44 | # CodeQL supports [ 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'swift' ] 45 | # Use only 'java-kotlin' to analyze code written in Java, Kotlin or both 46 | # Use only 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both 47 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 48 | 49 | steps: 50 | - name: Checkout repository 51 | uses: actions/checkout@v4 52 | 53 | - name: Setup Xcode 54 | run: sudo xcode-select -s /Applications/Xcode_15.2.app/Contents/Developer 55 | 56 | # Initializes the CodeQL tools for scanning. 57 | - name: Initialize CodeQL 58 | uses: github/codeql-action/init@v3 59 | with: 60 | languages: ${{ matrix.language }} 61 | # If you wish to specify custom queries, you can do so here or in a config file. 62 | # By default, queries listed here will override any specified in a config file. 63 | # Prefix the list here with "+" to use these queries and those in the config file. 64 | 65 | # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 66 | # queries: security-extended,security-and-quality 67 | 68 | 69 | # Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift). 70 | # If this step fails, then you should remove it and run the build manually (see below) 71 | - run: | 72 | echo "Run, Build Application using script" 73 | swift build 74 | 75 | - name: Perform CodeQL Analysis 76 | uses: github/codeql-action/analyze@v3 77 | with: 78 | category: "/language:${{matrix.language}}" 79 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/swift,swiftpm,swiftpackagemanager,xcode,macos 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=swift,swiftpm,swiftpackagemanager,xcode,macos 3 | 4 | ### macOS ### 5 | # General 6 | .DS_Store 7 | .AppleDouble 8 | .LSOverride 9 | 10 | # Icon must end with two \r 11 | Icon 12 | 13 | 14 | # Thumbnails 15 | ._* 16 | 17 | # Files that might appear in the root of a volume 18 | .DocumentRevisions-V100 19 | .fseventsd 20 | .Spotlight-V100 21 | .TemporaryItems 22 | .Trashes 23 | .VolumeIcon.icns 24 | .com.apple.timemachine.donotpresent 25 | 26 | # Directories potentially created on remote AFP share 27 | .AppleDB 28 | .AppleDesktop 29 | Network Trash Folder 30 | Temporary Items 31 | .apdisk 32 | 33 | ### macOS Patch ### 34 | # iCloud generated files 35 | *.icloud 36 | 37 | ### Swift ### 38 | # Xcode 39 | # 40 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 41 | 42 | ## User settings 43 | xcuserdata/ 44 | 45 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 46 | *.xcscmblueprint 47 | *.xccheckout 48 | 49 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 50 | build/ 51 | DerivedData/ 52 | *.moved-aside 53 | *.pbxuser 54 | !default.pbxuser 55 | *.mode1v3 56 | !default.mode1v3 57 | *.mode2v3 58 | !default.mode2v3 59 | *.perspectivev3 60 | !default.perspectivev3 61 | 62 | ## Obj-C/Swift specific 63 | *.hmap 64 | 65 | ## App packaging 66 | *.ipa 67 | *.dSYM.zip 68 | *.dSYM 69 | 70 | ## Playgrounds 71 | timeline.xctimeline 72 | playground.xcworkspace 73 | 74 | # Swift Package Manager 75 | # 76 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 77 | # Packages/ 78 | # Package.pins 79 | # Package.resolved 80 | *.xcodeproj 81 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 82 | # hence it is not needed unless you have added a package configuration file to your project 83 | .swiftpm 84 | 85 | .build/ 86 | 87 | # CocoaPods 88 | # 89 | # We recommend against adding the Pods directory to your .gitignore. However 90 | # you should judge for yourself, the pros and cons are mentioned at: 91 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 92 | # 93 | # Pods/ 94 | # 95 | # Add this line if you want to avoid checking in source code from the Xcode workspace 96 | # *.xcworkspace 97 | 98 | # Carthage 99 | # 100 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 101 | # Carthage/Checkouts 102 | 103 | Carthage/Build/ 104 | 105 | # fastlane 106 | # It is recommended to not store the screenshots in the git repo. 107 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 108 | # For more information about the recommended setup visit: 109 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 110 | 111 | fastlane/report.xml 112 | fastlane/Preview.html 113 | fastlane/screenshots/**/*.png 114 | fastlane/test_output 115 | 116 | # Code Injection 117 | # After new code Injection tools there's a generated folder /iOSInjectionProject 118 | # https://github.com/johnno1962/injectionforxcode 119 | 120 | iOSInjectionProject/ 121 | 122 | ### SwiftPackageManager ### 123 | # Packages 124 | xcuserdata 125 | *.xcodeproj 126 | 127 | 128 | ### SwiftPM ### 129 | 130 | 131 | ### Xcode ### 132 | 133 | ## Xcode 8 and earlier 134 | 135 | ### Xcode Patch ### 136 | *.xcodeproj/* 137 | !*.xcodeproj/project.pbxproj 138 | !*.xcodeproj/xcshareddata/ 139 | !*.xcodeproj/project.xcworkspace/ 140 | !*.xcworkspace/contents.xcworkspacedata 141 | /*.gcno 142 | **/xcshareddata/WorkspaceSettings.xcsettings 143 | .mint 144 | # End of https://www.toptal.com/developers/gitignore/api/swift,swiftpm,swiftpackagemanager,xcode,macos 145 | 146 | test_output.log 147 | .docc-build 148 | public -------------------------------------------------------------------------------- /.periphery.yml: -------------------------------------------------------------------------------- 1 | retain_public: true 2 | -------------------------------------------------------------------------------- /.spi.yml: -------------------------------------------------------------------------------- 1 | version: 1 2 | builder: 3 | configs: 4 | - documentation_targets: [DataThespian] 5 | swift_version: 6.0 6 | -------------------------------------------------------------------------------- /.swift-format: -------------------------------------------------------------------------------- 1 | { 2 | "fileScopedDeclarationPrivacy" : { 3 | "accessLevel" : "fileprivate" 4 | }, 5 | "indentation" : { 6 | "spaces" : 2 7 | }, 8 | "indentConditionalCompilationBlocks" : true, 9 | "indentSwitchCaseLabels" : false, 10 | "lineBreakAroundMultilineExpressionChainComponents" : false, 11 | "lineBreakBeforeControlFlowKeywords" : false, 12 | "lineBreakBeforeEachArgument" : false, 13 | "lineBreakBeforeEachGenericRequirement" : false, 14 | "lineLength" : 100, 15 | "maximumBlankLines" : 1, 16 | "multiElementCollectionTrailingCommas" : true, 17 | "noAssignmentInExpressions" : { 18 | "allowedFunctions" : [ 19 | "XCTAssertNoThrow" 20 | ] 21 | }, 22 | "prioritizeKeepingFunctionOutputTogether" : false, 23 | "respectsExistingLineBreaks" : true, 24 | "rules" : { 25 | "AllPublicDeclarationsHaveDocumentation" : true, 26 | "AlwaysUseLiteralForEmptyCollectionInit" : false, 27 | "AlwaysUseLowerCamelCase" : true, 28 | "AmbiguousTrailingClosureOverload" : true, 29 | "BeginDocumentationCommentWithOneLineSummary" : false, 30 | "DoNotUseSemicolons" : true, 31 | "DontRepeatTypeInStaticProperties" : true, 32 | "FileScopedDeclarationPrivacy" : false, 33 | "FullyIndirectEnum" : true, 34 | "GroupNumericLiterals" : true, 35 | "IdentifiersMustBeASCII" : true, 36 | "NeverForceUnwrap" : true, 37 | "NeverUseForceTry" : true, 38 | "NeverUseImplicitlyUnwrappedOptionals" : true, 39 | "NoAccessLevelOnExtensionDeclaration" : true, 40 | "NoAssignmentInExpressions" : true, 41 | "NoBlockComments" : true, 42 | "NoCasesWithOnlyFallthrough" : true, 43 | "NoEmptyTrailingClosureParentheses" : true, 44 | "NoLabelsInCasePatterns" : true, 45 | "NoLeadingUnderscores" : true, 46 | "NoParensAroundConditions" : true, 47 | "NoPlaygroundLiterals" : true, 48 | "NoVoidReturnOnFunctionSignature" : true, 49 | "OmitExplicitReturns" : false, 50 | "OneCasePerLine" : true, 51 | "OneVariableDeclarationPerLine" : true, 52 | "OnlyOneTrailingClosureArgument" : true, 53 | "OrderedImports" : true, 54 | "ReplaceForEachWithForLoop" : true, 55 | "ReturnVoidInsteadOfEmptyTuple" : true, 56 | "TypeNamesShouldBeCapitalized" : true, 57 | "UseEarlyExits" : false, 58 | "UseExplicitNilCheckInConditions" : true, 59 | "UseLetInEveryBoundCaseVariable" : true, 60 | "UseShorthandTypeNames" : true, 61 | "UseSingleLinePropertyGetter" : true, 62 | "UseSynthesizedInitializer" : true, 63 | "UseTripleSlashForDocumentationComments" : true, 64 | "UseWhereClausesInForLoops" : true, 65 | "ValidateDocumentationComments" : true 66 | }, 67 | "spacesAroundRangeFormationOperators" : false, 68 | "tabWidth" : 2, 69 | "version" : 1 70 | } -------------------------------------------------------------------------------- /.swiftlint.yml: -------------------------------------------------------------------------------- 1 | opt_in_rules: 2 | - array_init 3 | - closure_body_length 4 | - closure_end_indentation 5 | - closure_spacing 6 | - collection_alignment 7 | - conditional_returns_on_newline 8 | - contains_over_filter_count 9 | - contains_over_filter_is_empty 10 | - contains_over_first_not_nil 11 | - contains_over_range_nil_comparison 12 | - convenience_type 13 | - discouraged_object_literal 14 | - discouraged_optional_boolean 15 | - empty_collection_literal 16 | - empty_count 17 | - empty_string 18 | - empty_xctest_method 19 | - enum_case_associated_values_count 20 | - expiring_todo 21 | - explicit_acl 22 | - explicit_init 23 | - explicit_top_level_acl 24 | # - fallthrough 25 | - fatal_error_message 26 | - file_name 27 | - file_name_no_space 28 | - file_types_order 29 | - first_where 30 | - flatmap_over_map_reduce 31 | - force_unwrapping 32 | # - function_default_parameter_at_end 33 | - ibinspectable_in_extension 34 | - identical_operands 35 | - implicit_return 36 | - implicitly_unwrapped_optional 37 | - indentation_width 38 | - joined_default_parameter 39 | - last_where 40 | - legacy_multiple 41 | - legacy_random 42 | - literal_expression_end_indentation 43 | - lower_acl_than_parent 44 | # - missing_docs 45 | - modifier_order 46 | - multiline_arguments 47 | - multiline_arguments_brackets 48 | - multiline_function_chains 49 | - multiline_literal_brackets 50 | - multiline_parameters 51 | - nimble_operator 52 | - nslocalizedstring_key 53 | - nslocalizedstring_require_bundle 54 | - number_separator 55 | - object_literal 56 | - operator_usage_whitespace 57 | - optional_enum_case_matching 58 | - overridden_super_call 59 | - override_in_extension 60 | - pattern_matching_keywords 61 | - prefer_self_type_over_type_of_self 62 | - prefer_zero_over_explicit_init 63 | - private_action 64 | - private_outlet 65 | - prohibited_interface_builder 66 | - prohibited_super_call 67 | - quick_discouraged_call 68 | - quick_discouraged_focused_test 69 | - quick_discouraged_pending_test 70 | - reduce_into 71 | - redundant_nil_coalescing 72 | - redundant_type_annotation 73 | - required_enum_case 74 | - single_test_class 75 | - sorted_first_last 76 | - sorted_imports 77 | - static_operator 78 | - strong_iboutlet 79 | - toggle_bool 80 | # - trailing_closure 81 | - type_contents_order 82 | - unavailable_function 83 | - unneeded_parentheses_in_closure_argument 84 | - unowned_variable_capture 85 | - untyped_error_in_catch 86 | - vertical_parameter_alignment_on_call 87 | - vertical_whitespace_closing_braces 88 | - vertical_whitespace_opening_braces 89 | - xct_specific_matcher 90 | - yoda_condition 91 | analyzer_rules: 92 | - unused_import 93 | - unused_declaration 94 | cyclomatic_complexity: 95 | - 6 96 | - 12 97 | file_length: 98 | warning: 225 99 | error: 300 100 | function_body_length: 101 | - 50 102 | - 76 103 | function_parameter_count: 8 104 | line_length: 105 | - 108 106 | - 200 107 | closure_body_length: 108 | - 50 109 | - 60 110 | type_name: 111 | excluded: 112 | - ID 113 | identifier_name: 114 | excluded: 115 | - id 116 | - no 117 | excluded: 118 | - DerivedData 119 | - .build 120 | indentation_width: 121 | indentation_width: 2 122 | file_name: 123 | severity: error 124 | fatal_error_message: 125 | severity: error 126 | disabled_rules: 127 | - nesting 128 | - implicit_getter 129 | - switch_case_alignment 130 | - closure_parameter_position 131 | - trailing_comma 132 | - opening_brace -------------------------------------------------------------------------------- /Example/Sources/Assets.xcassets/AccentColor.colorset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "colors" : [ 3 | { 4 | "idiom" : "universal" 5 | } 6 | ], 7 | "info" : { 8 | "author" : "xcode", 9 | "version" : 1 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Example/Sources/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "mac", 5 | "scale" : "1x", 6 | "size" : "16x16" 7 | }, 8 | { 9 | "idiom" : "mac", 10 | "scale" : "2x", 11 | "size" : "16x16" 12 | }, 13 | { 14 | "idiom" : "mac", 15 | "scale" : "1x", 16 | "size" : "32x32" 17 | }, 18 | { 19 | "idiom" : "mac", 20 | "scale" : "2x", 21 | "size" : "32x32" 22 | }, 23 | { 24 | "idiom" : "mac", 25 | "scale" : "1x", 26 | "size" : "128x128" 27 | }, 28 | { 29 | "idiom" : "mac", 30 | "scale" : "2x", 31 | "size" : "128x128" 32 | }, 33 | { 34 | "idiom" : "mac", 35 | "scale" : "1x", 36 | "size" : "256x256" 37 | }, 38 | { 39 | "idiom" : "mac", 40 | "scale" : "2x", 41 | "size" : "256x256" 42 | }, 43 | { 44 | "idiom" : "mac", 45 | "scale" : "1x", 46 | "size" : "512x512" 47 | }, 48 | { 49 | "idiom" : "mac", 50 | "scale" : "2x", 51 | "size" : "512x512" 52 | } 53 | ], 54 | "info" : { 55 | "author" : "xcode", 56 | "version" : 1 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Example/Sources/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Example/Sources/ChildViewModel.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ChildViewModel.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion on 10/16/24. 6 | // 7 | 8 | import DataThespian 9 | import Foundation 10 | import SwiftData 11 | 12 | internal struct ChildViewModel: Sendable, Identifiable { 13 | internal let model: Model 14 | internal let timestamp: Date 15 | 16 | internal var id: PersistentIdentifier { 17 | model.persistentIdentifier 18 | } 19 | 20 | private init(model: Model, timestamp: Date) { 21 | self.model = model 22 | self.timestamp = timestamp 23 | } 24 | 25 | internal init(child: ItemChild) { 26 | self.init(model: .init(child), timestamp: child.timestamp) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Example/Sources/ContentObject.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ContentObject.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion on 10/10/24. 6 | // 7 | 8 | import Combine 9 | import DataThespian 10 | import Foundation 11 | import SwiftData 12 | 13 | @Observable 14 | @MainActor 15 | internal class ContentObject { 16 | internal let databaseChangePublisher = PassthroughSubject() 17 | private var databaseChangeCancellable: AnyCancellable? 18 | private var databaseChangeSubscription: AnyCancellable? 19 | private var database: (any Database)? 20 | internal private(set) var items = [ItemViewModel]() 21 | internal var selectedItemsID: Set = [] 22 | private var newItem: AnyCancellable? 23 | internal var error: (any Error)? 24 | 25 | internal var selectedItems: [ItemViewModel] { 26 | let selectedItemsID = self.selectedItemsID 27 | let items: [ItemViewModel] 28 | do { 29 | items = try self.items.filter( 30 | #Predicate { 31 | selectedItemsID.contains($0.id) 32 | } 33 | ) 34 | } catch { 35 | assertionFailure("Unable to filter selected items: \(error.localizedDescription)") 36 | self.error = error 37 | items = [] 38 | } 39 | // assert(items.count == selectedItemsID.count) 40 | return items 41 | } 42 | 43 | internal init() { 44 | self.databaseChangeSubscription = self.databaseChangePublisher.sink { _ in 45 | self.beginUpdateItems() 46 | } 47 | } 48 | 49 | private static func deleteModels(_ models: [Model], from database: (any Database)) 50 | async throws 51 | { 52 | try await database.deleteModels(models) 53 | } 54 | 55 | private func beginUpdateItems() { 56 | Task { 57 | do { 58 | try await self.updateItems() 59 | } catch { 60 | self.error = error 61 | } 62 | } 63 | } 64 | 65 | private func updateItems() async throws { 66 | guard let database else { 67 | return 68 | } 69 | self.items = try await database.withModelContext { modelContext in 70 | let items = try modelContext.fetch(FetchDescriptor()) 71 | return items.map(ItemViewModel.init) 72 | } 73 | } 74 | 75 | internal func initialize( 76 | withDatabase database: any Database, databaseChangePublisher: DatabaseChangePublicist 77 | ) { 78 | self.database = database 79 | self.databaseChangeCancellable = databaseChangePublisher(id: "contentView") 80 | .subscribe(self.databaseChangePublisher) 81 | self.beginUpdateItems() 82 | } 83 | 84 | internal func deleteSelectedItems() { 85 | let models = self.selectedItems.map { 86 | Model(persistentIdentifier: $0.id) 87 | } 88 | self.deleteItems(models) 89 | } 90 | internal func deleteItems(offsets: IndexSet) { 91 | let models = 92 | offsets 93 | .compactMap { items[$0].id } 94 | .map(Model.init(persistentIdentifier:)) 95 | 96 | assert(models.count == offsets.count) 97 | 98 | self.deleteItems(models) 99 | } 100 | 101 | internal func deleteItems(_ models: [Model]) { 102 | guard let database else { 103 | return 104 | } 105 | Task { 106 | try await Self.deleteModels(models, from: database) 107 | try await database.save() 108 | } 109 | } 110 | 111 | internal func addChild(to item: ItemViewModel) { 112 | guard let database else { 113 | return 114 | } 115 | Task { 116 | let timestamp = Date() 117 | let childModel = await database.insert { 118 | ItemChild(timestamp: timestamp) 119 | } 120 | 121 | try await database.withModelContext { modelContext in 122 | let item = try modelContext.get(item.model) 123 | let child = try modelContext.get(childModel) 124 | assert(child != nil && item != nil) 125 | child?.parent = item 126 | try modelContext.save() 127 | } 128 | } 129 | } 130 | 131 | internal func addItem(withDate date: Date = .init()) { 132 | guard let database else { 133 | return 134 | } 135 | Task { 136 | let insertedModel = await database.insert { Item(timestamp: date) } 137 | print("inserted:", insertedModel.isTemporary) 138 | try await database.save() 139 | let savedModel = try await database.get( 140 | for: .predicate( 141 | #Predicate { 142 | $0.timestamp == date 143 | } 144 | ) 145 | ) 146 | print("saved:", savedModel.isTemporary) 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /Example/Sources/ContentView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ContentView.swift 3 | // DataThespianExample 4 | // 5 | // Created by Leo Dion on 10/10/24. 6 | // 7 | 8 | import Combine 9 | import DataThespian 10 | import SwiftData 11 | import SwiftUI 12 | 13 | internal struct ContentView: View { 14 | @State private var object = ContentObject() 15 | @Environment(\.database) private var database 16 | @Environment(\.databaseChangePublicist) private var databaseChangePublisher 17 | 18 | internal var body: some View { 19 | NavigationSplitView { 20 | List(selection: self.$object.selectedItemsID) { 21 | ForEach(object.items) { item in 22 | Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard)) 23 | } 24 | .onDelete(perform: object.deleteItems) 25 | } 26 | .navigationSplitViewColumnWidth(min: 200, ideal: 220) 27 | .toolbar { 28 | ToolbarItem { 29 | Button(action: addItem) { 30 | Label("Add Item", systemImage: "plus") 31 | } 32 | } 33 | ToolbarItem { 34 | Button(action: object.deleteSelectedItems) { 35 | Label("Delete Selected Items", systemImage: "trash") 36 | } 37 | } 38 | } 39 | } detail: { 40 | let selectedItems = object.selectedItems 41 | if selectedItems.count > 1 { 42 | Text("Multiple Selected") 43 | } else if let item = selectedItems.first { 44 | ItemChildView(object: object, item: item) 45 | } else { 46 | Text("Select an item") 47 | } 48 | }.onAppear { 49 | self.object.initialize( 50 | withDatabase: database, 51 | databaseChangePublisher: databaseChangePublisher 52 | ) 53 | } 54 | } 55 | 56 | private func addItem() { 57 | self.addItem(withDate: .init()) 58 | } 59 | private func addItem(withDate date: Date) { 60 | self.object.addItem(withDate: .init()) 61 | } 62 | } 63 | 64 | #Preview { 65 | let databaseChangePublicist = DatabaseChangePublicist(dbWatcher: DataMonitor.shared) 66 | let config = ModelConfiguration(isStoredInMemoryOnly: true) 67 | 68 | // swift-format-ignore: NeverUseForceTry 69 | // swiftlint:disable:next force_try 70 | let modelContainer = try! ModelContainer(for: Item.self, configurations: config) 71 | 72 | let backgroundDatabase = BackgroundDatabase(modelContainer: modelContainer) { 73 | let context = ModelContext($0) 74 | context.autosaveEnabled = true 75 | return context 76 | } 77 | 78 | ContentView() 79 | .environment(\.databaseChangePublicist, databaseChangePublicist) 80 | .database(backgroundDatabase) 81 | } 82 | -------------------------------------------------------------------------------- /Example/Sources/DataThespianExample.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.files.user-selected.read-only 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Example/Sources/DataThespianExampleApp.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DataThespianExampleApp.swift 3 | // DataThespianExample 4 | // 5 | // Created by Leo Dion on 10/10/24. 6 | // 7 | 8 | import DataThespian 9 | import SwiftData 10 | import SwiftUI 11 | 12 | @main 13 | internal struct DataThespianExampleApp: App { 14 | private static let databaseChangePublicist = DatabaseChangePublicist() 15 | 16 | private static let database = BackgroundDatabase { 17 | // swift-format-ignore: NeverUseForceTry 18 | // swiftlint:disable:next force_try 19 | try! ModelActorDatabase(modelContainer: ModelContainer(for: Item.self)) { 20 | let context = ModelContext($0) 21 | context.autosaveEnabled = true 22 | return context 23 | } 24 | } 25 | 26 | internal var body: some Scene { 27 | WindowGroup { 28 | ContentView() 29 | } 30 | .database(Self.database) 31 | .environment(\.databaseChangePublicist, Self.databaseChangePublicist) 32 | } 33 | 34 | internal init() { 35 | DataMonitor.shared.begin(with: []) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Example/Sources/Item.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Item.swift 3 | // DataThespianExample 4 | // 5 | // Created by Leo Dion on 10/10/24. 6 | // 7 | 8 | import DataThespian 9 | import Foundation 10 | import SwiftData 11 | 12 | @Model 13 | internal final class Item: Unique { 14 | internal enum Keys: UniqueKeys { 15 | internal typealias Model = Item 16 | internal static let primary = timestamp 17 | internal static let timestamp = keyPath(\.timestamp) 18 | } 19 | 20 | internal private(set) var timestamp: Date 21 | internal private(set) var children: [ItemChild]? 22 | 23 | internal init(timestamp: Date) { 24 | self.timestamp = timestamp 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Example/Sources/ItemChild.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ItemChild.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion on 10/16/24. 6 | // 7 | import Foundation 8 | import SwiftData 9 | 10 | @Model 11 | internal final class ItemChild { 12 | internal var parent: Item? 13 | internal private(set) var timestamp: Date 14 | 15 | internal init(parent: Item? = nil, timestamp: Date) { 16 | self.parent = parent 17 | self.timestamp = timestamp 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Example/Sources/ItemChildView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ItemChildView.swift 3 | // DataThespianExample 4 | // 5 | // Created by Leo Dion on 10/16/24. 6 | // 7 | 8 | import SwiftUI 9 | 10 | internal struct ItemChildView: View { 11 | internal var object: ContentObject 12 | internal let item: ItemViewModel 13 | internal var body: some View { 14 | VStack { 15 | Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))") 16 | Divider() 17 | Button("Add Child") { 18 | object.addChild(to: item) 19 | } 20 | ForEach(item.children) { child in 21 | Text( 22 | "Child at \(child.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))" 23 | ) 24 | } 25 | } 26 | } 27 | } 28 | // 29 | // #Preview { 30 | // ItemChildView() 31 | // } 32 | -------------------------------------------------------------------------------- /Example/Sources/ItemViewModel.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ItemModel.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion on 10/10/24. 6 | // 7 | 8 | import DataThespian 9 | import Foundation 10 | import SwiftData 11 | 12 | internal struct ItemViewModel: Sendable, Identifiable { 13 | internal let model: Model 14 | internal let timestamp: Date 15 | internal let children: [ChildViewModel] 16 | 17 | internal var id: PersistentIdentifier { 18 | model.persistentIdentifier 19 | } 20 | 21 | private init(model: Model, timestamp: Date, children: [ChildViewModel]?) { 22 | self.model = model 23 | self.timestamp = timestamp 24 | self.children = children ?? [] 25 | } 26 | 27 | internal init(item: Item) { 28 | self.init( 29 | model: .init(item), 30 | timestamp: item.timestamp, 31 | children: item.children?.map(ChildViewModel.init) 32 | ) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Example/Sources/Preview Content/Preview Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Example/Support/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brightdigit/DataThespian/68039a49afcc9e7fb5c6b458a801f5f09ce4369a/Example/Support/.gitkeep -------------------------------------------------------------------------------- /Example/Support/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | $(MARKETING_VERSION) 19 | CFBundleVersion 20 | $(CURRENT_PROJECT_VERSION) 21 | ITSAppUsesNonExemptEncryption 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 BrightDigit 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Mintfile: -------------------------------------------------------------------------------- 1 | swiftlang/swift-format@600.0.0 2 | realm/SwiftLint@0.57.0 3 | a7ex/xcresultparser@1.7.2 4 | peripheryapp/periphery@2.20.0 -------------------------------------------------------------------------------- /Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "originHash" : "218abd6c7fefffa1c55b8836619484f00b1390a28b87c886220a143df08c3ed2", 3 | "pins" : [ 4 | { 5 | "identity" : "felinepine", 6 | "kind" : "remoteSourceControl", 7 | "location" : "https://github.com/brightdigit/FelinePine.git", 8 | "state" : { 9 | "revision" : "54c727e0b069ffda7f80db7af99bfab2518e0780", 10 | "version" : "1.0.0-beta.2" 11 | } 12 | }, 13 | { 14 | "identity" : "swift-docc-plugin", 15 | "kind" : "remoteSourceControl", 16 | "location" : "https://github.com/swiftlang/swift-docc-plugin", 17 | "state" : { 18 | "revision" : "85e4bb4e1cd62cec64a4b8e769dcefdf0c5b9d64", 19 | "version" : "1.4.3" 20 | } 21 | }, 22 | { 23 | "identity" : "swift-docc-symbolkit", 24 | "kind" : "remoteSourceControl", 25 | "location" : "https://github.com/swiftlang/swift-docc-symbolkit", 26 | "state" : { 27 | "revision" : "b45d1f2ed151d057b54504d653e0da5552844e34", 28 | "version" : "1.0.0" 29 | } 30 | }, 31 | { 32 | "identity" : "swift-log", 33 | "kind" : "remoteSourceControl", 34 | "location" : "https://github.com/apple/swift-log.git", 35 | "state" : { 36 | "revision" : "9cb486020ebf03bfa5b5df985387a14a98744537", 37 | "version" : "1.6.1" 38 | } 39 | } 40 | ], 41 | "version" : 3 42 | } 43 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 6.0 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | // swiftlint:disable explicit_acl explicit_top_level_acl 7 | let swiftSettings: [SwiftSetting] = [ 8 | SwiftSetting.enableExperimentalFeature("AccessLevelOnImport"), 9 | SwiftSetting.enableExperimentalFeature("BitwiseCopyable"), 10 | SwiftSetting.enableExperimentalFeature("GlobalActorIsolatedTypesUsability"), 11 | SwiftSetting.enableExperimentalFeature("IsolatedAny"), 12 | SwiftSetting.enableExperimentalFeature("MoveOnlyPartialConsumption"), 13 | SwiftSetting.enableExperimentalFeature("NestedProtocols"), 14 | SwiftSetting.enableExperimentalFeature("NoncopyableGenerics"), 15 | SwiftSetting.enableExperimentalFeature("RegionBasedIsolation"), 16 | SwiftSetting.enableExperimentalFeature("TransferringArgsAndResults"), 17 | SwiftSetting.enableExperimentalFeature("VariadicGenerics"), 18 | 19 | SwiftSetting.enableUpcomingFeature("FullTypedThrows"), 20 | SwiftSetting.enableUpcomingFeature("InternalImportsByDefault") 21 | ] 22 | 23 | let package = Package( 24 | name: "DataThespian", 25 | platforms: [.iOS(.v17), .macCatalyst(.v17), .macOS(.v14), .tvOS(.v17), .visionOS(.v1), .watchOS(.v10)], 26 | products: [ 27 | .library( 28 | name: "DataThespian", 29 | targets: ["DataThespian"] 30 | ) 31 | ], 32 | dependencies: [ 33 | .package(url: "https://github.com/brightdigit/FelinePine.git", from: "1.0.0-beta.2"), 34 | .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.4.0"), 35 | ], 36 | targets: [ 37 | .target( 38 | name: "DataThespian", 39 | dependencies: ["FelinePine"], 40 | swiftSettings: swiftSettings 41 | ), 42 | .testTarget( 43 | name: "DataThespianTests", 44 | dependencies: [ 45 | "DataThespian" 46 | ] 47 | ) 48 | ] 49 | ) 50 | // swiftlint:enable explicit_acl explicit_top_level_acl 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DataThespian 2 | 3 | [![](https://img.shields.io/badge/docc-read_documentation-blue)](https://swiftpackageindex.com/brightdigit/DataThespian/documentation) 4 | [![SwiftPM](https://img.shields.io/badge/SPM-Linux%20%7C%20iOS%20%7C%20macOS%20%7C%20watchOS%20%7C%20tvOS-success?logo=swift)](https://swift.org) 5 | [![Twitter](https://img.shields.io/badge/twitter-@brightdigit-blue.svg?style=flat)](http://twitter.com/brightdigit) 6 | ![GitHub](https://img.shields.io/github/license/brightdigit/DataThespian) 7 | ![GitHub issues](https://img.shields.io/github/issues/brightdigit/DataThespian) 8 | ![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/brightdigit/DataThespian/DataThespian.yml?label=actions&logo=github&?branch=main) 9 | 10 | [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fbrightdigit%2FDataThespian%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/brightdigit/DataThespian) 11 | [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fbrightdigit%2FDataThespian%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/brightdigit/DataThespian) 12 | 13 | [![Codecov](https://img.shields.io/codecov/c/github/brightdigit/DataThespian)](https://codecov.io/gh/brightdigit/DataThespian) 14 | [![CodeFactor Grade](https://img.shields.io/codefactor/grade/github/brightdigit/DataThespian)](https://www.codefactor.io/repository/github/brightdigit/DataThespian) 15 | [![codebeat badge](https://codebeat.co/badges/63949717-cda3-46c7-b1cb-60a0c2fe9c72)](https://codebeat.co/projects/github-com-brightdigit-DataThespian-main) 16 | [![Code Climate maintainability](https://img.shields.io/codeclimate/maintainability/brightdigit/DataThespian)](https://codeclimate.com/github/brightdigit/DataThespian) 17 | [![Code Climate technical debt](https://img.shields.io/codeclimate/tech-debt/brightdigit/DataThespian?label=debt)](https://codeclimate.com/github/brightdigit/DataThespian) 18 | [![Code Climate issues](https://img.shields.io/codeclimate/issues/brightdigit/DataThespian)](https://codeclimate.com/github/brightdigit/DataThespian) 19 | 20 | # Table of Contents 21 | 22 | * [Introduction](#introduction) 23 | * [Requirements](#requirements) 24 | * [Installation](#installation) 25 | * [Usage](#usage) 26 | * [Setting up Database](#setting-up-database) 27 | * [Making Queries](#making-queries) 28 | * [Documentation](#documentation) 29 | * [License](#license) 30 | 31 | # Introduction 32 | 33 | DataThespian is [a thread-safe SwiftData implementation that uses the power of ModelActors](https://brightdigit.com/tutorials/swiftdata-modelactor/) to provide an optimized and type-safe database interface. It offers a clean API for common database operations while maintaining concurrency safety and preventing common SwiftData pitfalls. 34 | 35 | Key features: 36 | - Thread-safe database operations using ModelActor 37 | - Type-safe query interface with Selectors 38 | - SwiftUI integration via Environment 39 | - Support for monitoring database changes 40 | - Collection synchronization utilities 41 | 42 | ## Requirements 43 | 44 | **Apple Platforms** 45 | 46 | - Xcode 16.0 or later 47 | - Swift 6.0 or later 48 | - iOS 17 / watchOS 10.0 / tvOS 17 / macOS 14 or later deployment targets 49 | 50 | **Linux** 51 | 52 | - Ubuntu 20.04 or later 53 | - Swift 6.0 or later 54 | 55 | ## Installation 56 | 57 | To integrate **DataThespian** into your app using SPM, specify it in your Package.swift file: 58 | 59 | ```swift 60 | let package = Package( 61 | ... 62 | dependencies: [ 63 | .package(url: "https://github.com/brightdigit/DataThespian.git", from: "1.0.0") 64 | ], 65 | targets: [ 66 | .target( 67 | name: "YourApps", 68 | dependencies: [ 69 | .product(name: "DataThespian", package: "DataThespian"), ... 70 | ]), 71 | ... 72 | ] 73 | ) 74 | ``` 75 | 76 | ## Usage 77 | 78 | ### Setting up Database 79 | 80 | When working with SwiftData, it's crucial to use a single `ModelContext` throughout your app. There are two ways to create your database: 81 | 82 | #### Using Built-in ModelActorDatabase 83 | 84 | ```swift 85 | // Create a database using the built-in ModelActorDatabase 86 | let database = ModelActorDatabase(modelContainer: container) 87 | ``` 88 | 89 | #### Creating Your Own Database Type 90 | 91 | You can also create your own database type by implementing the `Database` protocol: 92 | 93 | ```swift 94 | @ModelActor 95 | actor CustomDatabase: Database { 96 | } 97 | ``` 98 | 99 | #### Using SharedDatabase 100 | 101 | To avoid issues with multiple ModelContexts being created each time SwiftUI redraws views, use `SharedDatabase` to ensure a single shared context: 102 | 103 | ```swift 104 | public struct SharedDatabase { 105 | public static let shared: SharedDatabase = .init() 106 | 107 | public let schemas: [any PersistentModel.Type] 108 | public let modelContainer: ModelContainer 109 | public let database: any Database 110 | 111 | private init( 112 | schemas: [any PersistentModel.Type], 113 | modelContainer: ModelContainer? = nil, 114 | database: (any Database)? = nil 115 | ) { 116 | self.schemas = schemas 117 | // add cde to handle schema failure 118 | let modelContainer = try! modelContainer ?? ModelContainer(for: Schema(forTypes)) 119 | self.modelContainer = modelContainer 120 | self.database = database ?? ModelActorDatabase(modelContainer: modelContainer) 121 | } 122 | } 123 | ``` 124 | 125 | Then set up the database in your SwiftUI app: 126 | 127 | ```swift 128 | var body: some Scene { 129 | WindowGroup { 130 | RootView() 131 | } 132 | .database(SharedDatabase.shared.database) 133 | /* If you need @Query support 134 | .modelContainer(SharedDatabase.shared.modelContainer) 135 | */ 136 | } 137 | ``` 138 | 139 | Access the database in your views using the environment: 140 | 141 | ```swift 142 | @Environment(\.database) private var database 143 | ``` 144 | 145 | ### Making Queries 146 | 147 | DataThespian provides [a type-safe way to query your data](https://brightdigit.com/tutorials/swiftdata-crud-operations-modelactor/): 148 | 149 | ```swift 150 | // Fetch a single item 151 | let item = try await database.get(for: .predicate(#Predicate { 152 | $0.name == "Test" 153 | })) 154 | 155 | // Fetch multiple items with sorting 156 | let items = await database.fetch(for: .descriptor( 157 | predicate: #Predicate { $0.isActive }, 158 | sortBy: [SortDescriptor(\Item.timestamp, order: .reverse)] 159 | )) 160 | 161 | // Insert new item 162 | let timestamp = Date() 163 | let newItem = await database.insert { 164 | Item(name: "Test", timestamp: timestamp) 165 | } 166 | 167 | // Save changes 168 | try await database.save() 169 | 170 | // Re-query after save using a unique field 171 | let savedItem = try await database.getOptional(for: .predicate(#Predicate { 172 | $0.timestamp == timestamp 173 | })) 174 | ``` 175 | 255 | 256 | ## Documentation 257 | 258 | To learn more, check out the full [documentation](https://swiftpackageindex.com/brightdigit/DataThespian/documentation). 259 | 260 | # License 261 | 262 | This code is distributed under the MIT license. See the [LICENSE](https://github.com/brightdigit/DataThespian/LICENSE) file for more info. 263 | -------------------------------------------------------------------------------- /Scripts/header.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Function to print usage 4 | usage() { 5 | echo "Usage: $0 -d directory -c creator -o company -p package [-y year]" 6 | echo " -d directory Directory to read from (including subdirectories)" 7 | echo " -c creator Name of the creator" 8 | echo " -o company Name of the company with the copyright" 9 | echo " -p package Package or library name" 10 | echo " -y year Copyright year (optional, defaults to current year)" 11 | exit 1 12 | } 13 | 14 | # Get the current year if not provided 15 | current_year=$(date +"%Y") 16 | 17 | # Default values 18 | year="$current_year" 19 | 20 | # Parse arguments 21 | while getopts ":d:c:o:p:y:" opt; do 22 | case $opt in 23 | d) directory="$OPTARG" ;; 24 | c) creator="$OPTARG" ;; 25 | o) company="$OPTARG" ;; 26 | p) package="$OPTARG" ;; 27 | y) year="$OPTARG" ;; 28 | *) usage ;; 29 | esac 30 | done 31 | 32 | # Check for mandatory arguments 33 | if [ -z "$directory" ] || [ -z "$creator" ] || [ -z "$company" ] || [ -z "$package" ]; then 34 | usage 35 | fi 36 | 37 | # Define the header template 38 | header_template="// 39 | // %s 40 | // %s 41 | // 42 | // Created by %s. 43 | // Copyright © %s %s. 44 | // 45 | // Permission is hereby granted, free of charge, to any person 46 | // obtaining a copy of this software and associated documentation 47 | // files (the “Software”), to deal in the Software without 48 | // restriction, including without limitation the rights to use, 49 | // copy, modify, merge, publish, distribute, sublicense, and/or 50 | // sell copies of the Software, and to permit persons to whom the 51 | // Software is furnished to do so, subject to the following 52 | // conditions: 53 | // 54 | // The above copyright notice and this permission notice shall be 55 | // included in all copies or substantial portions of the Software. 56 | // 57 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 58 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 59 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 60 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 61 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 62 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 63 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 64 | // OTHER DEALINGS IN THE SOFTWARE. 65 | //" 66 | 67 | # Loop through each Swift file in the specified directory and subdirectories 68 | find "$directory" -type f -name "*.swift" | while read -r file; do 69 | # Check if the first line is the swift-format-ignore indicator 70 | first_line=$(head -n 1 "$file") 71 | if [[ "$first_line" == "// swift-format-ignore-file" ]]; then 72 | echo "Skipping $file due to swift-format-ignore directive." 73 | continue 74 | fi 75 | 76 | # Create the header with the current filename 77 | filename=$(basename "$file") 78 | header=$(printf "$header_template" "$filename" "$package" "$creator" "$year" "$company") 79 | 80 | # Remove all consecutive lines at the beginning which start with "// ", contain only whitespace, or only "//" 81 | awk ' 82 | BEGIN { skip = 1 } 83 | { 84 | if (skip && ($0 ~ /^\/\/ / || $0 ~ /^\/\/$/ || $0 ~ /^$/)) { 85 | next 86 | } 87 | skip = 0 88 | print 89 | }' "$file" > temp_file 90 | 91 | # Add the header to the cleaned file 92 | (echo "$header"; echo; cat temp_file) > "$file" 93 | 94 | # Remove the temporary file 95 | rm temp_file 96 | done 97 | 98 | echo "Headers added or files skipped appropriately across all Swift files in the directory and subdirectories." -------------------------------------------------------------------------------- /Scripts/lint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -o pipefail 4 | 5 | ERRORS=0 6 | 7 | run_command() { 8 | if [ "$LINT_MODE" == "STRICT" ]; then 9 | "$@" || ERRORS=$((ERRORS + 1)) 10 | else 11 | "$@" 12 | fi 13 | } 14 | 15 | if [ "$ACTION" == "install" ]; then 16 | if [ -n "$SRCROOT" ]; then 17 | exit 18 | fi 19 | fi 20 | 21 | export MINT_PATH="$PWD/.mint" 22 | MINT_ARGS="-n -m Mintfile --silent" 23 | MINT_RUN="/opt/homebrew/bin/mint run $MINT_ARGS" 24 | 25 | if [ -z "$SRCROOT" ] || [ -n "$CHILD_PACKAGE" ]; then 26 | SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) 27 | PACKAGE_DIR="${SCRIPT_DIR}/.." 28 | PERIPHERY_OPTIONS="" 29 | else 30 | PACKAGE_DIR="${SRCROOT}" 31 | PERIPHERY_OPTIONS="" 32 | fi 33 | 34 | 35 | if [ "$LINT_MODE" == "NONE" ]; then 36 | exit 37 | elif [ "$LINT_MODE" == "STRICT" ]; then 38 | SWIFTFORMAT_OPTIONS="--strict" 39 | SWIFTLINT_OPTIONS="--strict" 40 | else 41 | SWIFTFORMAT_OPTIONS="" 42 | SWIFTLINT_OPTIONS="" 43 | fi 44 | 45 | /opt/homebrew/bin/mint bootstrap 46 | 47 | echo "LINT Mode is $LINT_MODE" 48 | 49 | if [ "$LINT_MODE" == "INSTALL" ]; then 50 | exit 51 | fi 52 | 53 | if [ -z "$CI" ]; then 54 | run_command $MINT_RUN swiftlint --fix 55 | pushd $PACKAGE_DIR 56 | run_command $MINT_RUN swift-format format --configuration .swift-format --recursive --parallel --in-place Sources Tests Example/Sources 57 | popd 58 | else 59 | set -e 60 | fi 61 | 62 | $PACKAGE_DIR/scripts/header.sh -d $PACKAGE_DIR/Sources -c "Leo Dion" -o "BrightDigit" -p "DataThespian" 63 | run_command $MINT_RUN swiftlint lint $SWIFTLINT_OPTIONS 64 | 65 | pushd $PACKAGE_DIR 66 | run_command $MINT_RUN swift-format lint --recursive --parallel --configuration .swift-format $SWIFTFORMAT_OPTIONS Sources Tests Example/Sources 67 | #run_command $MINT_RUN periphery scan $PERIPHERY_OPTIONS --disable-update-check 68 | popd -------------------------------------------------------------------------------- /Scripts/swift-doc.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Check if ANTHROPIC_API_KEY is set 4 | if [ -z "$ANTHROPIC_API_KEY" ]; then 5 | echo "Error: ANTHROPIC_API_KEY environment variable is not set" 6 | echo "Please set it with: export ANTHROPIC_API_KEY='your-key-here'" 7 | exit 1 8 | fi 9 | 10 | # Check if jq is installed 11 | if ! command -v jq &> /dev/null; then 12 | echo "Error: jq is required but not installed." 13 | echo "Please install it:" 14 | echo " - On macOS: brew install jq" 15 | echo " - On Ubuntu/Debian: sudo apt-get install jq" 16 | echo " - On CentOS/RHEL: sudo yum install jq" 17 | exit 1 18 | fi 19 | 20 | # Check if an argument was provided 21 | if [ $# -eq 0 ]; then 22 | echo "Usage: $0 [--skip-backup]" 23 | exit 1 24 | fi 25 | 26 | TARGET=$1 27 | SKIP_BACKUP=0 28 | 29 | # Check for optional flags 30 | if [ "$2" = "--skip-backup" ]; then 31 | SKIP_BACKUP=1 32 | fi 33 | 34 | # Function to clean markdown code blocks 35 | clean_markdown() { 36 | local content="$1" 37 | # Remove ```swift from the start and ``` from the end, if present 38 | content=$(echo "$content" | sed -E '1s/^```swift[[:space:]]*//') 39 | content=$(echo "$content" | sed -E '$s/```[[:space:]]*$//') 40 | echo "$content" 41 | } 42 | 43 | # Function to process a single Swift file 44 | process_swift_file() { 45 | local SWIFT_FILE=$1 46 | echo "Processing: $SWIFT_FILE" 47 | 48 | # Create backup unless skipped 49 | if [ $SKIP_BACKUP -eq 0 ]; then 50 | cp "$SWIFT_FILE" "${SWIFT_FILE}.backup" 51 | echo "Created backup: ${SWIFT_FILE}.backup" 52 | fi 53 | 54 | # Read and escape the Swift file content for JSON 55 | local SWIFT_CODE 56 | SWIFT_CODE=$(jq -Rs . < "$SWIFT_FILE") 57 | 58 | # Create the JSON payload 59 | local JSON_PAYLOAD 60 | JSON_PAYLOAD=$(jq -n \ 61 | --arg code "$SWIFT_CODE" \ 62 | '{ 63 | model: "claude-3-haiku-20240307", 64 | max_tokens: 2000, 65 | messages: [{ 66 | role: "user", 67 | content: "Please add Swift documentation comments to the following code. Use /// style comments. Include parameter descriptions and return value documentation where applicable. Return only the documented code without any markdown formatting or explanation:\n\n\($code)" 68 | }] 69 | }') 70 | 71 | # Make the API call to Claude 72 | local response 73 | response=$(curl -s https://api.anthropic.com/v1/messages \ 74 | -H "Content-Type: application/json" \ 75 | -H "x-api-key: $ANTHROPIC_API_KEY" \ 76 | -H "anthropic-version: 2023-06-01" \ 77 | -d "$JSON_PAYLOAD") 78 | 79 | # Check if the API call was successful 80 | if [ $? -ne 0 ]; then 81 | echo "Error: API call failed for $SWIFT_FILE" 82 | return 1 83 | fi 84 | 85 | # Extract the content from the response using jq 86 | local documented_code 87 | documented_code=$(echo "$response" | jq -r '.content[0].text // empty') 88 | 89 | # Check if we got valid content back 90 | if [ -z "$documented_code" ]; then 91 | echo "Error: No valid response received for $SWIFT_FILE" 92 | echo "API Response: $response" 93 | return 1 94 | fi 95 | 96 | # Clean the markdown formatting from the response 97 | documented_code=$(clean_markdown "$documented_code") 98 | 99 | # Save the documented code to the file 100 | echo "$documented_code" > "$SWIFT_FILE" 101 | 102 | # Show diff if available and backup exists 103 | if [ $SKIP_BACKUP -eq 0 ] && command -v diff &> /dev/null; then 104 | echo -e "\nChanges made to $SWIFT_FILE:" 105 | diff "${SWIFT_FILE}.backup" "$SWIFT_FILE" 106 | fi 107 | 108 | echo "✓ Documentation added to $SWIFT_FILE" 109 | echo "----------------------------------------" 110 | } 111 | 112 | # Function to process directory 113 | process_directory() { 114 | local DIR=$1 115 | local SWIFT_FILES=0 116 | local PROCESSED=0 117 | local FAILED=0 118 | 119 | # Count total Swift files 120 | SWIFT_FILES=$(find "$DIR" -name "*.swift" | wc -l) 121 | echo "Found $SWIFT_FILES Swift files in $DIR" 122 | echo "----------------------------------------" 123 | 124 | # Process each Swift file 125 | while IFS= read -r file; do 126 | if process_swift_file "$file"; then 127 | ((PROCESSED++)) 128 | else 129 | ((FAILED++)) 130 | fi 131 | # Add a small delay to avoid API rate limits 132 | sleep 1 133 | done < <(find "$DIR" -name "*.swift") 134 | 135 | echo "Summary:" 136 | echo "- Total Swift files found: $SWIFT_FILES" 137 | echo "- Successfully processed: $PROCESSED" 138 | echo "- Failed: $FAILED" 139 | } 140 | 141 | # Main logic 142 | if [ -f "$TARGET" ]; then 143 | # Single file processing 144 | if [[ "$TARGET" == *.swift ]]; then 145 | process_swift_file "$TARGET" 146 | else 147 | echo "Error: File must have .swift extension" 148 | exit 1 149 | fi 150 | elif [ -d "$TARGET" ]; then 151 | # Directory processing 152 | process_directory "$TARGET" 153 | else 154 | echo "Error: $TARGET is neither a valid file nor directory" 155 | exit 1 156 | fi -------------------------------------------------------------------------------- /Sources/DataThespian/Assert.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Assert.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | public import Foundation 31 | 32 | /// Asserts that the current thread is the main thread if the `assertIsBackground` parameter is `true`. 33 | /// 34 | /// - Parameters: 35 | /// - isMainThread: A boolean indicating whether the current thread should be the main thread. 36 | /// - assertIsBackground: A boolean indicating whether the assertion should be made. 37 | @inlinable internal func assert(isMainThread: Bool, if assertIsBackground: Bool) { 38 | assert(!assertIsBackground || isMainThread == Thread.isMainThread) 39 | } 40 | 41 | /// Asserts that the current thread is the main thread. 42 | /// 43 | /// - Parameter isMainThread: A boolean indicating whether the current thread should be the main thread. 44 | @inlinable internal func assert(isMainThread: Bool) { 45 | assert(isMainThread == Thread.isMainThread) 46 | } 47 | 48 | /// Asserts that an error has occurred, logging the localized description of the error. 49 | /// 50 | /// - Parameters: 51 | /// - error: The error that has occurred. 52 | /// - file: The file in which the assertion occurred (default is the current file). 53 | /// - line: The line in the file at which the assertion occurred (default is the current line). 54 | @inlinable internal func assertionFailure( 55 | error: any Error, file: StaticString = #file, line: UInt = #line 56 | ) { 57 | assertionFailure(error.localizedDescription, file: file, line: line) 58 | } 59 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/BackgroundDatabase.swift: -------------------------------------------------------------------------------- 1 | // 2 | // BackgroundDatabase.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | import Foundation 32 | public import SwiftData 33 | 34 | /// Represents a background database that can be used in a concurrent environment. 35 | public final class BackgroundDatabase: Database { 36 | private actor DatabaseContainer { 37 | private let factory: @Sendable () -> any Database 38 | private var wrappedTask: Task? 39 | 40 | /// Initializes a `DatabaseContainer` with the given factory. 41 | /// - Parameter factory: A closure that creates a new database instance. 42 | fileprivate init(factory: @escaping @Sendable () -> any Database) { 43 | self.factory = factory 44 | } 45 | 46 | /// Provides access to the database instance, creating it lazily if necessary. 47 | fileprivate var database: any Database { 48 | get async { 49 | if let wrappedTask { 50 | return await wrappedTask.value 51 | } 52 | let task = Task { factory() } 53 | self.wrappedTask = task 54 | return await task.value 55 | } 56 | } 57 | } 58 | 59 | private let container: DatabaseContainer 60 | 61 | /// The database instance, accessed asynchronously. 62 | private var database: any Database { 63 | get async { 64 | await container.database 65 | } 66 | } 67 | 68 | /// Initializes a `BackgroundDatabase` with the given database. 69 | /// - Parameter database: a new database instance. 70 | public convenience init(database: @Sendable @escaping @autoclosure () -> any Database) { 71 | self.init(database) 72 | } 73 | 74 | /// Initializes a `BackgroundDatabase` with the given database factory. 75 | /// - Parameter factory: A closure that creates a new database instance. 76 | public init(_ factory: @Sendable @escaping () -> any Database) { 77 | self.container = .init(factory: factory) 78 | } 79 | 80 | /// Executes the given closure within the context of the database's model context. 81 | /// - Parameter closure: A closure that performs operations within the model context. 82 | /// - Returns: The result of the closure. 83 | public func withModelContext(_ closure: @Sendable @escaping (ModelContext) throws -> T) 84 | async rethrows -> T 85 | { 86 | try await self.database.withModelContext(closure) 87 | } 88 | } 89 | 90 | extension BackgroundDatabase { 91 | /// Initializes a `BackgroundDatabase` with the given model container and 92 | /// optional model context closure. 93 | /// - Parameters: 94 | /// - modelContainer: The model container to use. 95 | /// - closure: An optional closure that creates a model context 96 | /// from the provided model container. 97 | public convenience init( 98 | modelContainer: ModelContainer, 99 | modelContext closure: (@Sendable (ModelContainer) -> ModelContext)? = nil 100 | ) { 101 | let closure = closure ?? ModelContext.init 102 | self.init(database: ModelActorDatabase(modelContainer: modelContainer, modelContext: closure)) 103 | } 104 | 105 | /// Initializes a `BackgroundDatabase` with the given model container and the default model context. 106 | /// - Parameter modelContainer: The model container to use. 107 | public convenience init( 108 | modelContainer: SwiftData.ModelContainer 109 | ) { 110 | self.init( 111 | modelContainer: modelContainer, 112 | modelContext: ModelContext.init 113 | ) 114 | } 115 | 116 | /// Initializes a `BackgroundDatabase` with the given model container and model executor closure. 117 | /// - Parameters: 118 | /// - modelContainer: The model container to use. 119 | /// - closure: A closure that creates a model executor from the provided model container. 120 | public convenience init( 121 | modelContainer: SwiftData.ModelContainer, 122 | modelExecutor closure: @Sendable @escaping (ModelContainer) -> any ModelExecutor 123 | ) { 124 | self.init( 125 | database: ModelActorDatabase( 126 | modelContainer: modelContainer, 127 | modelExecutor: closure 128 | ) 129 | ) 130 | } 131 | } 132 | #endif 133 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/Database+Extras.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Database+Extras.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | import Foundation 32 | public import SwiftData 33 | 34 | extension Database { 35 | /// Executes a database transaction asynchronously. 36 | /// 37 | /// - Parameter block: A closure that performs database operations within the transaction. 38 | /// - Throws: Any errors that occur during the transaction. 39 | public func transaction(_ block: @Sendable @escaping (ModelContext) throws -> Void) async throws 40 | { 41 | try await self.withModelContext { context in 42 | try context.transaction { 43 | try block(context) 44 | } 45 | } 46 | } 47 | 48 | /// Deletes all models of the specified types from the database asynchronously. 49 | /// 50 | /// - Parameter types: An array of `PersistentModel.Type` instances 51 | /// representing the model types to delete. 52 | /// - Throws: Any errors that occur during the deletion process. 53 | public func deleteAll(of types: [any PersistentModel.Type]) async throws { 54 | try await self.transaction { context in 55 | for type in types { 56 | try context.delete(model: type) 57 | } 58 | } 59 | } 60 | } 61 | #endif 62 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/Database+Queryable.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Database+Queryable.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import SwiftData 32 | 33 | extension Database { 34 | /// Saves the current state of the database. 35 | /// - Throws: Any errors that occur during the save operation. 36 | public func save() async throws { 37 | try await self.withModelContext { try $0.save() } 38 | } 39 | 40 | /// Inserts a new persistent model into the database. 41 | /// - Parameters: 42 | /// - closuer: A closure that creates a new instance of the persistent model. 43 | /// - closure: A closure that performs additional operations on the inserted model. 44 | /// - Returns: The result of the `closure` parameter. 45 | public func insert( 46 | _ closuer: @Sendable @escaping () -> PersistentModelType, 47 | with closure: @escaping @Sendable (PersistentModelType) throws -> U 48 | ) async rethrows -> U { 49 | try await self.withModelContext { 50 | try $0.insert(closuer, with: closure) 51 | } 52 | } 53 | 54 | /// Retrieves an optional persistent model from the database. 55 | /// - Parameters: 56 | /// - selector: A selector that specifies the model to retrieve. 57 | /// - closure: A closure that performs additional operations on the retrieved model. 58 | /// - Returns: The result of the `closure` parameter. 59 | public func getOptional( 60 | for selector: Selector.Get, 61 | with closure: @escaping @Sendable (PersistentModelType?) throws -> U 62 | ) async rethrows -> U { 63 | try await self.withModelContext { 64 | try $0.getOptional(for: selector, with: closure) 65 | } 66 | } 67 | 68 | /// Retrieves a list of persistent models from the database. 69 | /// - Parameters: 70 | /// - selector: A selector that specifies the models to retrieve. 71 | /// - closure: A closure that performs additional operations on the retrieved models. 72 | /// - Returns: The result of the `closure` parameter. 73 | public func fetch( 74 | for selector: Selector.List, 75 | with closure: @escaping @Sendable ([PersistentModelType]) throws -> U 76 | ) async rethrows -> U { 77 | try await self.withModelContext { 78 | try $0.fetch(for: selector, with: closure) 79 | } 80 | } 81 | 82 | /// Deletes a persistent model from the database. 83 | /// - Parameter selector: A selector that specifies the model to delete. 84 | /// - Throws: Any errors that occur during the delete operation. 85 | public func delete(_ selector: Selector.Delete) 86 | async throws 87 | { 88 | try await self.withModelContext { 89 | try $0.delete(selector) 90 | } 91 | } 92 | } 93 | #endif 94 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/Database.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Database.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | 32 | import Foundation 33 | public import SwiftData 34 | 35 | /// `Sendable` protocol for querying a `ModelContext`. 36 | public protocol Database: Sendable, Queryable { 37 | /// Executes a closure safely within the context of a model. 38 | /// 39 | /// - Parameter closure: A closure that takes a `ModelContext` 40 | /// and returns a `Sendable` value of type `T`. 41 | /// - Returns: The value returned by the closure. 42 | func withModelContext(_ closure: @Sendable @escaping (ModelContext) throws -> T) 43 | async rethrows -> T 44 | } 45 | #endif 46 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/EnvironmentValues+Database.swift: -------------------------------------------------------------------------------- 1 | // 2 | // EnvironmentValues+Database.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftUI) && canImport(SwiftData) 31 | import Foundation 32 | import SwiftData 33 | public import SwiftUI 34 | /// Provides a default implementation of the `Database` protocol 35 | /// for use in environments where no other database has been set. 36 | private struct DefaultDatabase: Database { 37 | /// The singleton instance of the `DefaultDatabase`. 38 | static let instance = DefaultDatabase() 39 | 40 | // swiftlint:disable unavailable_function 41 | 42 | /// Executes the provided closure within the context of the default model context, 43 | /// asserting and throwing an error if no database has been set. 44 | /// 45 | /// - Parameter closure: A closure that takes a `ModelContext` and returns a value of type `T`. 46 | /// - Returns: The value returned by the provided closure. 47 | func withModelContext(_ closure: (ModelContext) throws -> T) async rethrows -> T { 48 | assertionFailure("No Database Set.") 49 | fatalError("No Database Set.") 50 | } 51 | // swiftlint:enable unavailable_function 52 | } 53 | 54 | extension EnvironmentValues { 55 | /// The database to be used within the current environment. 56 | @Entry public var database: any Database = DefaultDatabase.instance 57 | } 58 | 59 | extension Scene { 60 | /// Sets the database to be used within the current scene. 61 | /// 62 | /// - Parameter database: The database to be used. 63 | /// - Returns: A modified `Scene` with the provided database. 64 | public func database(_ database: any Database) -> some Scene { 65 | environment(\.database, database) 66 | } 67 | } 68 | 69 | extension View { 70 | /// Sets the database to be used within the current view. 71 | /// 72 | /// - Parameter database: The database to be used. 73 | /// - Returns: A modified `View` with the provided database. 74 | public func database(_ database: any Database) -> some View { 75 | environment(\.database, database) 76 | } 77 | } 78 | #endif 79 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/ModelActor+Database.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ModelActor+Database.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import SwiftData 32 | 33 | extension ModelActor where Self: Database { 34 | /// A Boolean value indicating whether the current thread is the background thread. 35 | public static var assertIsBackground: Bool { false } 36 | 37 | /// Executes a closure within the context of the model. 38 | /// 39 | /// - Parameter closure: The closure to execute within the model context. 40 | /// - Returns: The result of the closure execution. 41 | public func withModelContext( 42 | _ closure: @Sendable @escaping (ModelContext) throws -> T 43 | ) async rethrows -> T { 44 | assert(isMainThread: true, if: Self.assertIsBackground) 45 | let modelContext = self.modelContext 46 | return try closure(modelContext) 47 | } 48 | } 49 | #endif 50 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/ModelActorDatabase.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ModelActorDatabase.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import SwiftData 32 | 33 | /// Simplied and customizable `ModelActor` ``Database``. 34 | public actor ModelActorDatabase: Database, ModelActor { 35 | /// The model executor used by this database. 36 | public nonisolated let modelExecutor: any SwiftData.ModelExecutor 37 | /// The model container used by this database. 38 | public nonisolated let modelContainer: SwiftData.ModelContainer 39 | 40 | /// Initializes a new `ModelActorDatabase` with the given `modelContainer`. 41 | /// - Parameter modelContainer: The model container to use for this database. 42 | public init(modelContainer: SwiftData.ModelContainer) { 43 | self.init( 44 | modelContainer: modelContainer, 45 | modelContext: ModelContext.init 46 | ) 47 | } 48 | 49 | /// Initializes a new `ModelActorDatabase` with 50 | /// the given `modelContainer` and a custom `modelContext` closure. 51 | /// - Parameters: 52 | /// - modelContainer: The model container to use for this database. 53 | /// - closure: A closure that creates a 54 | /// custom `ModelContext` from the `ModelContainer`. 55 | public init( 56 | modelContainer: SwiftData.ModelContainer, 57 | modelContext closure: @Sendable @escaping (ModelContainer) -> ModelContext 58 | ) { 59 | self.init( 60 | modelContainer: modelContainer, 61 | modelExecutor: DefaultSerialModelExecutor.create(from: closure) 62 | ) 63 | } 64 | 65 | /// Initializes a new `ModelActorDatabase` with 66 | /// the given `modelContainer` and a custom `modelExecutor` closure. 67 | /// - Parameters: 68 | /// - modelContainer: The model container to use for this database. 69 | /// - closure: A closure that creates 70 | /// a custom `ModelExecutor` from the `ModelContainer`. 71 | public init( 72 | modelContainer: SwiftData.ModelContainer, 73 | modelExecutor closure: @Sendable @escaping (ModelContainer) -> any ModelExecutor 74 | ) { 75 | self.init( 76 | modelExecutor: closure(modelContainer), 77 | modelContainer: modelContainer 78 | ) 79 | } 80 | 81 | private init(modelExecutor: any ModelExecutor, modelContainer: ModelContainer) { 82 | self.modelExecutor = modelExecutor 83 | self.modelContainer = modelContainer 84 | } 85 | } 86 | 87 | extension DefaultSerialModelExecutor { 88 | fileprivate static func create( 89 | from closure: @Sendable @escaping (ModelContainer) -> ModelContext 90 | ) -> @Sendable (ModelContainer) -> any ModelExecutor { 91 | { 92 | DefaultSerialModelExecutor(modelContext: closure($0)) 93 | } 94 | } 95 | } 96 | #endif 97 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/QueryError.swift: -------------------------------------------------------------------------------- 1 | // 2 | // QueryError.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import SwiftData 32 | /// An error that occurs when a query fails to find an item. 33 | public enum QueryError: Error { 34 | /// Indicates that the item was not found. 35 | /// 36 | /// - Parameter selector: The `Selector.Get` instance that was used to perform the query. 37 | case itemNotFound(Selector.Get) 38 | } 39 | #endif 40 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/Queryable+Extensions.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Queryable+Extensions.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import SwiftData 32 | 33 | extension Queryable { 34 | /// Inserts a new persistent model into the database 35 | /// - Parameter closure: A closure that creates and returns a new persistent model 36 | /// - Returns: A wrapped Model instance containing the inserted persistent model 37 | @discardableResult 38 | public func insert( 39 | _ closure: @Sendable @escaping () -> PersistentModelType 40 | ) async -> Model { 41 | await self.insert(closure, with: Model.init) 42 | } 43 | 44 | /// Retrieves an optional model matching the given selector 45 | /// - Parameter selector: A selector defining the query criteria for retrieving the model 46 | /// - Returns: An optional wrapped Model instance if found, nil otherwise 47 | public func getOptional( 48 | for selector: Selector.Get 49 | ) async -> Model? { 50 | await self.getOptional(for: selector) { persistentModel in 51 | persistentModel.flatMap(Model.init) 52 | } 53 | } 54 | 55 | /// Fetches an array of models matching the given list selector 56 | /// - Parameter selector: A selector defining the query criteria for retrieving multiple models 57 | /// - Returns: An array of wrapped Model instances matching the selector criteria 58 | public func fetch( 59 | for selector: Selector.List 60 | ) async -> [Model] { 61 | await self.fetch(for: selector) { persistentModels in 62 | persistentModels.map(Model.init) 63 | } 64 | } 65 | 66 | /// Fetches and transforms multiple models using an array of selectors 67 | /// - Parameters: 68 | /// - selectors: An array of selectors to fetch models 69 | /// - closure: A transformation closure to apply to each fetched model 70 | /// - Returns: An array of transformed results 71 | public func fetch( 72 | for selectors: [Selector.Get], 73 | with closure: @escaping @Sendable (PersistentModelType) throws -> U 74 | ) async rethrows -> [U] { 75 | try await withThrowingTaskGroup( 76 | of: Optional.self, 77 | returning: [U].self, 78 | body: { group in 79 | for selector in selectors { 80 | group.addTask { 81 | try await self.getOptional(for: selector) { persistentModel in 82 | guard let persistentModel else { 83 | return Optional.none 84 | } 85 | return try closure(persistentModel) 86 | } 87 | } 88 | } 89 | return try await group.reduce(into: [U]()) { partialResult, result in 90 | if let result { 91 | partialResult.append(result) 92 | } 93 | } 94 | } 95 | ) 96 | } 97 | 98 | /// Retrieves a required model matching the given selector 99 | /// - Parameter selector: A selector defining the query criteria 100 | /// - Returns: A wrapped Model instance 101 | /// - Throws: QueryError.itemNotFound if the model doesn't exist 102 | public func get( 103 | for selector: Selector.Get 104 | ) async throws -> Model { 105 | try await self.getOptional(for: selector) { persistentModel in 106 | guard let persistentModel else { 107 | throw QueryError.itemNotFound(selector) 108 | } 109 | return Model(persistentModel) 110 | } 111 | } 112 | 113 | /// Retrieves and transforms a required model matching the given selector 114 | /// - Parameters: 115 | /// - selector: A selector defining the query criteria 116 | /// - closure: A transformation closure to apply to the fetched model 117 | /// - Returns: The transformed result 118 | /// - Throws: QueryError.itemNotFound if the model doesn't exist 119 | public func get( 120 | for selector: Selector.Get, 121 | with closure: @escaping @Sendable (PersistentModelType) throws -> U 122 | ) async throws -> U { 123 | try await self.getOptional(for: selector) { persistentModel in 124 | guard let persistentModel else { 125 | throw QueryError.itemNotFound(selector) 126 | } 127 | return try closure(persistentModel) 128 | } 129 | } 130 | 131 | /// Updates a single model matching the given selector 132 | /// - Parameters: 133 | /// - selector: A selector defining the model to update 134 | /// - closure: A closure that performs the update operation 135 | /// - Throws: QueryError.itemNotFound if the model doesn't exist 136 | public func update( 137 | for selector: Selector.Get, 138 | with closure: @escaping @Sendable (PersistentModelType) throws -> Void 139 | ) async throws { 140 | try await self.get(for: selector, with: closure) 141 | } 142 | 143 | /// Updates multiple models matching the given list selector 144 | /// - Parameters: 145 | /// - selector: A selector defining the models to update 146 | /// - closure: A closure that performs the update operation on the array of models 147 | /// - Throws: Rethrows any errors from the update closure 148 | public func update( 149 | for selector: Selector.List, 150 | with closure: @escaping @Sendable ([PersistentModelType]) throws -> Void 151 | ) async throws { 152 | try await self.fetch(for: selector, with: closure) 153 | } 154 | 155 | /// Inserts a model if it doesn't already exist based on a selector 156 | /// - Parameters: 157 | /// - model: A closure that creates the model to insert 158 | /// - selector: A closure that creates a selector from the model to check existence 159 | /// - Returns: Either the existing model or the newly inserted model 160 | public func insertIf( 161 | _ model: @Sendable @escaping () -> PersistentModelType, 162 | notExist selector: @Sendable @escaping (PersistentModelType) -> 163 | Selector.Get 164 | ) async -> Model { 165 | let persistentModel = model() 166 | let selector = selector(persistentModel) 167 | let modelOptional = await self.getOptional(for: selector) 168 | 169 | if let modelOptional { 170 | return modelOptional 171 | } else { 172 | return await self.insert(model) 173 | } 174 | } 175 | 176 | /// Inserts a model if it doesn't exist and transforms it 177 | /// - Parameters: 178 | /// - model: A closure that creates the model to insert 179 | /// - selector: A closure that creates a selector from the model to check existence 180 | /// - closure: A transformation closure to apply to the resulting model 181 | /// - Returns: The transformed result 182 | /// - Throws: Rethrows any errors from the transformation closure 183 | public func insertIf( 184 | _ model: @Sendable @escaping () -> PersistentModelType, 185 | notExist selector: @Sendable @escaping (PersistentModelType) -> 186 | Selector.Get, 187 | with closure: @escaping @Sendable (PersistentModelType) throws -> U 188 | ) async throws -> U { 189 | let model = await self.insertIf(model, notExist: selector) 190 | return try await self.get(for: .model(model), with: closure) 191 | } 192 | } 193 | 194 | extension Queryable { 195 | /// Deletes multiple models from the database 196 | /// - Parameter models: An array of models to delete 197 | /// - Throws: Rethrows any errors that occur during deletion 198 | public func deleteModels(_ models: [Model]) 199 | async throws 200 | { 201 | try await withThrowingTaskGroup( 202 | of: Void.self, 203 | body: { group in 204 | for model in models { 205 | group.addTask { 206 | try await self.delete(.model(model)) 207 | } 208 | } 209 | try await group.waitForAll() 210 | } 211 | ) 212 | } 213 | } 214 | #endif 215 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/Queryable.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Queryable.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import SwiftData 32 | /// Providers a set of _CRUD_ methods for a ``Database``. 33 | public protocol Queryable: Sendable { 34 | /// Saves the current state of the Queryable instance to the persistent data store. 35 | /// - Throws: An error that indicates why the save operation failed. 36 | func save() async throws 37 | 38 | /// Inserts a new persistent model into the data store and returns a transformed result. 39 | /// - Parameters: 40 | /// - insertClosure: A closure that creates a new instance of the `PersistentModelType`. 41 | /// - closure: A closure that performs some operation 42 | /// on the newly inserted `PersistentModelType` instance 43 | /// and returns a transformed result of type `U`. 44 | /// - Returns: The transformed result of type `U`. 45 | func insert( 46 | _ insertClosure: @Sendable @escaping () -> PersistentModelType, 47 | with closure: @escaping @Sendable (PersistentModelType) throws -> U 48 | ) async rethrows -> U 49 | 50 | /// Retrieves an optional persistent model from the data store and returns a transformed result. 51 | /// - Parameters: 52 | /// - selector: A `Selector.Get` instance 53 | /// that defines the criteria for retrieving the persistent model. 54 | /// - closure: A closure that performs some operation on 55 | /// the retrieved `PersistentModelType` instance (or `nil`) 56 | /// and returns a transformed result of type `U`. 57 | /// - Returns: The transformed result of type `U`. 58 | func getOptional( 59 | for selector: Selector.Get, 60 | with closure: @escaping @Sendable (PersistentModelType?) throws -> U 61 | ) async rethrows -> U 62 | 63 | /// Retrieves a list of persistent models from the data store and returns a transformed result. 64 | /// - Parameters: 65 | /// - selector: A `Selector.List` instance 66 | /// that defines the criteria for retrieving the list of persistent models. 67 | /// - closure: A closure that performs some operation on t 68 | /// he retrieved list of `PersistentModelType` instances and returns a transformed result of type `U`. 69 | /// - Returns: The transformed result of type `U`. 70 | func fetch( 71 | for selector: Selector.List, 72 | with closure: @escaping @Sendable ([PersistentModelType]) throws -> U 73 | ) async rethrows -> U 74 | 75 | /// Deletes one or more persistent models from the data store based on the provided selector. 76 | /// - Parameter selector: A `Selector.Delete` instance 77 | /// that defines the criteria for deleting the persistent models. 78 | /// - Throws: An error that indicates why the delete operation failed. 79 | func delete(_ selector: Selector.Delete) async throws 80 | } 81 | #endif 82 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/Selector.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Selector.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import Foundation 32 | public import SwiftData 33 | /// A type that represents a selector for interacting with a `PersistentModel`. 34 | public enum Selector: Sendable { 35 | /// A type that represents a way to delete data from a `PersistentModel`. 36 | public enum Delete: Sendable { 37 | /// Deletes data that matches the provided `Predicate`. 38 | case predicate(Predicate) 39 | /// Deletes all data for the `PersistentModel`. 40 | case all 41 | /// Deletes the provided `Model`. 42 | case model(Model) 43 | } 44 | 45 | /// A type that represents a way to fetch data from a `PersistentModel`. 46 | public enum List: Sendable { 47 | /// Fetches data using the provided `FetchDescriptor`. 48 | case descriptor(FetchDescriptor) 49 | } 50 | 51 | /// A type that represents a way to retrieve a `PersistentModel`. 52 | public enum Get: Sendable { 53 | /// Retrieves the `Model` with the provided `Model`. 54 | case model(Model) 55 | /// Retrieves the `PersistentModel` instances that match the provided `Predicate`. 56 | case predicate(Predicate) 57 | } 58 | } 59 | 60 | extension Selector.Get { 61 | /// Retrieves the `PersistentModel` instance with the provided unique key value. 62 | /// 63 | /// - Parameters: 64 | /// - key: The unique key to search for. 65 | /// - value: The value of the unique key to search for. 66 | /// - Returns: A `Selector.Get` case that can be used to retrieve the `PersistentModel` instance. 67 | @available(*, unavailable, message: "Not implemented yet.") 68 | public static func unique( 69 | _ key: UniqueKeyableType, 70 | equals value: UniqueKeyableType.ValueType 71 | ) -> Self where UniqueKeyableType.Model == T { 72 | .predicate( 73 | key.predicate(equals: value) 74 | ) 75 | } 76 | } 77 | 78 | extension Selector.List { 79 | /// Creates a `Selector.List` case 80 | /// that fetches `PersistentModel` instances using the provided parameters. 81 | /// 82 | /// - Parameters: 83 | /// - type: The type of `PersistentModel` to fetch. 84 | /// - predicate: An optional `Predicate` to filter the results. 85 | /// - sortBy: An optional array of `SortDescriptor` instances to sort the results. 86 | /// - fetchLimit: An optional limit on the number of results to fetch. 87 | /// - Returns: A `Selector.List` case that can be used to fetch `PersistentModel` instances. 88 | public static func descriptor( 89 | _ type: T.Type, 90 | predicate: Predicate? = nil, 91 | sortBy: [SortDescriptor] = [], 92 | fetchLimit: Int? = nil 93 | ) -> Selector.List { 94 | .descriptor(.init(predicate: predicate, sortBy: sortBy, fetchLimit: fetchLimit)) 95 | } 96 | 97 | /// Creates a `Selector.List` case that fetches `PersistentModel` instances 98 | /// using the provided parameters. 99 | /// 100 | /// - Parameters: 101 | /// - predicate: An optional `Predicate` to filter the results. 102 | /// - sortBy: An optional array of `SortDescriptor` instances to sort the results. 103 | /// - fetchLimit: An optional limit on the number of results to fetch. 104 | /// - Returns: A `Selector.List` case that can be used to fetch `PersistentModel` instances. 105 | public static func descriptor( 106 | predicate: Predicate? = nil, 107 | sortBy: [SortDescriptor] = [], 108 | fetchLimit: Int? = nil 109 | ) -> Selector.List { 110 | .descriptor(.init(predicate: predicate, sortBy: sortBy, fetchLimit: fetchLimit)) 111 | } 112 | 113 | /// Creates a `Selector.List` case that fetches all `PersistentModel` instances of the provided type. 114 | /// 115 | /// - Parameter type: The type of `PersistentModel` to fetch. 116 | /// - Returns: A `Selector.List` case 117 | /// that can be used to fetch all `PersistentModel` instances of the provided type. 118 | public static func all(_ type: T.Type) -> Selector.List { 119 | .descriptor(.init()) 120 | } 121 | 122 | /// Creates a `Selector.List` case that fetches all `PersistentModel` instances. 123 | /// 124 | /// - Returns: A `Selector.List` case that can be used to fetch all `PersistentModel` instances. 125 | public static func all() -> Selector.List { 126 | .descriptor(.init()) 127 | } 128 | } 129 | #endif 130 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/Unique.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Unique.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | /// A protocol that defines a type as being unique. 31 | @_documentation(visibility: internal) 32 | public protocol Unique { 33 | /// The associated type that conforms to `UniqueKeys` and represents the unique keys for this type. 34 | associatedtype Keys: UniqueKeys 35 | } 36 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/UniqueKey.swift: -------------------------------------------------------------------------------- 1 | // 2 | // UniqueKey.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | public import Foundation 31 | 32 | /// A protocol that defines a unique key for a model type. 33 | @_documentation(visibility: internal) 34 | public protocol UniqueKey: Sendable { 35 | /// The model type associated with this unique key. 36 | associatedtype Model: Unique 37 | 38 | /// The value type associated with this unique key. 39 | associatedtype ValueType: Sendable & Equatable & Codable 40 | 41 | /// Creates a predicate that checks if the model's value for this key equals the specified value. 42 | /// 43 | /// - Parameter value: The value to compare against. 44 | /// - Returns: A predicate that checks if the model's value for this key equals the specified value. 45 | func predicate(equals value: ValueType) -> Predicate 46 | } 47 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/UniqueKeyPath.swift: -------------------------------------------------------------------------------- 1 | // 2 | // UniqueKeyPath.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | public import Foundation 31 | 32 | // swiftlint:disable unavailable_function 33 | 34 | /// A struct that represents a unique key path for a model type. 35 | @_documentation(visibility: internal) 36 | public struct UniqueKeyPath: UniqueKey { 37 | /// The key path for the model type. 38 | private let keyPath: KeyPath & Sendable 39 | 40 | /// Initializes a new instance of `UniqueKeyPath` with the given key path. 41 | /// 42 | /// - Parameter keyPath: The key path for the model type. 43 | internal init(keyPath: any KeyPath & Sendable) { 44 | self.keyPath = keyPath 45 | } 46 | 47 | /// Creates a predicate that checks if the value of the key path is equal to the given value. 48 | /// 49 | /// - Parameter value: The value to compare against. 50 | /// - Returns: A predicate that can be used to filter models. 51 | public func predicate(equals value: ValueType) -> Predicate { 52 | fatalError("Not implemented yet.") 53 | } 54 | } 55 | 56 | // swiftlint:enable unavailable_function 57 | -------------------------------------------------------------------------------- /Sources/DataThespian/Databases/UniqueKeys.swift: -------------------------------------------------------------------------------- 1 | // 2 | // UniqueKeys.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | /// A protocol that defines the rules for a type that represents the unique keys for a `Model` type. 31 | /// 32 | /// The `UniqueKeys` protocol has two associated type requirements: 33 | /// 34 | /// - `Model`: The type for which the unique keys are defined. 35 | /// This type must conform to the `Unique` protocol. 36 | /// - `PrimaryKey`: The type that represents the primary key for the `Model` type. 37 | /// This type must conform to the `UniqueKey` protocol, and 38 | /// its `Model` associated type must be the same as 39 | /// the `Model` associated type of the `UniqueKeys` protocol. 40 | /// 41 | /// The protocol also has a static property requirement, `primary`, 42 | /// which returns the primary key for the `Model` type. 43 | @_documentation(visibility: internal) 44 | public protocol UniqueKeys: Sendable { 45 | /// The type for which the unique keys are defined. This type must conform to the `Unique` protocol. 46 | associatedtype Model: Unique 47 | 48 | /// The type that represents the primary key for the `Model` type. 49 | /// This type must conform to the `UniqueKey` protocol, and 50 | /// its `Model` associated type must be the same as 51 | /// the `Model` associated type of the `UniqueKeys` protocol. 52 | associatedtype PrimaryKey: UniqueKey where PrimaryKey.Model == Model 53 | 54 | /// The primary key for the `Model` type. 55 | static var primary: PrimaryKey { get } 56 | } 57 | 58 | extension UniqueKeys { 59 | /// Creates a `UniqueKeyPath` instance for the specified key path. 60 | /// 61 | /// - Parameter keyPath: A key path for a property of 62 | /// the `Model` type. The property must be `Sendable`, `Equatable`, and `Codable`. 63 | /// - Returns: A `UniqueKeyPath` instance for the specified key path. 64 | public static func keyPath( 65 | _ keyPath: any KeyPath & Sendable 66 | ) -> UniqueKeyPath { 67 | UniqueKeyPath(keyPath: keyPath) 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Sources/DataThespian/Documentation.docc/DataThespian.md: -------------------------------------------------------------------------------- 1 | # ``DataThespian`` 2 | 3 | A thread-safe implementation of SwiftData. 4 | 5 | ## Overview 6 | 7 | DataThespian combines the power of Actors, SwiftData, and ModelActors to create an optimized and easy-to-use APIs for developers. 8 | 9 | ### Requirements 10 | 11 | **Apple Platforms** 12 | 13 | - Xcode 16.0 or later 14 | - Swift 6.0 or later 15 | - iOS 17 / watchOS 10.0 / tvOS 17 / macOS 14 or later deployment targets 16 | 17 | **Linux** 18 | 19 | - Ubuntu 20.04 or later 20 | - Swift 6.0 or later 21 | 22 | ### Installation 23 | 24 | To integrate **DataThespian** into your app using SPM, specify it in your Package.swift file: 25 | 26 | ```swift 27 | let package = Package( 28 | ... 29 | dependencies: [ 30 | .package( 31 | url: "https://github.com/brightdigit/DataThespian.git", from: "1.0.0" 32 | ) 33 | ], 34 | targets: [ 35 | .target( 36 | name: "YourApps", 37 | dependencies: [ 38 | .product( 39 | name: "DataThespian", 40 | package: "DataThespian" 41 | ), ... 42 | ]), 43 | ... 44 | ] 45 | ) 46 | ``` 47 | 48 | ### Setting up Database 49 | 50 | ```swift 51 | var body: some Scene { 52 | WindowGroup { 53 | RootView() 54 | }.database(ModelActorDatabase(modelContainer: ...)) 55 | } 56 | ``` 57 | 58 | and then reference it in our SwiftUI View: 59 | 60 | ```swift 61 | @Environment(\.database) private var database 62 | ``` 63 | 64 | #### Using with ModelContext 65 | 66 | If you are familiar with Core Data, you probably know that you should use a single `NSManagedObjectContext` throughout your app. The issue here is that our initializer for `ModelActorDatabase` will be called each time the SwiftUI View is redraw. So if we look at the expanded `@ModelActor` Macro for our `ModelActorDatabase`, we see that a new `ModelContext` (SwiftData wrapper or abstraction, etc. of `NSManagedObjectContext`) is created each time: 67 | 68 | ```swift 69 | public init(modelContainer: SwiftData.ModelContainer) { 70 | let modelContext = ModelContext(modelContainer) 71 | self.modelExecutor = DefaultSerialModelExecutor(modelContext: modelContext) 72 | self.modelContainer = modelContainer 73 | } 74 | ``` 75 | 76 | The best approach is to create a singleton using `SharedDatabase`: 77 | 78 | ```swift 79 | public struct SharedDatabase { 80 | public static let shared: SharedDatabase = .init() 81 | 82 | public let schemas: [any PersistentModel.Type] 83 | public let modelContainer: ModelContainer 84 | public let database: any Database 85 | 86 | private init( 87 | schemas: [any PersistentModel.Type] = .all, 88 | modelContainer: ModelContainer? = nil, 89 | database: (any Database)? = nil 90 | ) { 91 | self.schemas = schemas 92 | let modelContainer = modelContainer ?? .forTypes(schemas) 93 | self.modelContainer = modelContainer 94 | self.database = database ?? ModelActorDatabase(modelContainer: modelContainer) 95 | } 96 | } 97 | ``` 98 | 99 | Then in your SwiftUI code: 100 | 101 | ```swift 102 | var body: some Scene { 103 | WindowGroup { 104 | RootView() 105 | } 106 | .database(SharedDatabase.shared.database) 107 | /* if we wish to continue using @Query 108 | .modelContainer(SharedDatabase.shared.modelContainer) 109 | */ 110 | } 111 | ``` 112 | 113 | ### Making Queries 114 | 115 | DataThespian uses a type-safe `Selector` enum to specify what data to query: 116 | 117 | ```swift 118 | // Get a single item 119 | let item = try await database.get(for: .predicate(#Predicate { 120 | $0.name == "Test" 121 | })) 122 | 123 | // Fetch a list with sorting 124 | let items = await database.fetch(for: .descriptor( 125 | predicate: #Predicate { $0.isActive == true }, 126 | sortBy: [SortDescriptor(\Item.timestamp, order: .reverse)], 127 | fetchLimit: 10 128 | )) 129 | 130 | // Delete matching items 131 | try await database.delete(.predicate(#Predicate { 132 | $0.timestamp < oneWeekAgo 133 | })) 134 | ``` 135 | 136 | ### Important: Working with Temporary IDs 137 | 138 | When inserting new models, SwiftData assigns temporary IDs that cannot be used across contexts until explicitly saved. After saving, you must re-query using a field value rather than the Model reference. Here's the safe pattern: 139 | 140 | ```swift 141 | // Create with a known unique value 142 | let timestamp = Date() 143 | let newItem = await database.insert { Item(name: "Test", timestamp: timestamp) } 144 | 145 | // Save to get permanent ID 146 | try await database.save() 147 | 148 | // Re-query using a unique field value 149 | let item = try await database.getOptional(for: .predicate(#Predicate { 150 | $0.timestamp == timestamp 151 | })) 152 | ``` 153 | 154 | ## Topics 155 | 156 | ### Database 157 | 158 | - ``Database`` 159 | - ``BackgroundDatabase`` 160 | - ``ModelActorDatabase`` 161 | 162 | ### Querying 163 | 164 | - ``Queryable`` 165 | - ``QueryError`` 166 | - ``Selector`` 167 | - ``Model`` 168 | 169 | ### Monitoring 170 | 171 | - ``DataMonitor`` 172 | - ``DataAgent`` 173 | - ``DatabaseChangeSet`` 174 | - ``DatabaseMonitoring`` 175 | - ``AgentRegister`` 176 | - ``ManagedObjectMetadata`` 177 | - ``DatabaseChangePublicist`` 178 | - ``DatabaseChangeType`` 179 | 180 | ### Synchronization 181 | 182 | - ``CollectionSynchronizer`` 183 | - ``ModelDifferenceSynchronizer`` 184 | - ``ModelSynchronizer`` 185 | - ``SynchronizationDifference`` 186 | - ``CollectionDifference`` 187 | -------------------------------------------------------------------------------- /Sources/DataThespian/Model.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Model.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | import Foundation 32 | public import SwiftData 33 | /// Phantom Type for easily retrieving fetching `PersistentModel` objects from a `ModelContext`. 34 | public struct Model: Sendable, Identifiable { 35 | /// An error that is thrown when a `PersistentModel` 36 | /// with the specified `PersistentIdentifier` is not found. 37 | public struct NotFoundError: Error { 38 | /// The `PersistentIdentifier` of the `PersistentModel` that was not found. 39 | public let persistentIdentifier: PersistentIdentifier 40 | } 41 | 42 | /// The unique identifier of the model. 43 | public var id: PersistentIdentifier.ID { persistentIdentifier.id } 44 | 45 | /// The `PersistentIdentifier` of the model. 46 | public let persistentIdentifier: PersistentIdentifier 47 | 48 | /// Initializes a new `Model` instance with the specified `PersistentIdentifier`. 49 | /// 50 | /// - Parameter persistentIdentifier: The `PersistentIdentifier` of the model. 51 | public init(persistentIdentifier: PersistentIdentifier) { 52 | self.persistentIdentifier = persistentIdentifier 53 | } 54 | } 55 | 56 | extension Model where T: PersistentModel { 57 | /// A boolean value indicating whether the model is temporary or not. 58 | public var isTemporary: Bool { 59 | self.persistentIdentifier.isTemporary ?? false 60 | } 61 | 62 | /// Initializes a new `Model` instance with the specified `PersistentModel`. 63 | /// 64 | /// - Parameter model: The `PersistentModel` to initialize the `Model` with. 65 | public init(_ model: T) { 66 | self.init(persistentIdentifier: model.persistentModelID) 67 | } 68 | 69 | /// Creates a new `Model` instance from the specified `PersistentModel`. 70 | /// 71 | /// - Parameter model: The `PersistentModel` to create the `Model` from. 72 | /// - Returns: A new `Model` instance, or `nil` if the `PersistentModel` is `nil`. 73 | internal static func ifMap(_ model: T?) -> Model? { 74 | model.map(self.init) 75 | } 76 | } 77 | #endif 78 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/AgentRegister.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AgentRegister.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | /// 32 | /// A protocol that defines an agent register for a specific agent type. 33 | /// 34 | public protocol AgentRegister: Sendable { 35 | /// 36 | /// The agent type associated with this register. 37 | /// 38 | associatedtype AgentType: DataAgent 39 | 40 | /// 41 | /// The unique identifier for this agent register. 42 | /// 43 | var id: String { get } 44 | 45 | /// 46 | /// Asynchronously retrieves the agent associated with this register. 47 | /// 48 | /// - Returns: The agent associated with this register. 49 | /// 50 | @Sendable func agent() async -> AgentType 51 | } 52 | 53 | extension AgentRegister { 54 | /// 55 | /// The unique identifier for this agent register. 56 | /// 57 | public var id: String { "\(AgentType.self)" } 58 | } 59 | #endif 60 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/Combine/DatabaseChangePublicist.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DatabaseChangePublicist.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(Combine) && canImport(SwiftData) 31 | public import Combine 32 | 33 | private struct NeverDatabaseMonitor: DatabaseMonitoring { 34 | /// Registers an agent with the database monitor, but always fails. 35 | /// - Parameters: 36 | /// - _: The agent to register. 37 | /// - _: A flag indicating whether the registration should be forced. 38 | func register(_: any AgentRegister, force _: Bool) { 39 | assertionFailure("Using Empty Database Listener") 40 | } 41 | } 42 | 43 | /// A struct that publishes database change events. 44 | public struct DatabaseChangePublicist: Sendable { 45 | private let dbWatcher: DatabaseMonitoring 46 | 47 | /// Initializes a new `DatabaseChangePublicist` instance. 48 | /// - Parameter dbWatcher: The database monitoring instance to use. Defaults to `DataMonitor.shared`. 49 | public init(dbWatcher: any DatabaseMonitoring = DataMonitor.shared) { 50 | self.dbWatcher = dbWatcher 51 | } 52 | 53 | /// Creates a `DatabaseChangePublicist` that never publishes any changes. 54 | public static func never() -> DatabaseChangePublicist { 55 | self.init(dbWatcher: NeverDatabaseMonitor()) 56 | } 57 | 58 | /// Publishes database change events for the specified ID. 59 | /// - Parameter id: The ID of the entity to watch for changes. 60 | /// - Returns: A publisher that emits `DatabaseChangeSet` values 61 | /// whenever the database changes for the specified ID. 62 | @Sendable public func callAsFunction(id: String) -> some Publisher 63 | { 64 | // print("Creating Publisher for \(id)") 65 | let subject = PassthroughSubject() 66 | dbWatcher.register(PublishingRegister(id: id, subject: subject), force: true) 67 | return subject 68 | } 69 | } 70 | #endif 71 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/Combine/EnvironmentValues+DatabaseChangePublicist.swift: -------------------------------------------------------------------------------- 1 | // 2 | // EnvironmentValues+DatabaseChangePublicist.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftUI) 31 | import Foundation 32 | 33 | public import SwiftUI 34 | 35 | extension EnvironmentValues { 36 | /// A `DatabaseChangePublicist` that determines how database changes are propagated to the UI. 37 | @Entry public var databaseChangePublicist: DatabaseChangePublicist = .never() 38 | } 39 | #endif 40 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/Combine/PublishingAgent.swift: -------------------------------------------------------------------------------- 1 | // 2 | // PublishingAgent.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(Combine) && canImport(SwiftData) 31 | @preconcurrency import Combine 32 | import Foundation 33 | 34 | /// An actor that manages the publishing of database change sets. 35 | internal actor PublishingAgent: DataAgent, Loggable { 36 | /// The subscription event. 37 | private enum SubscriptionEvent: Sendable { 38 | case cancel 39 | case subscribe 40 | } 41 | 42 | /// The logging category for the `PublishingAgent`. 43 | internal static var loggingCategory: ThespianLogging.Category { .application } 44 | 45 | /// The unique identifier for the agent. 46 | internal let agentID = UUID() 47 | 48 | /// The identifier for the agent. 49 | private let id: String 50 | 51 | /// The subject that publishes the database change sets. 52 | private let subject: PassthroughSubject 53 | 54 | /// The number of subscriptions. 55 | private var subscriptionCount = 0 56 | 57 | /// The cancellable for the subject. 58 | private var cancellable: AnyCancellable? 59 | 60 | /// The completion closure. 61 | private var completed: (@Sendable () -> Void)? 62 | 63 | /// Initializes a new `PublishingAgent` instance. 64 | /// - Parameters: 65 | /// - id: The identifier for the agent. 66 | /// - subject: The subject that publishes the database change sets. 67 | internal init(id: String, subject: PassthroughSubject) { 68 | self.id = id 69 | self.subject = subject 70 | Task { await self.initialize() } 71 | } 72 | 73 | /// Initializes the agent. 74 | private func initialize() { 75 | cancellable = subject.handleEvents { _ in 76 | self.onSubscriptionEvent(.subscribe) 77 | } receiveCancel: { 78 | self.onSubscriptionEvent(.cancel) 79 | } 80 | .sink { 81 | _ in 82 | } 83 | } 84 | 85 | /// Handles a subscription event. 86 | /// - Parameter event: The subscription event. 87 | private nonisolated func onSubscriptionEvent(_ event: SubscriptionEvent) { 88 | Task { await self.updateScriptionStatus(byEvent: event) } 89 | } 90 | 91 | /// Updates the subscription status. 92 | /// - Parameter event: The subscription event. 93 | private func updateScriptionStatus(byEvent event: SubscriptionEvent) { 94 | let oldCount = subscriptionCount 95 | let delta: Int = 96 | switch event { 97 | case .cancel: -1 98 | case .subscribe: 1 99 | } 100 | 101 | subscriptionCount += delta 102 | Self.logger.debug( 103 | // swiftlint:disable:next line_length 104 | "Updated Subscriptions for \(self.id) from \(oldCount) by \(delta) to \(self.subscriptionCount) \(self.agentID)" 105 | ) 106 | } 107 | 108 | /// Handles an update to the database. 109 | /// - Parameter update: The database change set. 110 | nonisolated internal func onUpdate(_ update: any DatabaseChangeSet) { 111 | Task { await self.sendUpdate(update) } 112 | } 113 | 114 | /// Sends the update to the subject. 115 | /// - Parameter update: The database change set. 116 | private func sendUpdate(_ update: any DatabaseChangeSet) { 117 | Task { @MainActor in await self.subject.send(update) } 118 | } 119 | 120 | /// Cancels the agent. 121 | private func cancel() { 122 | Self.logger.debug("Cancelling \(self.id) \(self.agentID)") 123 | cancellable?.cancel() 124 | cancellable = nil 125 | completed?() 126 | completed = nil 127 | } 128 | 129 | /// Sets the completion closure. 130 | /// - Parameter closure: The completion closure. 131 | nonisolated internal func onCompleted(_ closure: @escaping @Sendable () -> Void) { 132 | Task { await self.setCompleted(closure) } 133 | } 134 | 135 | /// Sets the completion closure. 136 | /// - Parameter closure: The completion closure. 137 | internal func setCompleted(_ closure: @escaping @Sendable () -> Void) { 138 | Self.logger.debug("SetCompleted \(self.id) \(self.agentID)") 139 | assert(completed == nil) 140 | completed = closure 141 | } 142 | 143 | /// Finishes the agent. 144 | internal func finish() { cancel() } 145 | } 146 | #endif 147 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/Combine/PublishingRegister.swift: -------------------------------------------------------------------------------- 1 | // 2 | // PublishingRegister.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(Combine) && canImport(SwiftData) 31 | @preconcurrency import Combine 32 | import Foundation 33 | 34 | /// A register that manages the publication of database changes. 35 | internal struct PublishingRegister: AgentRegister { 36 | /// The unique identifier for the register. 37 | internal let id: String 38 | 39 | /// The subject that publishes database change sets. 40 | private let subject: PassthroughSubject 41 | 42 | /// Initializes a new instance of `PublishingRegister`. 43 | /// 44 | /// - Parameters: 45 | /// - id: The unique identifier for the register. 46 | /// - subject: The subject that publishes database change sets. 47 | internal init(id: String, subject: PassthroughSubject) { 48 | self.id = id 49 | self.subject = subject 50 | } 51 | 52 | /// Creates a new publishing agent. 53 | /// 54 | /// - Returns: A new instance of `PublishingAgent`. 55 | internal func agent() async -> PublishingAgent { 56 | let agent = AgentType(id: id, subject: subject) 57 | 58 | return agent 59 | } 60 | } 61 | #endif 62 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/DataAgent.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DataAgent.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import Foundation 32 | /// A protocol that defines a data agent responsible for managing database updates and completions. 33 | public protocol DataAgent: Sendable { 34 | /// The unique identifier of the agent. 35 | var agentID: UUID { get } 36 | 37 | /// Called when the database is updated. 38 | /// 39 | /// - Parameter update: The database change set. 40 | func onUpdate(_ update: any DatabaseChangeSet) 41 | 42 | /// Called when the data agent's operations are completed. 43 | /// 44 | /// - Parameter closure: The closure to be executed when the operations are completed. 45 | func onCompleted(_ closure: @Sendable @escaping () -> Void) 46 | 47 | /// Finishes the data agent's operations. 48 | func finish() async 49 | } 50 | 51 | extension DataAgent { 52 | /// Called when the data agent's operations are completed. 53 | /// 54 | /// - Parameter closure: The closure to be executed when the operations are completed. 55 | public func onCompleted(_ closure: @Sendable @escaping () -> Void) {} 56 | } 57 | #endif 58 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/DataMonitor.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DataMonitor.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(Combine) && canImport(SwiftData) && canImport(CoreData) 31 | 32 | import Combine 33 | import CoreData 34 | import Foundation 35 | import SwiftData 36 | /// Monitors the database for changes and notifies registered agents of those changes. 37 | public actor DataMonitor: DatabaseMonitoring, Loggable { 38 | /// The logging category for this class. 39 | public static var loggingCategory: ThespianLogging.Category { .data } 40 | 41 | /// The shared instance of the `DataMonitor`. 42 | public static let shared = DataMonitor() 43 | 44 | private var object: (any NSObjectProtocol)? 45 | private var registrations = RegistrationCollection() 46 | 47 | private init() { Self.logger.debug("Creating DatabaseMonitor") } 48 | 49 | /// Registers the given agent with the database monitor. 50 | /// 51 | /// - Parameters: 52 | /// - registration: The agent to register. 53 | /// - force: Whether to force the registration, 54 | /// even if a registration with the same ID already exists. 55 | public nonisolated func register(_ registration: any AgentRegister, force: Bool) { 56 | Task { await self.addRegistration(registration, force: force) } 57 | } 58 | 59 | private func addRegistration(_ registration: any AgentRegister, force: Bool) { 60 | registrations.add(withID: registration.id, force: force, agent: registration.agent) 61 | } 62 | 63 | /// Begins monitoring the database with the given agent registrations. 64 | /// 65 | /// - Parameter builders: The agent registrations to monitor. 66 | public nonisolated func begin(with builders: [any AgentRegister]) { 67 | Task { 68 | await self.addObserver() 69 | for builder in builders { await self.addRegistration(builder, force: false) } 70 | } 71 | } 72 | 73 | private func addObserver() { 74 | guard object == nil else { 75 | return 76 | } 77 | object = NotificationCenter.default.addObserver( 78 | forName: .NSManagedObjectContextDidSave, 79 | object: nil, 80 | queue: nil, 81 | using: { notification in 82 | let update = NotificationDataUpdate(notification) 83 | Task { await self.notifyRegisration(update) } 84 | } 85 | ) 86 | } 87 | 88 | private func notifyRegisration(_ update: any DatabaseChangeSet) { 89 | guard !update.isEmpty else { 90 | return 91 | } 92 | Self.logger.debug("Notifying of Update") 93 | 94 | registrations.notify(update) 95 | } 96 | } 97 | #endif 98 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/DatabaseChangeSet.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DatabaseChangeSet.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | /// A protocol that represents a set of changes to a database. 32 | public protocol DatabaseChangeSet: Sendable { 33 | /// The set of inserted managed object metadata. 34 | var inserted: Set { get } 35 | 36 | /// The set of deleted managed object metadata. 37 | var deleted: Set { get } 38 | 39 | /// The set of updated managed object metadata. 40 | var updated: Set { get } 41 | } 42 | 43 | extension DatabaseChangeSet { 44 | /// A boolean value that indicates whether the change set is empty. 45 | public var isEmpty: Bool { inserted.isEmpty && deleted.isEmpty && updated.isEmpty } 46 | 47 | /// Checks whether the change set contains any changes of the specified types 48 | /// that match the provided entity names. 49 | /// 50 | /// - Parameters: 51 | /// - types: The set of change types to check for. Defaults to `.all`. 52 | /// - filteringEntityNames: The set of entity names to filter by. 53 | /// - Returns: `true` if the change set contains any changes of the specified types 54 | /// that match the provided entity names, `false` otherwise. 55 | public func update( 56 | of types: Set = .all, contains filteringEntityNames: Set 57 | ) -> Bool { 58 | let updateEntityNamesArray = types.flatMap { self[keyPath: $0.keyPath] }.map(\.entityName) 59 | let updateEntityNames = Set(updateEntityNamesArray) 60 | return !updateEntityNames.isDisjoint(with: filteringEntityNames) 61 | } 62 | } 63 | #endif 64 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/DatabaseChangeType.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DatabaseChangeType.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | /// An enumeration that represents the different types of changes that can occur in a database. 31 | public enum DatabaseChangeType: CaseIterable, Sendable { 32 | /// Represents an insertion of a new record in the database. 33 | case inserted 34 | /// Represents a deletion of a record in the database. 35 | case deleted 36 | /// Represents an update to an existing record in the database. 37 | case updated 38 | 39 | #if canImport(SwiftData) 40 | /// The key path associated with the current change type. 41 | internal var keyPath: KeyPath> { 42 | switch self { 43 | case .inserted: 44 | return \.inserted 45 | case .deleted: 46 | return \.deleted 47 | case .updated: 48 | return \.updated 49 | } 50 | } 51 | #endif 52 | } 53 | 54 | /// An extension to `Set` where the `Element` is `DatabaseChangeType`. 55 | extension Set where Element == DatabaseChangeType { 56 | /// A static property that represents a set containing all `DatabaseChangeType` cases. 57 | public static let all: Self = .init(DatabaseChangeType.allCases) 58 | } 59 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/DatabaseMonitoring.swift: -------------------------------------------------------------------------------- 1 | // 2 | // DatabaseMonitoring.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | /// A protocol that defines the behavior for database monitoring. 32 | public protocol DatabaseMonitoring: Sendable { 33 | /// Registers an agent with the database monitoring system. 34 | /// 35 | /// - Parameters: 36 | /// - registration: The agent to be registered. 37 | /// - force: A boolean value indicating whether the registration should be forced, 38 | /// even if a registration with the same ID already exists. 39 | func register(_ registration: any AgentRegister, force: Bool) 40 | } 41 | #endif 42 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/ManagedObjectMetadata.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ManagedObjectMetadata.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import SwiftData 32 | /// A struct that holds metadata about a managed object. 33 | public struct ManagedObjectMetadata: Sendable, Hashable { 34 | /// The name of the entity associated with the managed object. 35 | public let entityName: String 36 | /// The persistent identifier of the managed object. 37 | public let persistentIdentifier: PersistentIdentifier 38 | 39 | /// Initializes a `ManagedObjectMetadata` instance 40 | /// with the provided entity name and persistent identifier. 41 | /// 42 | /// - Parameters: 43 | /// - entityName: The name of the entity associated with the managed object. 44 | /// - persistentIdentifier: The persistent identifier of the managed object. 45 | public init(entityName: String, persistentIdentifier: PersistentIdentifier) { 46 | self.entityName = entityName 47 | self.persistentIdentifier = persistentIdentifier 48 | } 49 | } 50 | 51 | #if canImport(CoreData) 52 | import CoreData 53 | 54 | extension ManagedObjectMetadata { 55 | /// Initializes a `ManagedObjectMetadata` instance with the provided `NSManagedObject`. 56 | /// 57 | /// - Parameter managedObject: The `NSManagedObject` instance to get the metadata from. 58 | internal init?(managedObject: NSManagedObject) { 59 | let persistentIdentifier: PersistentIdentifier 60 | do { 61 | persistentIdentifier = try managedObject.objectID.persistentIdentifier() 62 | } catch { 63 | assertionFailure(error: error) 64 | return nil 65 | } 66 | 67 | guard let entityName = managedObject.entity.name else { 68 | assertionFailure("Missing entity name.") 69 | return nil 70 | } 71 | 72 | self.init(entityName: entityName, persistentIdentifier: persistentIdentifier) 73 | } 74 | } 75 | #endif 76 | #endif 77 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/Notification.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Notification.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(CoreData) 31 | import CoreData 32 | import Foundation 33 | 34 | extension Notification { 35 | /// Extracts a set of `ManagedObjectMetadata` from the user info dictionary of the notification. 36 | /// 37 | /// - Parameter key: The key to use to extract the set of `NSManagedObject` instances 38 | /// from the user info dictionary. 39 | /// - Returns: An optional set of `ManagedObjectMetadata` instances, 40 | /// or `nil` if the set of `NSManagedObject` instances could not be found or extracted. 41 | internal func managedObjects(key: String) -> Set? { 42 | guard let objects = userInfo?[key] as? Set else { 43 | return nil 44 | } 45 | 46 | return Set(objects.compactMap(ManagedObjectMetadata.init(managedObject:))) 47 | } 48 | } 49 | #endif 50 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/NotificationDataUpdate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // NotificationDataUpdate.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(CoreData) && canImport(SwiftData) 31 | import CoreData 32 | import Foundation 33 | /// Represents a set of changes to managed objects in a Core Data store. 34 | internal struct NotificationDataUpdate: DatabaseChangeSet, Sendable { 35 | /// The set of managed objects that were inserted. 36 | internal let inserted: Set 37 | 38 | /// The set of managed objects that were deleted. 39 | internal let deleted: Set 40 | 41 | /// The set of managed objects that were updated. 42 | internal let updated: Set 43 | 44 | /// Initializes a `NotificationDataUpdate` instance with the specified sets 45 | /// of inserted, deleted, and updated managed objects. 46 | /// 47 | /// - Parameters: 48 | /// - inserted: The set of managed objects that were inserted, or an empty set if none were inserted. 49 | /// - deleted: The set of managed objects that were deleted, or an empty set if none were deleted. 50 | /// - updated: The set of managed objects that were updated, or an empty set if none were updated. 51 | private init( 52 | inserted: Set?, 53 | deleted: Set?, 54 | updated: Set? 55 | ) { 56 | self.init( 57 | inserted: inserted ?? .init(), 58 | deleted: deleted ?? .init(), 59 | updated: updated ?? .init() 60 | ) 61 | } 62 | 63 | /// Initializes a `NotificationDataUpdate` instance with 64 | /// the specified sets of inserted, deleted, and updated managed objects. 65 | /// 66 | /// - Parameters: 67 | /// - inserted: The set of managed objects that were inserted. 68 | /// - deleted: The set of managed objects that were deleted. 69 | /// - updated: The set of managed objects that were updated. 70 | private init( 71 | inserted: Set, 72 | deleted: Set, 73 | updated: Set 74 | ) { 75 | self.inserted = inserted 76 | self.deleted = deleted 77 | self.updated = updated 78 | } 79 | 80 | /// Initializes a `NotificationDataUpdate` instance from a Notification object. 81 | /// 82 | /// - Parameter notification: The notification that triggered the data update. 83 | internal init(_ notification: Notification) { 84 | self.init( 85 | inserted: notification.managedObjects(key: NSInsertedObjectsKey), 86 | deleted: notification.managedObjects(key: NSDeletedObjectsKey), 87 | updated: notification.managedObjects(key: NSUpdatedObjectsKey) 88 | ) 89 | } 90 | } 91 | #endif 92 | -------------------------------------------------------------------------------- /Sources/DataThespian/Notification/RegistrationCollection.swift: -------------------------------------------------------------------------------- 1 | // 2 | // RegistrationCollection.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | import Foundation 32 | /// An actor that manages a collection of `DataAgent` registrations. 33 | internal actor RegistrationCollection: Loggable { 34 | internal static var loggingCategory: ThespianLogging.Category { .application } 35 | 36 | private var registrations = [String: DataAgent]() 37 | 38 | /// Notifies the collection of a database change set update. 39 | /// - Parameter update: The database change set update. 40 | nonisolated internal func notify(_ update: any DatabaseChangeSet) { 41 | Task { 42 | await self.onUpdate(update) 43 | Self.logger.debug("Notification Complete") 44 | } 45 | } 46 | 47 | /// Adds a new `DataAgent` registration to the collection. 48 | /// - Parameters: 49 | /// - id: The unique identifier for the registration. 50 | /// - force: A Boolean value indicating whether to force the registration if it already exists. 51 | /// - agent: A closure that creates the `DataAgent` to be registered. 52 | nonisolated internal func add( 53 | withID id: String, force: Bool, agent: @Sendable @escaping () async -> DataAgent 54 | ) { 55 | Task { await self.append(withID: id, force: force, agent: agent) } 56 | } 57 | 58 | private func append( 59 | withID id: String, force: Bool, agent: @Sendable @escaping () async -> DataAgent 60 | ) async { 61 | if let registration = registrations[id], force { 62 | Self.logger.debug("Overwriting \(id). Already exists.") 63 | await registration.finish() 64 | } else if registrations[id] != nil { 65 | Self.logger.debug("Can't register \(id). Already exists.") 66 | return 67 | } 68 | Self.logger.debug("Registering \(id)") 69 | let agent = await agent() 70 | agent.onCompleted { Task { await self.remove(withID: id, agentID: agent.agentID) } } 71 | registrations[id] = agent 72 | Self.logger.debug("Registration Count \(self.registrations.count)") 73 | } 74 | 75 | private func remove(withID id: String, agentID: UUID) { 76 | guard let agent = registrations[id] else { 77 | Self.logger.warning("No matching registration with id: \(id)") 78 | return 79 | } 80 | guard agent.agentID == agentID else { 81 | Self.logger.warning("No matching registration with agentID: \(agentID)") 82 | return 83 | } 84 | registrations.removeValue(forKey: id) 85 | Self.logger.debug("Registration Count \(self.registrations.count)") 86 | } 87 | 88 | private func onUpdate(_ update: any DatabaseChangeSet) { 89 | for (id, registration) in registrations { 90 | Self.logger.debug("Notifying \(id)") 91 | registration.onUpdate(update) 92 | } 93 | } 94 | } 95 | #endif 96 | -------------------------------------------------------------------------------- /Sources/DataThespian/SwiftData/FetchDescriptor.swift: -------------------------------------------------------------------------------- 1 | // 2 | // FetchDescriptor.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import Foundation 32 | public import SwiftData 33 | /// 34 | /// Represents a descriptor that can be used to fetch data from a data store. 35 | /// 36 | extension FetchDescriptor { 37 | /// 38 | /// Initializes a `FetchDescriptor` with the specified parameters. 39 | /// - Parameters: 40 | /// - predicate: An optional `Predicate` that filters the results. 41 | /// - sortBy: An array of `SortDescriptor` objects that determine the sort order of the results. 42 | /// - fetchLimit: An optional integer that limits the number of results returned. 43 | public init(predicate: Predicate? = nil, sortBy: [SortDescriptor] = [], fetchLimit: Int?) 44 | { 45 | self.init(predicate: predicate, sortBy: sortBy) 46 | self.fetchLimit = fetchLimit 47 | } 48 | } 49 | #endif 50 | -------------------------------------------------------------------------------- /Sources/DataThespian/SwiftData/ModelContext+Extension.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ModelContext+Extension.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import Foundation 32 | public import SwiftData 33 | /// Extension to `ModelContext` to provide additional functionality for managing persistent models. 34 | extension ModelContext { 35 | /// Inserts a new persistent model into the context. 36 | /// - Parameter closuer: A closure that creates a new instance of the `PersistentModel`. 37 | /// - Returns: A `Model` instance representing the newly inserted model. 38 | public func insert(_ closuer: @escaping @Sendable () -> T) -> Model { 39 | let model = closuer() 40 | self.insert(model) 41 | return .init(model) 42 | } 43 | 44 | /// Fetches an array of persistent models based on the provided selectors. 45 | /// - Parameter selectors: An array of `Selector.Get` instances 46 | /// to fetch the models. 47 | /// - Returns: An array of `PersistentModelType` instances. 48 | /// - Throws: A `SwiftData` error. 49 | public func fetch( 50 | for selectors: [Selector.Get] 51 | ) throws -> [PersistentModelType] { 52 | try selectors 53 | .map { 54 | try self.getOptional(for: $0) 55 | } 56 | .compactMap { $0 } 57 | } 58 | 59 | /// Retrieves a persistent model from the context. 60 | /// - Parameter model: A `Model` instance representing the persistent model to fetch. 61 | /// - Returns: The `T` instance of the persistent model. 62 | /// - Throws: `QueryError.itemNotFound` if the model is not found in the context. 63 | public func get(_ model: Model) throws -> T 64 | where T: PersistentModel { 65 | guard let item = try self.getOptional(model) else { 66 | throw QueryError.itemNotFound(.model(model)) 67 | } 68 | return item 69 | } 70 | 71 | /// Deletes persistent models based on the provided selectors. 72 | /// - Parameter selectors: An array of `Selector.Delete` instances 73 | /// to delete the models. 74 | /// - Throws: A `SwiftData` error. 75 | public func delete( 76 | _ selectors: [Selector.Delete] 77 | ) throws { 78 | for selector in selectors { 79 | try self.delete(selector) 80 | } 81 | } 82 | 83 | /// Retrieves the first persistent model that matches the provided predicate. 84 | /// - Parameter predicate: An optional `Predicate` instance to filter the results. 85 | /// - Returns: The first `PersistentModelType` instance that matches the predicate, 86 | /// or `nil` if no match is found. 87 | /// - Throws: A `SwiftData` error. 88 | public func first( 89 | where predicate: Predicate? = nil 90 | ) throws -> PersistentModelType? { 91 | try self.fetch(FetchDescriptor(predicate: predicate, fetchLimit: 1)).first 92 | } 93 | } 94 | #endif 95 | -------------------------------------------------------------------------------- /Sources/DataThespian/SwiftData/ModelContext+Queryable.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ModelContext+Queryable.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import SwiftData 32 | /// Extends the `ModelContext` class with additional methods for querying and managing persistent models. 33 | extension ModelContext { 34 | /// Inserts a new persistent model and performs a closure on it. 35 | /// 36 | /// - Parameters: 37 | /// - closuer: A closure that creates a new instance of the persistent model. 38 | /// - closure: A closure that performs an operation on the newly inserted persistent model. 39 | /// - Returns: The result of the `closure` parameter. 40 | public func insert( 41 | _ closuer: @Sendable @escaping () -> PersistentModelType, 42 | with closure: @escaping @Sendable (PersistentModelType) throws -> U 43 | ) rethrows -> U { 44 | let persistentModel = closuer() 45 | self.insert(persistentModel) 46 | return try closure(persistentModel) 47 | } 48 | 49 | /// Retrieves an optional persistent model based on a selector. 50 | /// 51 | /// - Parameter selector: A selector that specifies the criteria for retrieving the persistent model. 52 | /// - Returns: An optional persistent model that matches the selector criteria. 53 | /// - Throws: A `SwiftData` error. 54 | public func getOptional(for selector: Selector.Get) 55 | throws -> PersistentModelType? 56 | { 57 | let persistentModel: PersistentModelType? 58 | switch selector { 59 | case .model(let model): 60 | persistentModel = try self.getOptional(model) 61 | case .predicate(let predicate): 62 | persistentModel = try self.first(where: predicate) 63 | } 64 | return persistentModel 65 | } 66 | 67 | /// Retrieves an optional persistent model based on a selector and performs a closure on it. 68 | /// 69 | /// - Parameters: 70 | /// - selector: A selector that specifies the criteria for retrieving the persistent model. 71 | /// - closure: A closure that performs an operation on the retrieved persistent model. 72 | /// - Returns: The result of the `closure` parameter. 73 | /// - Throws: A `SwiftData` error. 74 | public func getOptional( 75 | for selector: Selector.Get, 76 | with closure: @escaping @Sendable (PersistentModelType?) throws -> U 77 | ) throws -> U { 78 | let persistentModel: PersistentModelType? 79 | switch selector { 80 | case .model(let model): 81 | persistentModel = try self.getOptional(model) 82 | case .predicate(let predicate): 83 | persistentModel = try self.first(where: predicate) 84 | } 85 | return try closure(persistentModel) 86 | } 87 | 88 | /// Retrieves a list of persistent models based on a selector and performs a closure on it. 89 | /// 90 | /// - Parameters: 91 | /// - selector: A selector that specifies the criteria for retrieving the list of persistent models. 92 | /// - closure: A closure that performs an operation on the retrieved list of persistent models. 93 | /// - Returns: The result of the `closure` parameter. 94 | /// - Throws: A `SwiftData` error. 95 | public func fetch( 96 | for selector: Selector.List, 97 | with closure: @escaping @Sendable ([PersistentModelType]) throws -> U 98 | ) throws -> U { 99 | let persistentModels: [PersistentModelType] 100 | switch selector { 101 | case .descriptor(let descriptor): 102 | persistentModels = try self.fetch(descriptor) 103 | } 104 | return try closure(persistentModels) 105 | } 106 | 107 | /// Deletes persistent models based on a selector. 108 | /// 109 | /// - Parameter selector: A selector that specifies the criteria for deleting the persistent models. 110 | /// - Throws: A `SwiftData` error. 111 | public func delete(_ selector: Selector.Delete) throws 112 | { 113 | switch selector { 114 | case .all: 115 | try self.delete(model: PersistentModelType.self) 116 | case .model(let model): 117 | if let persistentModel = try self.getOptional(model) { 118 | self.delete(persistentModel) 119 | } 120 | case .predicate(let predicate): 121 | try self.delete(model: PersistentModelType.self, where: predicate) 122 | } 123 | } 124 | } 125 | #endif 126 | -------------------------------------------------------------------------------- /Sources/DataThespian/SwiftData/ModelContext.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ModelContext.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | import Foundation 32 | public import SwiftData 33 | 34 | /// An extension to the `ModelContext` class that provides additional functionality using ``Model``. 35 | extension ModelContext { 36 | /// Retrieves an optional persistent model of the specified type with the given persistent identifier. 37 | /// 38 | /// - Parameter model: The model for which to retrieve the persistent model. 39 | /// - Returns: An optional instance of the specified persistent model, 40 | /// or `nil` if the model was not found. 41 | /// - Throws: A `SwiftData` error. 42 | public func getOptional(_ model: Model) throws -> T? 43 | where T: PersistentModel { 44 | try self.persistentModel(withID: model.persistentIdentifier) 45 | } 46 | 47 | /// Retrieves a persistent model of the specified type with the given persistent identifier. 48 | /// 49 | /// - Parameter objectID: The persistent identifier of the model to retrieve. 50 | /// - Returns: An optional instance of the specified persistent model, 51 | /// or `nil` if the model was not found. 52 | /// - Throws: A `SwiftData` error. 53 | private func persistentModel(withID objectID: PersistentIdentifier) throws -> T? 54 | where T: PersistentModel { 55 | if let registered: T = registeredModel(for: objectID) { 56 | return registered 57 | } 58 | if let notRegistered: T = model(for: objectID) as? T { 59 | return notRegistered 60 | } 61 | 62 | let fetchDescriptor = FetchDescriptor( 63 | predicate: #Predicate { $0.persistentModelID == objectID }, 64 | fetchLimit: 1 65 | ) 66 | 67 | return try fetch(fetchDescriptor).first 68 | } 69 | } 70 | #endif 71 | -------------------------------------------------------------------------------- /Sources/DataThespian/SwiftData/NSManagedObjectID.swift: -------------------------------------------------------------------------------- 1 | // 2 | // NSManagedObjectID.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(CoreData) && canImport(SwiftData) 31 | public import CoreData 32 | import Foundation 33 | public import SwiftData 34 | 35 | // periphery:ignore 36 | private struct PersistentIdentifierJSON: Codable { 37 | private struct Implementation: Codable { 38 | fileprivate init( 39 | primaryKey: String, 40 | uriRepresentation: URL, 41 | isTemporary: Bool, 42 | storeIdentifier: String, 43 | entityName: String 44 | ) { 45 | self.primaryKey = primaryKey 46 | self.uriRepresentation = uriRepresentation 47 | self.isTemporary = isTemporary 48 | self.storeIdentifier = storeIdentifier 49 | self.entityName = entityName 50 | } 51 | private var primaryKey: String 52 | private var uriRepresentation: URL 53 | private var isTemporary: Bool 54 | private var storeIdentifier: String 55 | private var entityName: String 56 | } 57 | 58 | private var implementation: Implementation 59 | 60 | private init(implementation: PersistentIdentifierJSON.Implementation) { 61 | self.implementation = implementation 62 | } 63 | 64 | fileprivate init( 65 | primaryKey: String, 66 | uriRepresentation: URL, 67 | isTemporary: Bool, 68 | storeIdentifier: String, 69 | entityName: String 70 | ) { 71 | self.init( 72 | implementation: 73 | .init( 74 | primaryKey: primaryKey, 75 | uriRepresentation: uriRepresentation, 76 | isTemporary: isTemporary, 77 | storeIdentifier: storeIdentifier, 78 | entityName: entityName 79 | ) 80 | ) 81 | } 82 | } 83 | 84 | extension NSManagedObjectID { 85 | public enum PersistentIdentifierError: Error { 86 | case decodingError(DecodingError) 87 | case encodingError(EncodingError) 88 | case missingProperty(Property) 89 | 90 | public enum Property: Sendable { 91 | case storeIdentifier 92 | case entityName 93 | } 94 | } 95 | 96 | /// Compute PersistentIdentifier from NSManagedObjectID. 97 | /// 98 | /// - Returns: A PersistentIdentifier instance. 99 | /// - Throws: `PersistentIdentifierError` 100 | /// if the `storeIdentifier` or `entityName` properties are missing. 101 | public func persistentIdentifier() throws -> PersistentIdentifier { 102 | guard let storeIdentifier else { 103 | throw PersistentIdentifierError.missingProperty(.storeIdentifier) 104 | } 105 | guard let entityName else { throw PersistentIdentifierError.missingProperty(.entityName) } 106 | let json = PersistentIdentifierJSON( 107 | primaryKey: primaryKey, 108 | uriRepresentation: uriRepresentation(), 109 | isTemporary: isTemporaryID, 110 | storeIdentifier: storeIdentifier, 111 | entityName: entityName 112 | ) 113 | let encoder = JSONEncoder() 114 | let data: Data 115 | do { data = try encoder.encode(json) } catch let error as EncodingError { 116 | throw PersistentIdentifierError.encodingError(error) 117 | } 118 | let decoder = JSONDecoder() 119 | do { return try decoder.decode(PersistentIdentifier.self, from: data) } catch let error 120 | as DecodingError 121 | { throw PersistentIdentifierError.decodingError(error) } 122 | } 123 | } 124 | 125 | // Extensions to expose needed implementation details 126 | extension NSManagedObjectID { 127 | /// The primary key of the managed object, which is the last path component of the URI. 128 | public var primaryKey: String { uriRepresentation().lastPathComponent } 129 | 130 | /// The store identifier, which is the host of the URI. 131 | public var storeIdentifier: String? { 132 | guard let identifier = uriRepresentation().host() else { 133 | return nil 134 | } 135 | return identifier 136 | } 137 | 138 | /// The entity name, which is derived from the entity. 139 | public var entityName: String? { 140 | guard let entityName = entity.name else { 141 | return nil 142 | } 143 | return entityName 144 | } 145 | } 146 | #endif 147 | -------------------------------------------------------------------------------- /Sources/DataThespian/SwiftData/PersistentIdentifier.swift: -------------------------------------------------------------------------------- 1 | // 2 | // PersistentIdentifier.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(CoreData) && canImport(SwiftData) 31 | import CoreData 32 | import Foundation 33 | import SwiftData 34 | /// Returns the value of a child property of an object using reflection. 35 | /// 36 | /// - Parameters: 37 | /// - object: The object to inspect. 38 | /// - childName: The name of the child property to retrieve. 39 | /// - Returns: The value of the child property, or nil if it does not exist. 40 | private func getMirrorChildValue(of object: Any, childName: String) -> Any? { 41 | guard let child = Mirror(reflecting: object).children.first(where: { $0.label == childName }) 42 | else { 43 | return nil 44 | } 45 | 46 | return child.value 47 | } 48 | 49 | // Extension to add computed properties for accessing underlying CoreData 50 | // implementation details of PersistentIdentifier 51 | extension PersistentIdentifier { 52 | // Private stored property to hold reference to underlying implementation 53 | private var mirrorImplementation: Any? { 54 | guard let implementation = getMirrorChildValue(of: self, childName: "implementation") else { 55 | assertionFailure("Should always be there.") 56 | return nil 57 | } 58 | return implementation 59 | } 60 | 61 | // Computed property to access managedObjectID from implementation 62 | private var objectID: NSManagedObjectID? { 63 | guard let mirrorImplementation, 64 | let objectID = getMirrorChildValue(of: mirrorImplementation, childName: "managedObjectID") 65 | as? NSManagedObjectID 66 | else { 67 | return nil 68 | } 69 | return objectID 70 | } 71 | 72 | // Computed property to access uriRepresentation from objectID 73 | private var uriRepresentation: URL? { 74 | objectID?.uriRepresentation() 75 | } 76 | 77 | // swiftlint:disable:next discouraged_optional_boolean 78 | internal var isTemporary: Bool? { 79 | guard let mirrorImplementation, 80 | let isTemporary = getMirrorChildValue(of: mirrorImplementation, childName: "isTemporary") 81 | as? Bool 82 | else { 83 | assertionFailure("Should always be there.") 84 | return nil 85 | } 86 | return isTemporary 87 | } 88 | } 89 | #endif 90 | -------------------------------------------------------------------------------- /Sources/DataThespian/Synchronization/CollectionDifference.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CollectionDifference.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import SwiftData 32 | /// Represents the difference between a persistent model and its associated data. 33 | public struct CollectionDifference: 34 | Sendable 35 | { 36 | /// The items that need to be inserted. 37 | public let inserts: [DataType] 38 | /// The models that need to be deleted. 39 | public let modelsToDelete: [Model] 40 | /// The items that need to be updated. 41 | public let updates: [DataType] 42 | 43 | /// Initializes a `CollectionDifference` instance with 44 | /// the specified inserts, models to delete, and updates. 45 | /// - Parameters: 46 | /// - inserts: The items that need to be inserted. 47 | /// - modelsToDelete: The models that need to be deleted. 48 | /// - updates: The items that need to be updated. 49 | public init( 50 | inserts: [DataType], modelsToDelete: [Model], updates: [DataType] 51 | ) { 52 | self.inserts = inserts 53 | self.modelsToDelete = modelsToDelete 54 | self.updates = updates 55 | } 56 | } 57 | 58 | extension CollectionDifference { 59 | /// The delete selectors for the models that need to be deleted. 60 | public var deleteSelectors: [DataThespian.Selector.Delete] { 61 | self.modelsToDelete.map { 62 | .model($0) 63 | } 64 | } 65 | 66 | /// Initializes a `CollectionDifference` instance by comparing the persistent models and data. 67 | /// - Parameters: 68 | /// - persistentModels: The persistent models to compare. 69 | /// - data: The data to compare. 70 | /// - persistentModelKeyPath: The key path to the unique identifier in the persistent models. 71 | /// - dataKeyPath: The key path to the unique identifier in the data. 72 | public init( 73 | persistentModels: [PersistentModelType]?, 74 | data: [DataType]?, 75 | persistentModelKeyPath: KeyPath, 76 | dataKeyPath: KeyPath 77 | ) { 78 | let persistentModels = persistentModels ?? [] 79 | let entryMap: [ID: PersistentModelType] = 80 | .init( 81 | uniqueKeysWithValues: persistentModels.map { 82 | ($0[keyPath: persistentModelKeyPath], $0) 83 | } 84 | ) 85 | 86 | let data = data ?? [] 87 | let dataMap: [ID: DataType] = .init( 88 | uniqueKeysWithValues: data.map { 89 | ($0[keyPath: dataKeyPath], $0) 90 | } 91 | ) 92 | 93 | let entryIDsToUpdate = Set(entryMap.keys).intersection(dataMap.keys) 94 | let entryIDsToDelete = Set(entryMap.keys).subtracting(dataMap.keys) 95 | let entryIDsToInsert = Set(dataMap.keys).subtracting(entryMap.keys) 96 | 97 | let entriesToDelete = entryIDsToDelete.compactMap { entryMap[$0] }.map(Model.init) 98 | let entryItemsToInsert = entryIDsToInsert.compactMap { dataMap[$0] } 99 | let entriesToUpdate = entryIDsToUpdate.compactMap { 100 | dataMap[$0] 101 | } 102 | 103 | assert(entryIDsToUpdate.count == entriesToUpdate.count) 104 | assert(entryIDsToDelete.count == entriesToDelete.count) 105 | assert(entryItemsToInsert.count == entryIDsToInsert.count) 106 | 107 | self.init( 108 | inserts: entryItemsToInsert, 109 | modelsToDelete: entriesToDelete, 110 | updates: entriesToUpdate 111 | ) 112 | } 113 | } 114 | #endif 115 | -------------------------------------------------------------------------------- /Sources/DataThespian/Synchronization/CollectionSynchronizer.swift: -------------------------------------------------------------------------------- 1 | // 2 | // CollectionSynchronizer.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import SwiftData 32 | private struct SynchronizationUpdate { 33 | var file: DataType? 34 | var entry: PersistentModelType? 35 | } 36 | /// A protocol that defines the synchronization behavior between a persistent model and data. 37 | public protocol CollectionSynchronizer { 38 | /// The type of the persistent model. 39 | associatedtype PersistentModelType: PersistentModel 40 | 41 | /// The type of the data. 42 | associatedtype DataType: Sendable 43 | 44 | /// The type of the identifier. 45 | associatedtype ID: Hashable 46 | 47 | /// The key path to the identifier in the data. 48 | static var dataKey: KeyPath { get } 49 | 50 | /// The key path to the identifier in the persistent model. 51 | static var persistentModelKey: KeyPath { get } 52 | 53 | /// Retrieves a selector for fetching the persistent model from the data. 54 | /// 55 | /// - Parameter data: The data to use for constructing the selector. 56 | /// - Returns: A selector for fetching the persistent model. 57 | static func getSelector(from data: DataType) -> DataThespian.Selector.Get 58 | 59 | /// Creates a persistent model from the provided data. 60 | /// 61 | /// - Parameter data: The data to create the persistent model from. 62 | /// - Returns: The created persistent model. 63 | static func persistentModel(from data: DataType) -> PersistentModelType 64 | 65 | /// Synchronizes the persistent model with the provided data. 66 | /// 67 | /// - Parameters: 68 | /// - persistentModel: The persistent model to synchronize. 69 | /// - data: The data to synchronize the persistent model with. 70 | /// - Throws: Any errors that occur during the synchronization process. 71 | static func synchronize(_ persistentModel: PersistentModelType, with data: DataType) throws 72 | } 73 | 74 | extension CollectionSynchronizer { 75 | /// Synchronizes the difference between a collection of persistent models and a collection of data. 76 | /// 77 | /// - Parameters: 78 | /// - difference: The difference between the persistent models and the data. 79 | /// - modelContext: The model context to use for the synchronization. 80 | /// - Returns: The list of persistent models that were inserted. 81 | /// - Throws: Any errors that occur during the synchronization process. 82 | public static func synchronizeDifference( 83 | _ difference: CollectionDifference, 84 | using modelContext: ModelContext 85 | ) throws -> [PersistentModelType] { 86 | try modelContext.delete(difference.deleteSelectors) 87 | 88 | let modelsToInsert: [Model] = difference.inserts.map { model in 89 | modelContext.insert { 90 | Self.persistentModel(from: model) 91 | } 92 | } 93 | 94 | let inserted = try modelsToInsert.map { 95 | try modelContext.get($0) 96 | } 97 | 98 | let updateSelectors = difference.updates.map { 99 | Self.getSelector(from: $0) 100 | } 101 | 102 | let entriesToUpdate = try modelContext.fetch(for: updateSelectors) 103 | 104 | var dictionary = [ID: SynchronizationUpdate]() 105 | 106 | for file in difference.updates { 107 | let id = file[keyPath: Self.dataKey] 108 | assert(dictionary[id] == nil) 109 | dictionary[id] = SynchronizationUpdate(file: file) 110 | } 111 | 112 | for entry in entriesToUpdate { 113 | let id = entry[keyPath: Self.persistentModelKey] 114 | assert(dictionary[id] != nil) 115 | dictionary[id]?.entry = entry 116 | } 117 | 118 | for update in dictionary.values { 119 | guard let entry = update.entry, let file = update.file else { 120 | assertionFailure() 121 | continue 122 | } 123 | try Self.synchronize(entry, with: file) 124 | } 125 | 126 | return inserted 127 | } 128 | } 129 | #endif 130 | -------------------------------------------------------------------------------- /Sources/DataThespian/Synchronization/ModelDifferenceSynchronizer.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ModelDifferenceSynchronizer.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | import SwiftData 32 | /// A protocol that defines the requirements for a synchronizer that can synchronize model differences. 33 | public protocol ModelDifferenceSynchronizer: ModelSynchronizer { 34 | /// The type of synchronization difference used by this synchronizer. 35 | associatedtype SynchronizationDifferenceType: SynchronizationDifference 36 | where 37 | SynchronizationDifferenceType.DataType == DataType, 38 | SynchronizationDifferenceType.PersistentModelType == PersistentModelType 39 | 40 | /// Synchronizes the given synchronization difference with the database. 41 | /// 42 | /// - Parameters: 43 | /// - diff: The synchronization difference to be synchronized. 44 | /// - database: The database to be used for the synchronization. 45 | /// - Throws: An error that may occur during the synchronization process. 46 | static func synchronize( 47 | _ diff: SynchronizationDifferenceType, 48 | using database: any Database 49 | ) async throws 50 | } 51 | 52 | extension ModelDifferenceSynchronizer { 53 | /// Synchronizes the given model with the data using the database. 54 | /// 55 | /// - Parameters: 56 | /// - model: The model to be synchronized. 57 | /// - data: The data to be used for the synchronization. 58 | /// - database: The database to be used for the synchronization. 59 | /// - Throws: An error that may occur during the synchronization process. 60 | public static func synchronizeModel( 61 | _ model: Model, 62 | with data: DataType, 63 | using database: any Database 64 | ) async throws { 65 | let diff = try await database.get(for: .model(model)) { entry in 66 | SynchronizationDifferenceType.comparePersistentModel(entry, with: data) 67 | } 68 | 69 | return try await self.synchronize(diff, using: database) 70 | } 71 | } 72 | #endif 73 | -------------------------------------------------------------------------------- /Sources/DataThespian/Synchronization/ModelSynchronizer.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ModelSynchronizer.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import SwiftData 32 | 33 | /// A protocol that defines a model synchronizer. 34 | public protocol ModelSynchronizer { 35 | /// The type of the persistent model. 36 | associatedtype PersistentModelType: PersistentModel 37 | /// The type of the data to be synchronized. 38 | associatedtype DataType: Sendable 39 | 40 | /// Synchronizes the model with the provided data, using the specified database. 41 | /// 42 | /// - Parameters: 43 | /// - model: The model to be synchronized. 44 | /// - data: The data to be synchronized with the model. 45 | /// - database: The database to be used for the synchronization. 46 | /// - Throws: Any errors that may occur during the synchronization process. 47 | static func synchronizeModel( 48 | _ model: Model, 49 | with data: DataType, 50 | using database: any Database 51 | ) async throws 52 | } 53 | #endif 54 | -------------------------------------------------------------------------------- /Sources/DataThespian/Synchronization/SynchronizationDifference.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SynchronizationDifference.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | #if canImport(SwiftData) 31 | public import SwiftData 32 | 33 | /// A protocol that defines a synchronization difference between a persistent model and some data. 34 | public protocol SynchronizationDifference: Sendable { 35 | /// The type of the persistent model. 36 | associatedtype PersistentModelType: PersistentModel 37 | /// The type of the data. 38 | associatedtype DataType: Sendable 39 | 40 | /// Compares a persistent model with some data and returns a synchronization difference. 41 | /// 42 | /// - Parameters: 43 | /// - persistentModel: The persistent model to compare. 44 | /// - data: The data to compare. 45 | /// - Returns: The synchronization difference between the persistent model and the data. 46 | static func comparePersistentModel( 47 | _ persistentModel: PersistentModelType, 48 | with data: DataType 49 | ) -> Self 50 | } 51 | #endif 52 | -------------------------------------------------------------------------------- /Sources/DataThespian/ThespianLogging.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ThespianLogging.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion. 6 | // Copyright © 2025 BrightDigit. 7 | // 8 | // Permission is hereby granted, free of charge, to any person 9 | // obtaining a copy of this software and associated documentation 10 | // files (the “Software”), to deal in the Software without 11 | // restriction, including without limitation the rights to use, 12 | // copy, modify, merge, publish, distribute, sublicense, and/or 13 | // sell copies of the Software, and to permit persons to whom the 14 | // Software is furnished to do so, subject to the following 15 | // conditions: 16 | // 17 | // The above copyright notice and this permission notice shall be 18 | // included in all copies or substantial portions of the Software. 19 | // 20 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 21 | // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 22 | // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 23 | // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 24 | // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 25 | // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 26 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 27 | // OTHER DEALINGS IN THE SOFTWARE. 28 | // 29 | 30 | public import FelinePine 31 | 32 | /// Conforms to the `FelinePine.Loggable` protocol, where the `LoggingSystemType` is `ThespianLogging`. 33 | internal protocol Loggable: FelinePine.Loggable where Self.LoggingSystemType == ThespianLogging {} 34 | 35 | /// A logging system used in the `DataThespian` application. 36 | @_documentation(visibility: internal) 37 | public enum ThespianLogging: LoggingSystem { 38 | /// Represents the different logging categories used in the `ThespianLogging` system. 39 | public enum Category: String, CaseIterable { 40 | /// Logs related to the application. 41 | case application 42 | /// Logs related to data. 43 | case data 44 | } 45 | 46 | /// Default subsystem to use for logging. 47 | public static var subsystem: String { 48 | "DataThespian" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Tests/DataThespianTests/Child.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Child.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion on 1/7/25. 6 | // 7 | 8 | #if canImport(SwiftData) 9 | import Foundation 10 | import SwiftData 11 | 12 | @Model 13 | internal class Child { 14 | internal var id: UUID 15 | internal var parent: Parent? 16 | internal init(id: UUID) { 17 | self.id = id 18 | } 19 | } 20 | #endif 21 | -------------------------------------------------------------------------------- /Tests/DataThespianTests/DatabaseTests.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import Testing 3 | 4 | @testable import DataThespian 5 | 6 | #if canImport(SwiftData) 7 | import SwiftData 8 | #endif 9 | 10 | internal struct DatabaseTests { 11 | @Test(.enabled(if: swiftDataIsAvailable())) internal func withModelContext() async throws { 12 | #if canImport(SwiftData) 13 | let database = try TestingDatabase(for: Parent.self, Child.self) 14 | let parentID = UUID() 15 | try await database.withModelContext { context in 16 | context.insert(Parent(id: parentID)) 17 | try context.save() 18 | } 19 | 20 | let parentIDs = await database.fetch(for: .all(Parent.self)) { parents in 21 | parents.map(\.id) 22 | } 23 | 24 | #expect(parentIDs == [parentID]) 25 | #endif 26 | // Write your test here and use APIs like `#expect(...)` to check expected conditions. 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Tests/DataThespianTests/Parent.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Parent.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion on 1/7/25. 6 | // 7 | 8 | #if canImport(SwiftData) 9 | import Foundation 10 | import SwiftData 11 | 12 | @Model 13 | internal class Parent { 14 | internal var id: UUID 15 | internal init(id: UUID) { 16 | self.id = id 17 | } 18 | } 19 | #endif 20 | -------------------------------------------------------------------------------- /Tests/DataThespianTests/SwiftDataIsAvailable.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SwiftDataIsAvailable.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion on 1/7/25. 6 | // 7 | 8 | internal func swiftDataIsAvailable() -> Bool { 9 | #if canImport(SwiftData) 10 | true 11 | #else 12 | false 13 | #endif 14 | } 15 | -------------------------------------------------------------------------------- /Tests/DataThespianTests/TestingDatabase.swift: -------------------------------------------------------------------------------- 1 | // 2 | // TestingDatabase.swift 3 | // DataThespian 4 | // 5 | // Created by Leo Dion on 1/7/25. 6 | // 7 | 8 | #if canImport(SwiftData) 9 | @testable import DataThespian 10 | import SwiftData 11 | 12 | @ModelActor 13 | internal actor TestingDatabase: Database { 14 | } 15 | 16 | extension TestingDatabase { 17 | internal init(for forTypes: any PersistentModel.Type...) throws { 18 | let container = try ModelContainer( 19 | for: .init(forTypes), 20 | configurations: .init(isStoredInMemoryOnly: true) 21 | ) 22 | self.init(modelContainer: container) 23 | } 24 | } 25 | #endif 26 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | ignore: 2 | - "Tests" 3 | -------------------------------------------------------------------------------- /macros.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "fingerprint" : "c55848b2aa4b29a4df542b235dfdd792a6fbe341", 4 | "packageIdentity" : "swift-testing", 5 | "targetName" : "TestingMacros" 6 | } 7 | ] -------------------------------------------------------------------------------- /project.yml: -------------------------------------------------------------------------------- 1 | name: DataThespian 2 | settings: 3 | LINT_MODE: ${LINT_MODE} 4 | packages: 5 | DataThespian: 6 | path: . 7 | aggregateTargets: 8 | Lint: 9 | buildScripts: 10 | - path: Scripts/lint.sh 11 | name: Lint 12 | basedOnDependencyAnalysis: false 13 | schemes: {} 14 | targets: 15 | DataThespianExample: 16 | type: application 17 | platform: macOS 18 | dependencies: 19 | - package: DataThespian 20 | product: DataThespian 21 | sources: 22 | - path: "Example/Sources" 23 | - path: "Example/Support" 24 | settings: 25 | base: 26 | PRODUCT_BUNDLE_IDENTIFIER: com.Demo.DataThespianExample 27 | SWIFT_STRICT_CONCURRENCY: complete 28 | SWIFT_UPCOMING_FEATURE_CONCISE_MAGIC_FILE: YES 29 | SWIFT_UPCOMING_FEATURE_DEPRECATE_APPLICATION_MAIN: YES 30 | SWIFT_UPCOMING_FEATURE_DISABLE_OUTWARD_ACTOR_ISOLATION: YES 31 | SWIFT_UPCOMING_FEATURE_EXISTENTIAL_ANY: YES 32 | SWIFT_UPCOMING_FEATURE_FORWARD_TRAILING_CLOSURES: YES 33 | SWIFT_UPCOMING_FEATURE_GLOBAL_CONCURRENCY: YES 34 | SWIFT_UPCOMING_FEATURE_IMPLICIT_OPEN_EXISTENTIALS: YES 35 | SWIFT_UPCOMING_FEATURE_IMPORT_OBJC_FORWARD_DECLS: YES 36 | SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES: YES 37 | SWIFT_UPCOMING_FEATURE_INTERNAL_IMPORTS_BY_DEFAULT: YES 38 | SWIFT_UPCOMING_FEATURE_ISOLATED_DEFAULT_VALUES: YES 39 | SWIFT_UPCOMING_FEATURE_REGION_BASED_ISOLATION: YES 40 | info: 41 | path: Example/Support/Info.plist 42 | properties: 43 | CFBundlePackageType: APPL 44 | ITSAppUsesNonExemptEncryption: false 45 | CFBundleShortVersionString: $(MARKETING_VERSION) 46 | CFBundleVersion: $(CURRENT_PROJECT_VERSION) --------------------------------------------------------------------------------