|
| 1 | +import Dependencies |
| 2 | +import DependenciesTestSupport |
| 3 | +import GRDB |
| 4 | +import Sharing |
| 5 | +import SharingGRDB |
| 6 | +import StructuredQueries |
| 7 | +import SwiftUI |
| 8 | +import Testing |
| 9 | + |
| 10 | +@Suite(.dependency(\.defaultDatabase, try .database())) |
| 11 | +struct FetchTests { |
| 12 | + @Test func bareFetchAll() async throws { |
| 13 | + @FetchAll var records: [Record] |
| 14 | + try await Task.sleep(nanoseconds: 100_000_000) |
| 15 | + #expect(records == [Record(id: 1), Record(id: 2), Record(id: 3)]) |
| 16 | + } |
| 17 | + |
| 18 | + @Test func fetchAllWithQuery() async throws { |
| 19 | + @FetchAll(Record.where { $0.id > 1 }) var records: [Record] |
| 20 | + try await Task.sleep(nanoseconds: 100_000_000) |
| 21 | + #expect(records == [Record(id: 2), Record(id: 3)]) |
| 22 | + } |
| 23 | + |
| 24 | + @Test func fetchCountWithQuery() async throws { |
| 25 | + @FetchOne(Record.where { $0.id > 1 }.count()) var recordsCount = 0 |
| 26 | + try await Task.sleep(nanoseconds: 100_000_000) |
| 27 | + #expect(recordsCount == 2) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +@Table |
| 32 | +private struct Record: Equatable { |
| 33 | + let id: Int |
| 34 | +} |
| 35 | +extension DatabaseWriter where Self == DatabaseQueue { |
| 36 | + fileprivate static func database() throws -> DatabaseQueue { |
| 37 | + let database = try DatabaseQueue() |
| 38 | + var migrator = DatabaseMigrator() |
| 39 | + migrator.registerMigration("Up") { db in |
| 40 | + try #sql( |
| 41 | + """ |
| 42 | + CREATE TABLE "records" ("id" INTEGER PRIMARY KEY AUTOINCREMENT) |
| 43 | + """ |
| 44 | + ) |
| 45 | + .execute(db) |
| 46 | + for _ in 1...3 { |
| 47 | + _ = try Record.insert(Record.Draft()).execute(db) |
| 48 | + } |
| 49 | + } |
| 50 | + try migrator.migrate(database) |
| 51 | + return database |
| 52 | + } |
| 53 | +} |
0 commit comments