axiom-sqlitedata-migration

0
0
Source

Use when migrating from SwiftData to SQLiteData — decision guide, pattern equivalents, code examples, CloudKit sharing (SwiftData can't), performance benchmarks, gradual migration strategy

Install

mkdir -p .claude/skills/axiom-sqlitedata-migration && curl -L -o skill.zip "https://mcp.directory/api/skills/download/6507" && unzip -o skill.zip -d .claude/skills/axiom-sqlitedata-migration && rm skill.zip

Installs to .claude/skills/axiom-sqlitedata-migration

About this skill

Migrating from SwiftData to SQLiteData

When to Switch

┌─────────────────────────────────────────────────────────┐
│ Should I switch from SwiftData to SQLiteData?           │
├─────────────────────────────────────────────────────────┤
│                                                         │
│  Performance problems with 10k+ records?                │
│    YES → SQLiteData (10-50x faster for large datasets)  │
│                                                         │
│  Need CloudKit record SHARING (not just sync)?          │
│    YES → SQLiteData (SwiftData cannot share records)    │
│                                                         │
│  Complex queries across multiple tables?                │
│    YES → SQLiteData + raw GRDB when needed              │
│                                                         │
│  Need Sendable models for Swift 6 concurrency?          │
│    YES → SQLiteData (value types, not classes)          │
│                                                         │
│  Testing @Model classes is painful?                     │
│    YES → SQLiteData (pure structs, easy to mock)        │
│                                                         │
│  Happy with SwiftData for simple CRUD?                  │
│    YES → Stay with SwiftData (simpler for basic apps)   │
│                                                         │
└─────────────────────────────────────────────────────────┘

Pattern Equivalents

SwiftDataSQLiteData
@Model class Item@Table nonisolated struct Item
@Attribute(.unique)@Column(primaryKey: true) or SQL UNIQUE
@Relationship var tags: [Tag]var tagIDs: [Tag.ID] + join query
@Query var items: [Item]@FetchAll var items: [Item]
@Query(sort: \.title)@FetchAll(Item.order(by: \.title))
@Query(filter: #Predicate { $0.isActive })@FetchAll(Item.where(\.isActive))
@Environment(\.modelContext)@Dependency(\.defaultDatabase)
context.insert(item)Item.insert { Item.Draft(...) }.execute(db)
context.delete(item)Item.find(id).delete().execute(db)
try context.save()Automatic in database.write { } block
ModelContainer(for:)prepareDependencies { $0.defaultDatabase = }

Code Example

SwiftData (Before)

import SwiftData

@Model
class Task {
    var id: UUID
    var title: String
    var isCompleted: Bool
    var project: Project?

    init(title: String) {
        self.id = UUID()
        self.title = title
        self.isCompleted = false
    }
}

struct TaskListView: View {
    @Environment(\.modelContext) private var context
    @Query(sort: \.title) private var tasks: [Task]

    var body: some View {
        List(tasks) { task in
            Text(task.title)
        }
    }

    func addTask(_ title: String) {
        let task = Task(title: title)
        context.insert(task)
    }

    func deleteTask(_ task: Task) {
        context.delete(task)
    }
}

SQLiteData (After)

import SQLiteData

@Table
nonisolated struct Task: Identifiable {
    let id: UUID
    var title = ""
    var isCompleted = false
    var projectID: Project.ID?
}

struct TaskListView: View {
    @Dependency(\.defaultDatabase) var database
    @FetchAll(Task.order(by: \.title)) var tasks

    var body: some View {
        List(tasks) { task in
            Text(task.title)
        }
    }

    func addTask(_ title: String) {
        try database.write { db in
            try Task.insert {
                Task.Draft(title: title)
            }
            .execute(db)
        }
    }

    func deleteTask(_ task: Task) {
        try database.write { db in
            try Task.find(task.id).delete().execute(db)
        }
    }
}

Key differences:

  • classstruct with nonisolated
  • @Model@Table
  • @Query@FetchAll
  • @Environment(\.modelContext)@Dependency(\.defaultDatabase)
  • Implicit save → Explicit database.write { } block
  • Direct init → .Draft type for inserts
  • @Relationship → Explicit foreign key + join

CloudKit Sharing (SwiftData Can't Do This)

SwiftData supports CloudKit sync but NOT sharing. SQLiteData is the only Apple-native option for record sharing.

// 1. Setup SyncEngine with sharing
prepareDependencies {
    $0.defaultDatabase = try! appDatabase()
    $0.defaultSyncEngine = try SyncEngine(
        for: $0.defaultDatabase,
        tables: Task.self, Project.self
    )
}

// 2. Share a record
@Dependency(\.defaultSyncEngine) var syncEngine
@State var sharedRecord: SharedRecord?

func shareProject(_ project: Project) async throws {
    sharedRecord = try await syncEngine.share(record: project) { share in
        share[CKShare.SystemFieldKey.title] = "Join my project!"
    }
}

// 3. Present native sharing UI
.sheet(item: $sharedRecord) { record in
    CloudSharingView(sharedRecord: record)
}

Sharing enables: Collaborative lists, shared workspaces, family sharing, team features.


Performance Comparison

OperationSwiftDataSQLiteDataImprovement
Insert 50k records~4 minutes~45 seconds5x
Query 10k with predicate~2 seconds~50ms40x
Memory (10k objects)~80MB~20MB4x smaller
Cold launch (large DB)~3 seconds~200ms15x

Benchmarks approximate, vary by device and data shape.


Migrating Existing User Data

Critical: Schema migration alone loses all user data. You must export from SwiftData and import into SQLiteData.

// 1. Read all records from SwiftData's backing store
func migrateExistingData(from modelContext: ModelContext, to database: any DatabaseWriter) throws {
    // Fetch all SwiftData records
    let descriptor = FetchDescriptor<SwiftDataTask>()
    let existingTasks = try modelContext.fetch(descriptor)

    // 2. Bulk insert into SQLiteData
    try database.write { db in
        for task in existingTasks {
            try SQLiteTask.insert {
                SQLiteTask.Draft(
                    id: task.id,
                    title: task.title,
                    isCompleted: task.isCompleted,
                    projectID: task.project?.id
                )
            }
            .execute(db)
        }
    }

    // 3. Verify migration
    let count = try database.read { db in
        try SQLiteTask.fetchCount(db)
    }
    assert(count == existingTasks.count, "Migration count mismatch!")
}

Migration checklist:

  • Export all models before deleting SwiftData container
  • Migrate relationships (fetch parent IDs for foreign keys)
  • Verify record counts match after migration
  • Keep SwiftData container as backup until confirmed working
  • Run migration on first launch with a version flag in UserDefaults

Gradual Migration Strategy

You don't have to migrate everything at once:

  1. Add SQLiteData for new features — Keep SwiftData for existing simple CRUD
  2. Migrate one model at a time — Start with the performance bottleneck
  3. Use separate databases initially — SQLiteData for heavy data/sharing, SwiftData for preferences
  4. Consolidate if needed — Or keep hybrid if it works

Common Gotchas

Relationships → Foreign Keys

// SwiftData: implicit relationship
@Relationship var tasks: [Task]

// SQLiteData: explicit column + query
// In child: var projectID: Project.ID
// To fetch: Task.where { $0.projectID.eq(#bind(project.id)) }

Cascade Deletes

// SwiftData: @Relationship(deleteRule: .cascade)

// SQLiteData: Define in SQL schema
// "REFERENCES parent(id) ON DELETE CASCADE"

No Automatic Inverse

// SwiftData: @Relationship(inverse: \Task.project)

// SQLiteData: Query both directions manually
let tasks = Task.where { $0.projectID.eq(#bind(project.id)) }
let project = Project.find(task.projectID)

Related Skills:

  • axiom-sqlitedata — Full SQLiteData API reference
  • axiom-swiftdata — SwiftData patterns if staying with Apple's framework
  • axiom-grdb — Raw GRDB for complex queries

History: See git log for changes

axiom-ios-build

CharlesWiltgen

Use when ANY iOS build fails, test crashes, Xcode misbehaves, or environment issue occurs before debugging code. Covers build failures, compilation errors, dependency conflicts, simulator problems, environment-first diagnostics.

91

axiom-getting-started

CharlesWiltgen

Use when first installing Axiom, unsure which skill to use, want an overview of available skills, or need help finding the right skill for your situation — interactive onboarding that recommends skills based on your project and current focus

00

axiom-ui-testing

CharlesWiltgen

Use when writing UI tests, recording interactions, tests have race conditions, timing dependencies, inconsistent pass/fail behavior, or XCTest UI tests are flaky - covers Recording UI Automation (WWDC 2025), condition-based waiting, network conditioning, multi-factor testing, crash debugging, and accessibility-first testing patterns

00

axiom-core-spotlight-ref

CharlesWiltgen

Use when indexing app content for Spotlight search, using NSUserActivity for prediction/handoff, or choosing between CSSearchableItem and IndexedEntity - covers Core Spotlight framework and NSUserActivity integration for iOS 9+

00

axiom-vision-diag

CharlesWiltgen

subject not detected, hand pose missing landmarks, low confidence observations, Vision performance, coordinate conversion, VisionKit errors, observation nil, text not recognized, barcode not detected, DataScannerViewController not working, document scan issues

00

axiom-now-playing-carplay

CharlesWiltgen

CarPlay Now Playing integration patterns. Use when implementing CarPlay audio controls, CPNowPlayingTemplate customization, or debugging CarPlay-specific issues.

00

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318399

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

340397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

452339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.