Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60beb7cd9c | ||
|
|
284a4ee1ac | ||
|
|
b27e378cfa | ||
|
|
459726f9af | ||
|
|
4f00e405c3 | ||
|
|
87f4d816e6 | ||
|
|
ea7ebe1ff5 | ||
|
|
89899432ba | ||
|
|
3a1c211746 | ||
|
|
c3664e2b16 | ||
|
|
ea1353bd6c | ||
|
|
4a5d4d6e49 | ||
|
|
c85abdba86 | ||
|
|
57aa4c30bf | ||
|
|
67b7941129 | ||
|
|
db01b0063c | ||
|
|
e1ddc8154f | ||
|
|
e637c156a2 | ||
|
|
60ad8a809a | ||
|
|
84ac401886 | ||
|
|
26b875f64c | ||
|
|
fdc8abfdbe | ||
|
|
fc641092f7 | ||
|
|
63d360053b | ||
|
|
dc440d5a8f | ||
|
|
5ab0d18055 | ||
|
|
437b800d8c | ||
|
|
b840babb55 | ||
|
|
725d4a3fba | ||
|
|
4ab8ac8d3f | ||
|
|
73b279b5c1 | ||
|
|
fa681fb8c6 | ||
|
|
cedcfbe330 | ||
|
|
abd3ba39b1 | ||
|
|
d66d2118b5 | ||
|
|
0a92a99223 | ||
|
|
19e5e62098 | ||
|
|
d948e37388 | ||
|
|
60de81633e | ||
|
|
c02139c045 | ||
|
|
93bd527984 | ||
|
|
157d02b55c | ||
|
|
82d28b3167 | ||
|
|
717c2836ec | ||
|
|
cf8fa0e5f8 | ||
|
|
84ef0a92da | ||
|
|
2ae000df43 | ||
|
|
738a187f68 | ||
|
|
4ff057ac3b | ||
|
|
0d49d7612f | ||
|
|
342b81f65e | ||
|
|
a651f34f67 | ||
|
|
5475dc98dc | ||
|
|
3692ba2293 | ||
|
|
266efa041c | ||
|
|
ebb2f7346d | ||
|
|
f955e5fabc | ||
|
|
65c803a110 | ||
|
|
8b1b3b0396 | ||
|
|
bf28d1bd85 | ||
|
|
45edf58f9e | ||
|
|
d07e8bd3a0 | ||
|
|
7feaa748a4 | ||
|
|
c159638498 | ||
|
|
5aa385094b | ||
|
|
1cd20176c6 | ||
|
|
06891e99e1 | ||
|
|
d5f38a6a24 | ||
|
|
68d23a5f33 | ||
|
|
75f92f6f14 | ||
|
|
6c70ee6b77 | ||
|
|
c8ae3cb61c | ||
|
|
dd4d3e35f3 | ||
|
|
7b2619e757 | ||
|
|
a7b9a27c51 | ||
|
|
fcfd6e9028 | ||
|
|
9011f71247 | ||
|
|
069bce217d | ||
|
|
5a91340671 | ||
|
|
ba2e3cb468 | ||
|
|
f633be4ba1 | ||
|
|
4074fcfcc7 | ||
|
|
18cdf4956e |
No files matched your search
@@ -7,6 +7,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
- `6.15.x` Releases - [6.15.0](#6150) - [6.15.1](#6151)
|
||||
- `6.14.x` Releases - [6.14.0](#6140)
|
||||
- `6.13.x` Releases - [6.13.0](#6130)
|
||||
- `6.12.x` Releases - [6.12.0](#6120)
|
||||
- `6.11.x` Releases - [6.11.0](#6110)
|
||||
- `6.10.x` Releases - [6.10.0](#6100) - [6.10.1](#6101) - [6.10.2](#6102)
|
||||
- `6.9.x` Releases - [6.9.0](#690) - [6.9.1](#691) - [6.9.2](#692)
|
||||
- `6.8.x` Releases - [6.8.0](#680)
|
||||
@@ -108,6 +113,51 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 6.15.1
|
||||
|
||||
Released June 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.0...v6.15.1)
|
||||
|
||||
- **Fixed**: Fixed Xcode 15 warnings
|
||||
- **Fixed**: [#1391](https://github.com/groue/GRDB.swift/pull/1391) Fix upsert in FTS5-synchronized tables
|
||||
|
||||
|
||||
## 6.15.0
|
||||
|
||||
Released June 2, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.14.0...v6.15.0)
|
||||
|
||||
- **New**: [#1382](https://github.com/groue/GRDB.swift/pull/1382) Add `DerivableRequest.all()`
|
||||
- **New**: [#1384](https://github.com/groue/GRDB.swift/pull/1384) Allow ValueObservation to start from a truncated wal file
|
||||
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
|
||||
|
||||
|
||||
## 6.14.0
|
||||
|
||||
Released May 25, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.13.0...v6.14.0)
|
||||
|
||||
- **New**: [#1376](https://github.com/groue/GRDB.swift/pull/1376) Bitwise operations
|
||||
- **New**: [#1379](https://github.com/groue/GRDB.swift/pull/1379) Create indexes with a default name
|
||||
|
||||
|
||||
## 6.13.0
|
||||
|
||||
Released May 15, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.12.0...v6.13.0)
|
||||
|
||||
- **New**: [#1373](https://github.com/groue/GRDB.swift/pull/1373) Deprecate string literal arguments for `TableDefinition.check()`
|
||||
|
||||
|
||||
## 6.12.0
|
||||
|
||||
Released April 29, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.11.0...v6.12.0)
|
||||
|
||||
- **Fixed**: [#1364](https://github.com/groue/GRDB.swift/pull/1364) Fix a regression introduced with version 6.10.0, where starting multiple observations while performing writes could create a deadlock.
|
||||
- **New**: `FetchableRecordDecoder` is an object that decodes `Decodable` fetchable records from database rows. You may want to use this decoder when you want to use the `Decodable` initializer from `init(row: Row)`.
|
||||
|
||||
## 6.11.0
|
||||
|
||||
Released April 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.2...v6.11.0)
|
||||
|
||||
- **New**: [#1361](https://github.com/groue/GRDB.swift/pull/1361) `DatabaseMigrator.eraseDatabaseOnSchemaChange` ignores internal schema objects
|
||||
|
||||
## 6.10.2
|
||||
|
||||
Released April 10, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.1...v6.10.2)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.10.2'
|
||||
s.version = '6.15.1'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -71,6 +71,7 @@
|
||||
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; };
|
||||
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
|
||||
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
|
||||
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; };
|
||||
@@ -458,6 +459,7 @@
|
||||
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
|
||||
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
|
||||
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
|
||||
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
|
||||
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
|
||||
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
|
||||
56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1056,6 +1058,7 @@
|
||||
563B06BF2185CD1700B38F35 /* ValueObservation */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */,
|
||||
560233C82724338800529DF3 /* SharedValueObservationTests.swift */,
|
||||
563B06F621861D8300B38F35 /* ValueObservationCountTests.swift */,
|
||||
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */,
|
||||
@@ -1733,6 +1736,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */,
|
||||
569BBA4622906A8200478429 /* InflectionsTests.json in Resources */,
|
||||
56D496C21D81374C008276D7 /* Betty.jpeg in Resources */,
|
||||
);
|
||||
|
||||
@@ -14,9 +14,14 @@
|
||||
extension RangeReplaceableCollection {
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
///
|
||||
/// // [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor)
|
||||
/// For example, you can turn a cursor of strings into an array
|
||||
/// of strings:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
public init(_ cursor: some Cursor<Element>) throws {
|
||||
@@ -26,9 +31,14 @@ extension RangeReplaceableCollection {
|
||||
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
///
|
||||
/// // [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor, minimumCapacity: 100)
|
||||
/// For example, you can turn a cursor of strings into an array
|
||||
/// of strings:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [String]
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Array(cursor, minimumCapacity: 100)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
/// - parameter minimumCapacity: Prepares the returned collection to store
|
||||
@@ -41,8 +51,8 @@ extension RangeReplaceableCollection {
|
||||
|
||||
/// Adds the elements of a cursor to the end of this collection.
|
||||
///
|
||||
/// In case of error, an unspecified amount of elements have been added to
|
||||
/// the collection.
|
||||
/// - Important: If an error is thrown, an unspecified amount of
|
||||
/// elements have been added to the collection.
|
||||
///
|
||||
/// - parameter newElements: The elements to append to the collection.
|
||||
public mutating func append(contentsOf newElements: some Cursor<Element>) throws {
|
||||
@@ -58,9 +68,13 @@ extension Dictionary {
|
||||
/// given closure and whose values are arrays of the elements that returned
|
||||
/// each key.
|
||||
///
|
||||
/// // [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to group into a dictionary.
|
||||
/// - parameter keyForValue: A closure that returns a key for each element
|
||||
@@ -81,12 +95,16 @@ extension Dictionary {
|
||||
/// given closure and whose values are arrays of the elements that returned
|
||||
/// each key.
|
||||
///
|
||||
/// // [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// grouping: cursor,
|
||||
/// by: { $0.teamID })
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db)
|
||||
/// let dictionary = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// grouping: cursor,
|
||||
/// by: { $0.teamID })
|
||||
/// ```
|
||||
///
|
||||
/// - parameter minimumCapacity: The minimum number of key-value pairs that
|
||||
/// the newly created dictionary should be able to store without
|
||||
@@ -112,9 +130,13 @@ extension Dictionary {
|
||||
/// of key-value tuples with unique keys. Passing a cursor with duplicate
|
||||
/// keys to this initializer results in a fatal error.
|
||||
///
|
||||
/// // [Int64: Player]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
|
||||
/// new dictionary. Every key in `keysAndValues` must be unique.
|
||||
@@ -137,11 +159,15 @@ extension Dictionary {
|
||||
/// of key-value tuples with unique keys. Passing a cursor with duplicate
|
||||
/// keys to this initializer results in a fatal error.
|
||||
///
|
||||
/// // [Int64: Player]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// uniqueKeysWithValues: cursor)
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a [Int64: [Player]]
|
||||
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
|
||||
/// let playerByID = try Dictionary(
|
||||
/// minimumCapacity: 100,
|
||||
/// uniqueKeysWithValues: cursor)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter minimumCapacity: The minimum number of key-value pairs that
|
||||
/// the newly created dictionary should be able to store without
|
||||
@@ -165,9 +191,13 @@ extension Dictionary {
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// // Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor)
|
||||
/// For example, you can turn a cursor of strings into a set of strings:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
public init(_ cursor: some Cursor<Element>) throws {
|
||||
@@ -180,9 +210,13 @@ extension Set {
|
||||
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// // Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor, minimumCapacity: 100)
|
||||
/// For example, you can turn a cursor of strings into a set of strings:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Create a Set<String>
|
||||
/// let cursor = try String.fetchCursor(db, ...)
|
||||
/// let strings = try Set(cursor, minimumCapacity: 100)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
/// - parameter minimumCapacity: The minimum number of elements that the
|
||||
@@ -240,6 +274,75 @@ extension Sequence {
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Iterating Over a Cursor’s Elements
|
||||
///
|
||||
/// - ``next()``
|
||||
/// - ``forEach(_:)-4ib2m``
|
||||
/// - ``enumerated()``
|
||||
/// - ``isEmpty``
|
||||
///
|
||||
/// ### Finding Elements
|
||||
///
|
||||
/// - ``contains(_:)``
|
||||
/// - ``contains(where:)``
|
||||
/// - ``first(where:)``
|
||||
/// - ``min()``
|
||||
/// - ``min(by:)``
|
||||
/// - ``max()``
|
||||
/// - ``max(by:)``
|
||||
///
|
||||
/// ### Selecting Elements
|
||||
///
|
||||
/// - ``prefix(_:)``
|
||||
/// - ``prefix(while:)``
|
||||
/// - ``suffix(_:)``
|
||||
///
|
||||
/// ### Excluding Elements
|
||||
///
|
||||
/// - ``dropFirst()``
|
||||
/// - ``dropFirst(_:)``
|
||||
/// - ``dropLast()``
|
||||
/// - ``dropLast(_:)``
|
||||
/// - ``drop(while:)``
|
||||
/// - ``filter(_:)``
|
||||
///
|
||||
/// ### Transforming a Cursor
|
||||
///
|
||||
/// - ``map(_:)``
|
||||
/// - ``compactMap(_:)``
|
||||
/// - ``flatMap(_:)-5ci2v``
|
||||
/// - ``flatMap(_:)-8jxlj``
|
||||
/// - ``reduce(_:_:)``
|
||||
/// - ``reduce(into:_:)``
|
||||
///
|
||||
/// ### Transforming a Sequence into a Cursor
|
||||
///
|
||||
/// - ``Swift/Sequence/flatMap(_:)``
|
||||
///
|
||||
/// ### Joining Elements
|
||||
///
|
||||
/// - ``joined()-5r5ja``
|
||||
/// - ``joined()-7bnrx``
|
||||
/// - ``joined(separator:)``
|
||||
///
|
||||
/// ### Filling RangeReplaceableCollection with the contents of a Cursor
|
||||
///
|
||||
/// - ``Swift/RangeReplaceableCollection/init(_:)``
|
||||
/// - ``Swift/RangeReplaceableCollection/init(_:minimumCapacity:)``
|
||||
/// - ``Swift/RangeReplaceableCollection/append(contentsOf:)``
|
||||
///
|
||||
/// ### Creating a Dictionary from the contents of a Cursor
|
||||
///
|
||||
/// - ``Swift/Dictionary/init(grouping:by:)``
|
||||
/// - ``Swift/Dictionary/init(minimumCapacity:grouping:by:)``
|
||||
/// - ``Swift/Dictionary/init(uniqueKeysWithValues:)``
|
||||
/// - ``Swift/Dictionary/init(minimumCapacity:uniqueKeysWithValues:)``
|
||||
///
|
||||
/// ### Creating a Set from the contents of a Cursor
|
||||
///
|
||||
/// - ``Swift/Set/init(_:)``
|
||||
/// - ``Swift/Set/init(_:minimumCapacity:)``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyCursor``
|
||||
@@ -269,7 +372,7 @@ extension Cursor {
|
||||
/// Returns a Boolean value indicating whether the cursor does not contain
|
||||
/// any element.
|
||||
///
|
||||
/// - important: This property may consume elements.
|
||||
/// - important: This property consumes an element.
|
||||
public var isEmpty: Bool {
|
||||
get throws { try next() == nil }
|
||||
}
|
||||
@@ -294,13 +397,17 @@ extension Cursor {
|
||||
/// Returns a cursor of pairs (n, x), where n represents a consecutive
|
||||
/// integer starting at zero, and x represents an element of the cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
/// ```swift
|
||||
/// let cursor = try String.fetchCursor(db, sql: """
|
||||
/// SELECT 'foo' UNION ALL SELECT 'bar'
|
||||
/// """)
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
/// ```
|
||||
public func enumerated() -> EnumeratedCursor<Self> {
|
||||
EnumeratedCursor(self)
|
||||
}
|
||||
@@ -346,11 +453,13 @@ extension Cursor {
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the cursor, the result is an empty cursor.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst(2))
|
||||
/// // Prints "[3, 4, 5]"
|
||||
/// try print(numbers.dropFirst(10))
|
||||
/// // Prints "[]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst(2))
|
||||
/// // Prints "[3, 4, 5]"
|
||||
/// try print(numbers.dropFirst(10))
|
||||
/// // Prints "[]"
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop from the beginning of
|
||||
/// the cursor. `n` must be greater than or equal to zero.
|
||||
@@ -364,9 +473,11 @@ extension Cursor {
|
||||
///
|
||||
/// The following example drops the first element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst())
|
||||
/// // Prints "[2, 3, 4, 5]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst())
|
||||
/// // Prints "[2, 3, 4, 5]"
|
||||
/// ```
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
@@ -381,11 +492,13 @@ extension Cursor {
|
||||
/// The cursor must be finite. If the number of elements to drop exceeds
|
||||
/// the number of elements in the cursor, the result is an empty array.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast(2))
|
||||
/// // Prints "[1, 2, 3]"
|
||||
/// try print(numbers.dropLast(10))
|
||||
/// // Prints "[]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast(2))
|
||||
/// // Prints "[1, 2, 3]"
|
||||
/// try print(numbers.dropLast(10))
|
||||
/// // Prints "[]"
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop off the end of the
|
||||
/// cursor. `n` must be greater than or equal to zero.
|
||||
@@ -414,9 +527,11 @@ extension Cursor {
|
||||
///
|
||||
/// The following example drops the last element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast())
|
||||
/// // Prints "[1, 2, 3, 4]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast())
|
||||
/// // Prints "[1, 2, 3, 4]"
|
||||
/// ```
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
@@ -502,11 +617,13 @@ extension Cursor {
|
||||
/// If the maximum length exceeds the number of elements in the cursor,
|
||||
/// the result contains all the elements in the cursor.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.prefix(2))
|
||||
/// // Prints "[1, 2]"
|
||||
/// try print(numbers.prefix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.prefix(2))
|
||||
/// // Prints "[1, 2]"
|
||||
/// try print(numbers.prefix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
/// value of `maxLength` must be greater than or equal to zero.
|
||||
@@ -562,11 +679,13 @@ extension Cursor {
|
||||
/// elements in the cursor, the result contains all the elements in the
|
||||
/// cursor.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.suffix(2))
|
||||
/// // Prints "[4, 5]"
|
||||
/// try print(numbers.suffix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
/// ```swift
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.suffix(2))
|
||||
/// // Prints "[4, 5]"
|
||||
/// try print(numbers.suffix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
/// value of `maxLength` must be greater than or equal to zero.
|
||||
@@ -620,24 +739,16 @@ extension Cursor where Element: Equatable {
|
||||
extension Cursor where Element: Comparable {
|
||||
/// Returns the maximum element in the cursor.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's maximum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
/// - Returns: The cursor's maximum element. If the cursor has no
|
||||
/// elements, returns `nil`.
|
||||
public func max() throws -> Element? {
|
||||
try max(by: <)
|
||||
}
|
||||
|
||||
/// Returns the minimum element in the cursor.
|
||||
///
|
||||
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
|
||||
/// if its first argument should be ordered before its second
|
||||
/// argument; otherwise, `false`.
|
||||
/// - Returns: The cursor's minimum element, according to
|
||||
/// `areInIncreasingOrder`. If the cursor has no elements, returns
|
||||
/// `nil`.
|
||||
/// - Returns: The cursor's minimum element. If the cursor has no
|
||||
/// elements, returns `nil`.
|
||||
public func min() throws -> Element? {
|
||||
try min(by: <)
|
||||
}
|
||||
|
||||
@@ -1313,11 +1313,33 @@ struct TableInfo: FetchableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
enum SchemaObjectType: String {
|
||||
case index
|
||||
case table
|
||||
case trigger
|
||||
case view
|
||||
/// A value in the `type` column of `sqlite_master`.
|
||||
struct SchemaObjectType: Hashable, RawRepresentable, DatabaseValueConvertible {
|
||||
var rawValue: String
|
||||
init(rawValue: String) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
static let index = SchemaObjectType(rawValue: "index")
|
||||
static let table = SchemaObjectType(rawValue: "table")
|
||||
static let trigger = SchemaObjectType(rawValue: "trigger")
|
||||
static let view = SchemaObjectType(rawValue: "view")
|
||||
}
|
||||
|
||||
/// A row in `sqlite_master`.
|
||||
struct SchemaObject: Hashable, FetchableRecord {
|
||||
var type: SchemaObjectType
|
||||
var name: String
|
||||
var tbl_name: String?
|
||||
var sql: String?
|
||||
|
||||
init(row: Row) throws {
|
||||
// "rootpage" column is not always there: avoid using numerical indexes
|
||||
type = row["type"]
|
||||
name = row["name"]
|
||||
tbl_name = row["tbl_name"]
|
||||
sql = row["sql"]
|
||||
}
|
||||
}
|
||||
|
||||
/// All objects in a database schema (tables, views, indexes, triggers).
|
||||
@@ -1328,7 +1350,6 @@ struct SchemaInfo: Equatable {
|
||||
/// (case-insensitive).
|
||||
func containsObjectNamed(_ name: String, ofType type: SchemaObjectType) -> Bool {
|
||||
let name = name.lowercased()
|
||||
let type = type.rawValue
|
||||
return objects.contains {
|
||||
$0.type == type && $0.name.lowercased() == name
|
||||
}
|
||||
@@ -1341,15 +1362,12 @@ struct SchemaInfo: Equatable {
|
||||
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
|
||||
let name = name.lowercased()
|
||||
return objects
|
||||
.first { $0.type == type.rawValue && $0.name.lowercased() == name }?
|
||||
.first { $0.type == type && $0.name.lowercased() == name }?
|
||||
.name
|
||||
}
|
||||
|
||||
private struct SchemaObject: Codable, Hashable, FetchableRecord {
|
||||
var type: String
|
||||
var name: String
|
||||
var tbl_name: String?
|
||||
var sql: String?
|
||||
func filter(_ isIncluded: (SchemaObject) -> Bool) -> Self {
|
||||
SchemaInfo(objects: objects.filter(isIncluded))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -94,6 +94,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``add(tokenizer:)``
|
||||
/// - ``backup(to:pagesPerStep:progress:)``
|
||||
/// - ``checkpoint(_:on:)``
|
||||
/// - ``clearSchemaCache()``
|
||||
|
||||
@@ -84,12 +84,20 @@ public final class DatabasePool {
|
||||
// > Many applications choose NORMAL when in WAL mode
|
||||
try db.execute(sql: "PRAGMA synchronous = NORMAL")
|
||||
|
||||
if !FileManager.default.fileExists(atPath: path + "-wal") {
|
||||
// Create the -wal file if it does not exist yet. This
|
||||
// avoids an SQLITE_CANTOPEN (14) error whenever a user
|
||||
// opens a pool to an existing non-WAL database, and
|
||||
// attempts to read from it.
|
||||
// See https://github.com/groue/GRDB.swift/issues/102
|
||||
// Make sure a non-empty wal file exists.
|
||||
//
|
||||
// The presence of the wal file avoids an SQLITE_CANTOPEN (14)
|
||||
// error when the user opens a pool and reads from it.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/102>.
|
||||
//
|
||||
// The non-empty wal file avoids an SQLITE_ERROR (1) error
|
||||
// when the user opens a pool and creates a wal snapshot
|
||||
// (which happens when starting a ValueObservation).
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1383>.
|
||||
let walPath = path + "-wal"
|
||||
if try FileManager.default.fileExists(atPath: walPath) == false
|
||||
|| (URL(fileURLWithPath: walPath).resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0
|
||||
{
|
||||
try db.inSavepoint {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
|
||||
@@ -900,9 +908,11 @@ extension DatabasePool {
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
|
||||
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html), or
|
||||
/// if this method is called from a database access where a write
|
||||
/// transaction is open.
|
||||
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
|
||||
/// or if this method is called from a write transaction, or if the
|
||||
/// wal file is missing or truncated (size zero).
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
public func makeSnapshotPool() throws -> DatabaseSnapshotPool {
|
||||
try unsafeReentrantRead { db in
|
||||
try DatabaseSnapshotPool(db)
|
||||
|
||||
@@ -108,12 +108,10 @@ public final class DatabaseSnapshotPool {
|
||||
/// assert(count == 0)
|
||||
/// ```
|
||||
///
|
||||
/// If any of the following statements are false when the snapshot is
|
||||
/// created, a ``DatabaseError`` of code `SQLITE_ERROR` is thrown:
|
||||
///
|
||||
/// - The database connection must be in the
|
||||
/// [WAL mode](https://www.sqlite.org/wal.html).
|
||||
/// - There must not be a write transaction open.
|
||||
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
|
||||
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
|
||||
/// or if this method is called from a write transaction, or if the
|
||||
/// wal file is missing or truncated (size zero).
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
///
|
||||
@@ -175,9 +173,9 @@ public final class DatabaseSnapshotPool {
|
||||
/// let snapshot = try DatabaseSnapshotPool(path: "/path/to/database.sqlite")
|
||||
/// ```
|
||||
///
|
||||
/// If the database at `path` is not in the
|
||||
/// [WAL mode](https://www.sqlite.org/wal.html), a ``DatabaseError`` of code
|
||||
/// `SQLITE_ERROR` is thrown.
|
||||
/// A ``DatabaseError`` of code `SQLITE_ERROR` is thrown if the SQLite
|
||||
/// database is not in the [WAL mode](https://www.sqlite.org/wal.html),
|
||||
/// or if the wal file is missing or truncated (size zero).
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
///
|
||||
|
||||
@@ -468,7 +468,7 @@ extension DatabaseWriter {
|
||||
|
||||
// MARK: - Erasing the content of the database
|
||||
|
||||
/// Erases the content of the database.
|
||||
/// Erase the database: delete all content, drop all tables, etc.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func erase() throws {
|
||||
try barrierWriteWithoutTransaction { try $0.erase() }
|
||||
@@ -687,7 +687,7 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
/// Erases the content of the database.
|
||||
/// Erase the database: delete all content, drop all tables, etc.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
|
||||
@@ -58,10 +58,6 @@
|
||||
/// - ``makePreparedRequest(_:forSingleResult:)``
|
||||
/// - ``PreparedRequest``
|
||||
///
|
||||
/// ### Database Observation Support
|
||||
///
|
||||
/// - ``databaseRegion(_:)``
|
||||
///
|
||||
/// ### Adapting the Fetched Rows
|
||||
///
|
||||
/// - ``adapted(_:)``
|
||||
@@ -217,8 +213,8 @@ public struct AnyFetchRequest<RowDecoder> {
|
||||
///
|
||||
/// // AnyFetchRequest<Row>
|
||||
/// let rowRequest = playerRequest.asRequest(of: Row.self)
|
||||
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> AnyFetchRequest<RowDecoder> {
|
||||
AnyFetchRequest<RowDecoder>(request: request)
|
||||
public func asRequest<T>(of type: T.Type) -> AnyFetchRequest<T> {
|
||||
AnyFetchRequest<T>(request: request)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,8 @@
|
||||
///
|
||||
/// - ``append(literal:)``
|
||||
/// - ``append(sql:arguments:)``
|
||||
/// - ``Swift/Collection/joined(separator:)``
|
||||
/// - ``Swift/Sequence/joined(separator:)``
|
||||
public struct SQL {
|
||||
/// `SQL.Element` is a component of an `SQL` literal.
|
||||
///
|
||||
@@ -316,12 +318,12 @@ extension SQL: SQLOrderingTerm {
|
||||
}
|
||||
|
||||
extension Sequence where Element == SQL {
|
||||
/// Returns the concatenated `SQL` literal of this sequence of literals,
|
||||
/// Concatenates the sequence elements into a new `SQL` literal,
|
||||
/// inserting the given raw SQL separator between each element.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```
|
||||
/// ```swift
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
@@ -341,7 +343,7 @@ extension Sequence where Element == SQL {
|
||||
}
|
||||
|
||||
extension Collection where Element == SQL {
|
||||
/// Returns the concatenated `SQL` literal of this collection of literals,
|
||||
/// Concatenates the collection elements into a new `SQL` literal,
|
||||
/// inserting the given raw SQL separator between each element.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -89,7 +89,7 @@ public protocol StatementColumnConvertible {
|
||||
///
|
||||
/// Do not check for `NULL` in your implementation of this method. Null
|
||||
/// database values are handled
|
||||
/// in ``fromStatement(_:atUncheckedIndex:)-2i8y6``.
|
||||
/// in ``StatementColumnConvertible/fromStatement(_:atUncheckedIndex:)-2i8y6``.
|
||||
///
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if canImport(CoreGraphics)
|
||||
import CoreGraphics
|
||||
|
||||
/// CGFloat adopts DatabaseValueConvertible
|
||||
/// `CGFloat` is a database value.
|
||||
extension CGFloat: DatabaseValueConvertible {
|
||||
/// Returns a REAL database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// Data is convertible to and from DatabaseValue.
|
||||
/// `Data` is a database value.
|
||||
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSDate is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
/// `NSDate` is a database value.
|
||||
extension NSDate: DatabaseValueConvertible {
|
||||
/// Returns a TEXT database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
@@ -31,8 +30,6 @@ extension NSDate: DatabaseValueConvertible {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension Date: DatabaseValueConvertible {
|
||||
/// Returns a TEXT database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
@@ -115,6 +112,7 @@ extension Date: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// `Date` is a database value.
|
||||
extension Date: StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// Decimal adopts DatabaseValueConvertible
|
||||
/// `Decimal` is a database value.
|
||||
extension Decimal: DatabaseValueConvertible {
|
||||
/// Returns a TEXT decimal value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
/// `NSData` is a database value.
|
||||
extension NSData: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a BLOB database value.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// NSNull adopts DatabaseValueConvertible
|
||||
/// `NSDate` is a database value.
|
||||
extension NSNull: DatabaseValueConvertible {
|
||||
|
||||
/// Returns the NULL database value.
|
||||
|
||||
@@ -9,7 +9,7 @@ private let integerRoundingBehavior = NSDecimalNumberHandler(
|
||||
raiseOnUnderflow: false,
|
||||
raiseOnDivideByZero: false)
|
||||
|
||||
/// NSNumber adopts DatabaseValueConvertible
|
||||
/// `NSNumber` is a database value.
|
||||
extension NSNumber: DatabaseValueConvertible {
|
||||
|
||||
/// A database value.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSString adopts DatabaseValueConvertible
|
||||
/// `NSString` is a database value.
|
||||
extension NSString: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a TEXT database value.
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
/// `NSURL` is a database value.
|
||||
///
|
||||
/// `NSURL` stores its `absoluteString` in the database.
|
||||
extension NSURL: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a TEXT database value containing the absolute URL.
|
||||
@@ -18,5 +20,7 @@ extension NSURL: DatabaseValueConvertible {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// URL stores its absoluteString in the database.
|
||||
/// `URL` is a database value.
|
||||
///
|
||||
/// `URL` stores its `absoluteString` in the database.
|
||||
extension URL: DatabaseValueConvertible { }
|
||||
@@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
/// `NSUUID` is a database value.
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
public var databaseValue: DatabaseValue {
|
||||
@@ -35,7 +35,7 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// UUID adopts DatabaseValueConvertible
|
||||
/// `UUID` is a database value.
|
||||
extension UUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
public var databaseValue: DatabaseValue {
|
||||
|
||||
@@ -44,6 +44,7 @@ extension Optional: SQLSelectable where Wrapped: SQLSelectable {
|
||||
|
||||
extension Optional: SQLSpecificExpressible where Wrapped: SQLSpecificExpressible { }
|
||||
|
||||
/// `Optional` is a database value when it wrapped type is.
|
||||
extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
switch self {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// MARK: - Value Types
|
||||
|
||||
/// Bool adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Bool` is a database value.
|
||||
extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -95,7 +95,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int` is a database value.
|
||||
extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -134,7 +134,7 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int8` is a database value.
|
||||
extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -173,7 +173,7 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int16` is a database value.
|
||||
extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -212,7 +212,7 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int32` is a database value.
|
||||
extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -251,7 +251,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Int64` is a database value.
|
||||
extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -294,7 +294,7 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt` is a database value.
|
||||
extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -333,7 +333,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt8` is a database value.
|
||||
extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -372,7 +372,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt16` is a database value.
|
||||
extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -411,7 +411,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt32` is a database value.
|
||||
extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -450,7 +450,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `UInt64` is a database value.
|
||||
extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -489,7 +489,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Double` is a database value.
|
||||
extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -529,7 +529,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Float adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `Float` is a database value.
|
||||
extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
@@ -569,7 +569,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// String adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
/// `String` is a database value.
|
||||
extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
|
||||
@@ -30,11 +30,30 @@ final class WALSnapshot: Sendable {
|
||||
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
// <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
//
|
||||
// > The following must be true for sqlite3_snapshot_get() to succeed. [...]
|
||||
// >
|
||||
// > 1. The database handle must not be in autocommit mode.
|
||||
// > 2. Schema S of database connection D must be a WAL
|
||||
// > mode database.
|
||||
// > 3. There must not be a write transaction open on schema S
|
||||
// > of database connection D.
|
||||
// > 4. One or more transactions must have been written to the
|
||||
// > current wal file since it was created on disk (by any
|
||||
// > connection). This means that a snapshot cannot be taken
|
||||
// > on a wal mode database with no wal file immediately
|
||||
// > after it is first opened. At least one transaction must
|
||||
// > be written to it first.
|
||||
|
||||
// Test condition 1:
|
||||
if sqlite3_get_autocommit(db.sqliteConnection) != 0 {
|
||||
throw DatabaseError(resultCode: code, message: """
|
||||
Can't create snapshot because database is in autocommit mode.
|
||||
""")
|
||||
}
|
||||
|
||||
// Test condition 2:
|
||||
if let journalMode = try? String.fetchOne(db, sql: "PRAGMA journal_mode"),
|
||||
journalMode != "wal"
|
||||
{
|
||||
@@ -42,7 +61,14 @@ final class WALSnapshot: Sendable {
|
||||
Can't create snapshot because database is not in WAL mode.
|
||||
""")
|
||||
}
|
||||
throw DatabaseError(resultCode: code)
|
||||
|
||||
// Condition 3 can't happen because GRDB only calls this
|
||||
// initializer from read transactions.
|
||||
//
|
||||
// Hence it is condition 4 that is false:
|
||||
throw DatabaseError(resultCode: code, message: """
|
||||
Can't create snapshot from a missing or empty wal file.
|
||||
""")
|
||||
}
|
||||
guard let sqliteSnapshot else {
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
|
||||
@@ -14,7 +14,7 @@ The other chapters cover, with more details, the fundamentals of SQLite concurre
|
||||
|
||||
**The two concurrency rules are strongly recommended practices.** They are all about SQLite, a robust and reliable database that takes great care of your data: don't miss an opportunity to put it on your side!
|
||||
|
||||
### Rule 1: Connect to any database file only once
|
||||
#### Rule 1: Connect to any database file only once
|
||||
|
||||
Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the whole duration of your use of the database. Not for the duration of _each_ database access, but really for the duration of _all_ database accesses to this file.
|
||||
|
||||
@@ -27,7 +27,7 @@ Open one single ``DatabaseQueue`` or ``DatabasePool`` per database file, for the
|
||||
- You will not be able to use the <doc:DatabaseObservation> features.
|
||||
- You will see SQLite errors ([`SQLITE_BUSY`]).
|
||||
|
||||
### Rule 2: Mind your transactions
|
||||
#### Rule 2: Mind your transactions
|
||||
|
||||
Database operations that are grouped in a transaction are guaranteed to be either fully saved on disk, or not at all. Read-only transactions guarantee a stable and immutable view of the database, and do not see changes performed by eventual concurrent writes.
|
||||
|
||||
@@ -150,31 +150,31 @@ This prevents the database operations from various concurrent accesses from bein
|
||||
|
||||
**You will generally use the safe database access methods `read` and `write`.** In this context, "safe" means that a database access is concurrency-friendly, because GRDB provides the following guarantees:
|
||||
|
||||
### Serialized Writes
|
||||
#### Serialized Writes
|
||||
|
||||
**All writes performed by one ``DatabaseQueue`` or ``DatabasePool`` instance are serialized.**
|
||||
|
||||
This guarantee prevents [`SQLITE_BUSY`] errors during concurrent writes.
|
||||
|
||||
### Write Transactions
|
||||
#### Write Transactions
|
||||
|
||||
**All writes are wrapped in a transaction.**
|
||||
|
||||
Concurrent reads can not see partial database updates (even reads performed by other processes).
|
||||
|
||||
### Isolated Reads
|
||||
#### Isolated Reads
|
||||
|
||||
**All reads are wrapped in a transaction.**
|
||||
|
||||
An isolated read sees a stable and immutable state of the database, and does not see changes performed by eventual concurrent writes (even writes performed by other processes). See [Isolation In SQLite](https://www.sqlite.org/isolation.html) for more information.
|
||||
|
||||
### Forbidden Writes
|
||||
#### Forbidden Writes
|
||||
|
||||
**Inside a read access, all attempts to write raise an error.**
|
||||
|
||||
This enforces the immutability of the database during a read.
|
||||
|
||||
### Non-Reentrancy
|
||||
#### Non-Reentrancy
|
||||
|
||||
**Database accesses methods are not reentrant.**
|
||||
|
||||
|
||||
@@ -249,8 +249,8 @@ try db.create(table: "player") { t in
|
||||
|
||||
// One single player at any given position in a team
|
||||
try db.create(
|
||||
index: "playerTeamPosition",
|
||||
on: "player", columns: ["teamId", "position"],
|
||||
indexOn: "player",
|
||||
columns: ["teamId", "position"],
|
||||
options: .unique)
|
||||
```
|
||||
|
||||
@@ -268,10 +268,7 @@ try db.create(
|
||||
> try db.create(table: "team") { t in
|
||||
> t.column("name", .text)
|
||||
> }
|
||||
> try db.create(
|
||||
> index: "teamName",
|
||||
> on: "team", columns: ["name"],
|
||||
> options: .unique)
|
||||
> try db.create(indexOn: "team", columns: ["name"], options: .unique)
|
||||
> ```
|
||||
>
|
||||
> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See <doc:Migrations> for the detailed procedure.
|
||||
@@ -365,6 +362,7 @@ extension Team: TableRecord {
|
||||
- ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
- ``Database/drop(table:)``
|
||||
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
|
||||
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
|
||||
- ``Database/rename(table:to:)``
|
||||
- ``Database/ColumnType``
|
||||
- ``Database/ConflictResolution``
|
||||
@@ -376,7 +374,9 @@ extension Team: TableRecord {
|
||||
|
||||
### Database Indexes
|
||||
|
||||
- ``Database/create(indexOn:columns:options:condition:)``
|
||||
- ``Database/create(index:on:columns:options:condition:)``
|
||||
- ``Database/drop(indexOn:columns:)``
|
||||
- ``Database/drop(index:)``
|
||||
- ``IndexOptions``
|
||||
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
# ``GRDB``
|
||||
|
||||
A toolkit for SQLite databases, with a focus on application development
|
||||
|
||||
## Overview
|
||||
|
||||
Use GRDB to save your application’s permanent data into SQLite databases.
|
||||
|
||||
The library provides raw access to SQL and advanced SQLite features, because one sometimes enjoys a sharp tool.
|
||||
|
||||
It has robust concurrency primitives, so that multi-threaded applications can efficiently use their databases.
|
||||
|
||||
It grants your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to.
|
||||
|
||||
Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMDB](https://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications.
|
||||
|
||||
## Topics
|
||||
|
||||
### Fundamentals
|
||||
|
||||
- <doc:DatabaseConnections>
|
||||
- <doc:SQLSupport>
|
||||
- <doc:Concurrency>
|
||||
- <doc:Transactions>
|
||||
|
||||
### Migrations and The Database Schema
|
||||
|
||||
- <doc:DatabaseSchema>
|
||||
- <doc:Migrations>
|
||||
|
||||
### Records and the Query Interface
|
||||
|
||||
- <doc:QueryInterface>
|
||||
- <doc:RecordRecommendedPractices>
|
||||
- <doc:RecordTimestamps>
|
||||
- <doc:SingleRowTables>
|
||||
|
||||
### Responding to Database Changes
|
||||
|
||||
- <doc:DatabaseObservation>
|
||||
|
||||
### Full-Text Search
|
||||
|
||||
- <doc:FullTextSearch>
|
||||
|
||||
### Combine Publishers
|
||||
|
||||
- ``DatabasePublishers``
|
||||
@@ -165,6 +165,38 @@ This extra conformance is not required: only aim at the low-level C interface if
|
||||
- ``fetchSet(_:_:)-1foke``
|
||||
- ``fetchOne(_:_:)-o6yj``
|
||||
|
||||
### Supported Value Types
|
||||
|
||||
- ``Swift/Bool``
|
||||
- ``CoreFoundation/CGFloat``
|
||||
- ``Foundation/Data``
|
||||
- ``DatabaseDateComponents``
|
||||
- ``Foundation/Date``
|
||||
- ``Swift/Double``
|
||||
- ``Foundation/Decimal``
|
||||
- ``Swift/Float``
|
||||
- ``Swift/Int``
|
||||
- ``Swift/Int8``
|
||||
- ``Swift/Int16``
|
||||
- ``Swift/Int32``
|
||||
- ``Swift/Int64``
|
||||
- ``Foundation/NSData``
|
||||
- ``Foundation/NSDate``
|
||||
- ``Foundation/NSNull``
|
||||
- ``Foundation/NSNumber``
|
||||
- ``Foundation/NSString``
|
||||
- ``Foundation/NSURL``
|
||||
- ``Foundation/NSUUID``
|
||||
- ``Swift/Optional``
|
||||
- ``Swift/UInt``
|
||||
- ``Swift/UInt8``
|
||||
- ``Swift/UInt16``
|
||||
- ``Swift/UInt32``
|
||||
- ``Swift/UInt64``
|
||||
- ``Swift/String``
|
||||
- ``Foundation/URL``
|
||||
- ``Foundation/UUID``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseValueCursor``
|
||||
|
||||
@@ -159,7 +159,7 @@ let cancellable = try sharedObservation
|
||||
|
||||
While the standard ``tracking(_:)`` method lets you track changes to a fetched value and receive any changes to it, sometimes your use case might require more granular control.
|
||||
|
||||
Consider a scenario where you'd like to get a specific Player's row, but only when their `score` column changes. You can use ``tracking(region:fetch:)`` to do just that:
|
||||
Consider a scenario where you'd like to get a specific Player's row, but only when their `score` column changes. You can use ``tracking(region:_:fetch:)`` to do just that:
|
||||
|
||||
```swift
|
||||
let observation = ValueObservation.tracking(
|
||||
@@ -172,7 +172,7 @@ let observation = ValueObservation.tracking(
|
||||
)
|
||||
```
|
||||
|
||||
This ``tracking(region:fetch:)`` method lets you entirely separate the **observed region** from the **fetched value** itself, for maximum flexibility. See ``DatabaseRegionConvertible`` for more information about the regions that can be tracked.
|
||||
This ``tracking(region:_:fetch:)`` method lets you entirely separate the **observed region(s)** from the **fetched value** itself, for maximum flexibility. See ``DatabaseRegionConvertible`` for more information about the regions that can be tracked.
|
||||
|
||||
## ValueObservation Performance
|
||||
|
||||
@@ -219,13 +219,16 @@ When needed, you can help GRDB optimize observations and reduce database content
|
||||
|
||||
> Tip: When the observation tracks a constant database region, create an optimized observation with the ``trackingConstantRegion(_:)`` method. See the documentation of this method for more information about what constitutes a "constant region", and the nature of the optimization.
|
||||
|
||||
**Truncating WAL checkpoints impact ValueObservation.** Such checkpoints are performed with ``Database/checkpoint(_:on:)`` or [`PRAGMA wal_checkpoint`](https://www.sqlite.org/pragma.html#pragma_wal_checkpoint). When an observation is started on a ``DatabasePool``, from a database that has a missing or empty [wal file](https://www.sqlite.org/tempfiles.html#write_ahead_log_wal_files), the observation will always notify two values when it starts, even if the database content is not changed. This is a consequence of the impossibility to create the [wal snapshot](https://www.sqlite.org/c3ref/snapshot_get.html) needed for detecting that no changes were performed during the observation startup. If your application performs truncating checkpoints, you will avoid this behavior if you recreate a non-empty wal file before starting observations. To do so, perform any kind of no-op transaction (such a creating and dropping a dummy table).
|
||||
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating a ValueObservation
|
||||
|
||||
- ``tracking(_:)``
|
||||
- ``trackingConstantRegion(_:)``
|
||||
- ``tracking(region:fetch:)``
|
||||
- ``tracking(region:_:fetch:)``
|
||||
- ``tracking(regions:fetch:)``
|
||||
|
||||
### Creating a Shared Observation
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# ``GRDB``
|
||||
|
||||
A toolkit for SQLite databases, with a focus on application development
|
||||
|
||||
##
|
||||
|
||||

|
||||
|
||||
- [GitHub Repository](http://github.com/groue/GRDB.swift)
|
||||
- [Installation Instructions, encryption with SQLCipher, custom SQLite builds](https://github.com/groue/GRDB.swift#installation)
|
||||
- [GRDBQuery](https://github.com/groue/GRDBQuery), the SwiftUI companion for GRDB
|
||||
|
||||
## Overview
|
||||
|
||||
Use this library to save your application’s permanent data into SQLite databases. It comes with built-in tools that address common needs:
|
||||
|
||||
- **SQL Generation**
|
||||
|
||||
Enhance your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to.
|
||||
|
||||
- **Database Observation**
|
||||
|
||||
Get notifications when database values are modified.
|
||||
|
||||
- **Robust Concurrency**
|
||||
|
||||
Multi-threaded applications can efficiently use their databases, including WAL databases that support concurrent reads and writes.
|
||||
|
||||
- **Migrations**
|
||||
|
||||
Evolve the schema of your database as you ship new versions of your application.
|
||||
|
||||
- **Leverage your SQLite skills**
|
||||
|
||||
Not all developers need advanced SQLite features. But when you do, GRDB is as sharp as you want it to be. Come with your SQL and SQLite skills, or learn new ones as you go!
|
||||
|
||||
## Usage
|
||||
|
||||
Start using the database in four steps:
|
||||
|
||||
```swift
|
||||
import GRDB
|
||||
|
||||
// 1. Open a database connection
|
||||
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
|
||||
// 2. Define the database schema
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Define a record type
|
||||
struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
var id: String
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
// 4. Write and read in the database
|
||||
try dbQueue.write { db in
|
||||
try Player(id: "1", name: "Arthur", score: 100).insert(db)
|
||||
try Player(id: "2", name: "Barbara", score: 1000).insert(db)
|
||||
}
|
||||
|
||||
let players: [Player] = try dbQueue.read { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Topics
|
||||
|
||||
### Fundamentals
|
||||
|
||||
- <doc:DatabaseConnections>
|
||||
- <doc:SQLSupport>
|
||||
- <doc:Concurrency>
|
||||
- <doc:Transactions>
|
||||
|
||||
### Migrations and The Database Schema
|
||||
|
||||
- <doc:DatabaseSchema>
|
||||
- <doc:Migrations>
|
||||
|
||||
### Records and the Query Interface
|
||||
|
||||
- <doc:QueryInterface>
|
||||
- <doc:RecordRecommendedPractices>
|
||||
- <doc:RecordTimestamps>
|
||||
- <doc:SingleRowTables>
|
||||
|
||||
### Responding to Database Changes
|
||||
|
||||
- <doc:DatabaseObservation>
|
||||
|
||||
### Full-Text Search
|
||||
|
||||
- <doc:FullTextSearch>
|
||||
|
||||
### Combine Publishers
|
||||
|
||||
- ``DatabasePublishers``
|
||||
@@ -55,7 +55,7 @@ Thanks to this database schema, the application will always process *consistent
|
||||
|
||||
> Tip: **A local SQLite database is not a JSON payload loaded from a remote server.**
|
||||
>
|
||||
> The JSON format and content can not be controlled, and an application must defend itself against wacky servers. But a local database is under your full control. It is trustable. A relational database such as SQLite guarantee the quality of users data, as long as enough energy is put in the proper definition of the database schema.
|
||||
> The JSON format and content can not be controlled, and an application must defend itself against wacky servers. But a local database is under your full control. It is trustable. A relational database such as SQLite guarantees the quality of users data, as long as enough energy is put in the proper definition of the database schema.
|
||||
|
||||
> Tip: **Plan early for future versions of your application**: use <doc:Migrations>.
|
||||
|
||||
@@ -510,7 +510,7 @@ For more information about associations, see the [Associations] guide.
|
||||
|
||||
The additional record types described in the previous section may look superfluous. Some other database libraries are able to navigate in graphs of records without additional types.
|
||||
|
||||
For example, [Core Data] and Ruby's [Active Record] uses **lazy loading**. This means that relationships are lazily fetched on demand:
|
||||
For example, [Core Data] and Ruby's [Active Record] use **lazy loading**. This means that relationships are lazily fetched on demand:
|
||||
|
||||
```ruby
|
||||
# Lazy loading with Active Record
|
||||
@@ -549,7 +549,7 @@ if let author = query.get() {
|
||||
}
|
||||
```
|
||||
|
||||
**GRDB supports eager loading**. The difference with Fluent is that the relationships are modelled in a dedicated record type that provides full compile and runtime safety:
|
||||
**GRDB supports eager loading**. The difference with Fluent is that the relationships are modelled in a dedicated record type that provides runtime safety:
|
||||
|
||||
```swift
|
||||
// Eager loading with GRDB
|
||||
|
||||
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 104 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 134 KiB |
@@ -81,7 +81,6 @@ For a more detailed overview, see [SQLite API](https://github.com/groue/GRDB.swi
|
||||
|
||||
### Database Values
|
||||
|
||||
- ``DatabaseDateComponents``
|
||||
- ``DatabaseValueConvertible``
|
||||
- ``StatementColumnConvertible``
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ extension Database {
|
||||
///
|
||||
/// class MyTokenizer : FTS5CustomTokenizer { ... }
|
||||
/// db.add(tokenizer: MyTokenizer.self)
|
||||
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
|
||||
public func add(tokenizer: (some FTS5CustomTokenizer).Type) {
|
||||
let api = FTS5.api(self)
|
||||
|
||||
// Swift won't let the @convention(c) xCreate() function below create
|
||||
@@ -76,7 +76,7 @@ extension Database {
|
||||
return SQLITE_ERROR
|
||||
}
|
||||
do {
|
||||
let tokenizer = try Tokenizer(db: db, arguments: arguments)
|
||||
let tokenizer = try tokenizer.init(db: db, arguments: arguments)
|
||||
|
||||
// Tokenizer must remain alive until xDeleteTokenizer()
|
||||
// is called, as the xDelete member of xTokenizer
|
||||
@@ -158,7 +158,7 @@ extension Database {
|
||||
let code = withUnsafeMutablePointer(to: &xTokenizer) { xTokenizerPointer in
|
||||
api.pointee.xCreateTokenizer(
|
||||
UnsafeMutablePointer(mutating: api),
|
||||
Tokenizer.name,
|
||||
tokenizer.name,
|
||||
constructorPointer,
|
||||
xTokenizerPointer,
|
||||
deleteConstructor)
|
||||
|
||||
@@ -457,7 +457,13 @@ public struct DatabaseMigrator {
|
||||
}
|
||||
}()
|
||||
|
||||
if try db.schema(.main) != tmpSchema {
|
||||
// Only compare user objects
|
||||
func isUserObject(_ object: SchemaObject) -> Bool {
|
||||
!Database.isSQLiteInternalTable(object.name) && !Database.isGRDBInternalTable(object.name)
|
||||
}
|
||||
let tmpUserSchema = tmpSchema.filter(isUserObject)
|
||||
let userSchema = try db.schema(.main).filter(isUserObject)
|
||||
if userSchema != tmpUserSchema {
|
||||
needsErase = true
|
||||
return .commit
|
||||
}
|
||||
|
||||
@@ -436,7 +436,7 @@ extension QueryInterfaceRequest: DerivableRequest {
|
||||
}
|
||||
}
|
||||
|
||||
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
|
||||
public func with<T>(_ cte: CommonTableExpression<T>) -> Self {
|
||||
with {
|
||||
$0.relation.ctes[cte.tableName] = cte.cte
|
||||
}
|
||||
@@ -1279,6 +1279,90 @@ extension ColumnExpression {
|
||||
public static func /= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
column.set(to: column / value)
|
||||
}
|
||||
|
||||
/// Creates an assignment that applies a bitwise and.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// Column("mask") &= 2
|
||||
/// Column("mask") &= Column("other")
|
||||
/// ```
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = score & 2
|
||||
/// try Player.updateAll(db, Column("mask") &= 2)
|
||||
/// }
|
||||
/// ```
|
||||
public static func &= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
column.set(to: column & value)
|
||||
}
|
||||
|
||||
/// Creates an assignment that applies a bitwise or.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// Column("mask") |= 2
|
||||
/// Column("mask") |= Column("other")
|
||||
/// ```
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = score | 2
|
||||
/// try Player.updateAll(db, Column("mask") |= 2)
|
||||
/// }
|
||||
/// ```
|
||||
public static func |= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
column.set(to: column | value)
|
||||
}
|
||||
|
||||
/// Creates an assignment that applies a bitwise left shift.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// Column("mask") <<= 2
|
||||
/// Column("mask") <<= Column("other")
|
||||
/// ```
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = score << 2
|
||||
/// try Player.updateAll(db, Column("mask") <<= 2)
|
||||
/// }
|
||||
/// ```
|
||||
public static func <<= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
column.set(to: column << value)
|
||||
}
|
||||
|
||||
/// Creates an assignment that applies a bitwise right shift.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// Column("mask") >>= 2
|
||||
/// Column("mask") >>= Column("other")
|
||||
/// ```
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = score >> 2
|
||||
/// try Player.updateAll(db, Column("mask") >>= 2)
|
||||
/// }
|
||||
/// ```
|
||||
public static func >>= (column: Self, value: some SQLExpressible) -> ColumnAssignment {
|
||||
column.set(to: column >> value)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Eager loading of hasMany associations
|
||||
|
||||
@@ -214,6 +214,7 @@ extension SelectionRequest {
|
||||
///
|
||||
/// ### The WHERE and JOIN ON Clauses
|
||||
///
|
||||
/// - ``all()``
|
||||
/// - ``filter(_:)``
|
||||
/// - ``filter(literal:)``
|
||||
/// - ``filter(sql:arguments:)``
|
||||
@@ -291,6 +292,13 @@ extension FilteredRequest {
|
||||
public func none() -> Self {
|
||||
filterWhenConnected { _ in false }
|
||||
}
|
||||
|
||||
/// Returns `self`: a request that fetches all rows from this request.
|
||||
///
|
||||
/// This method, which does nothing, exists in order to match ``none()``.
|
||||
public func all() -> Self {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TableRequest
|
||||
@@ -1328,6 +1336,7 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
///
|
||||
/// ### The WHERE Clause
|
||||
///
|
||||
/// - ``FilteredRequest/all()``
|
||||
/// - ``FilteredRequest/filter(_:)``
|
||||
/// - ``TableRequest/filter(id:)``
|
||||
/// - ``TableRequest/filter(ids:)``
|
||||
|
||||
@@ -196,7 +196,7 @@ public struct SQLExpression {
|
||||
|
||||
/// An associative binary SQL operator, such as `+`, `*`, `AND`, etc.
|
||||
///
|
||||
/// Use it with the `joined(operator:)` method. For example:
|
||||
/// Use an associative operator with the `joined(operator:)` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT score + bonus + 1000 FROM player
|
||||
@@ -206,6 +206,27 @@ public struct SQLExpression {
|
||||
/// 1000.databaseValue]
|
||||
/// let request = Player.select(values.joined(operator: .add))
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Arithmetic Operators
|
||||
///
|
||||
/// - ``add``
|
||||
/// - ``multiply``
|
||||
///
|
||||
/// ### Logical Operators
|
||||
///
|
||||
/// - ``and``
|
||||
/// - ``or``
|
||||
///
|
||||
/// ### String Operators
|
||||
///
|
||||
/// - ``concat``
|
||||
///
|
||||
/// ### Bitwise Operators
|
||||
///
|
||||
/// - ``bitwiseAnd``
|
||||
/// - ``bitwiseOr``
|
||||
public struct AssociativeBinaryOperator: Hashable {
|
||||
/// The SQL operator
|
||||
let sql: String
|
||||
@@ -215,7 +236,7 @@ public struct SQLExpression {
|
||||
|
||||
/// If true, (a • b) • c is strictly equal to a • (b • c).
|
||||
///
|
||||
/// `AND`, `OR`, `||` (concat) are stricly associative.
|
||||
/// `AND`, `OR`, `||` (concat), `&`, `|` are stricly associative.
|
||||
///
|
||||
/// `+` and `*` are not stricly associative when applied to floating
|
||||
/// point values.
|
||||
@@ -226,7 +247,7 @@ public struct SQLExpression {
|
||||
///
|
||||
/// `||` (concat) is bijective.
|
||||
///
|
||||
/// `AND`, `OR`, `+` and `*` are not.
|
||||
/// `AND`, `OR`, `+` and `*`, `&`, `|` are not.
|
||||
let isBijective: Bool
|
||||
|
||||
/// Creates a binary operator
|
||||
@@ -237,7 +258,7 @@ public struct SQLExpression {
|
||||
self.isBijective = bijective
|
||||
}
|
||||
|
||||
/// The `+` binary SQL operator.
|
||||
/// The arithmetic `+` binary SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -245,13 +266,19 @@ public struct SQLExpression {
|
||||
/// // score + bonus
|
||||
/// [Column("score"), Column("bonus")].joined(operator: .add)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `add` operator, used when joining an
|
||||
/// empty sequence, is `0`.
|
||||
///
|
||||
/// The `add` operator performs a numeric addition. To concatenate
|
||||
/// strings, use the ``concat`` operator instead.
|
||||
public static let add = AssociativeBinaryOperator(
|
||||
sql: "+",
|
||||
neutralValue: 0.databaseValue,
|
||||
strictlyAssociative: false,
|
||||
bijective: false)
|
||||
|
||||
/// The `*` binary SQL operator.
|
||||
/// The arithmetic `*` binary SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -259,13 +286,16 @@ public struct SQLExpression {
|
||||
/// // score * factor
|
||||
/// [Column("score"), Column("factor")].joined(operator: .multiply)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `multiply` operator, used when joining an
|
||||
/// empty sequence, is `1`.
|
||||
public static let multiply = AssociativeBinaryOperator(
|
||||
sql: "*",
|
||||
neutralValue: 1.databaseValue,
|
||||
strictlyAssociative: false,
|
||||
bijective: false)
|
||||
|
||||
/// The `AND` binary SQL operator.
|
||||
/// The logical `AND` binary SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -273,13 +303,16 @@ public struct SQLExpression {
|
||||
/// // isBlue AND isTall
|
||||
/// [Column("isBlue"), Column("isTall")].joined(operator: .and)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `and` operator, used when joining an
|
||||
/// empty sequence, is `true`.
|
||||
public static let and = AssociativeBinaryOperator(
|
||||
sql: "AND",
|
||||
neutralValue: true.databaseValue,
|
||||
strictlyAssociative: true,
|
||||
bijective: false)
|
||||
|
||||
/// The `OR` binary SQL operator.
|
||||
/// The logical `OR` binary SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -287,6 +320,9 @@ public struct SQLExpression {
|
||||
/// // isBlue OR isTall
|
||||
/// [Column("isBlue"), Column("isTall")].joined(operator: .or)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `or` operator, used when joining an
|
||||
/// empty sequence, is `false`.
|
||||
public static let or = AssociativeBinaryOperator(
|
||||
sql: "OR",
|
||||
neutralValue: false.databaseValue,
|
||||
@@ -301,11 +337,49 @@ public struct SQLExpression {
|
||||
/// // firstName || ' ' || lastName
|
||||
/// [Column("firstName"), " ", Column("lastName")].joined(operator: .concat)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `concat` operator, used when joining an
|
||||
/// empty sequence, is the empty string.
|
||||
public static let concat = AssociativeBinaryOperator(
|
||||
sql: "||",
|
||||
neutralValue: "".databaseValue,
|
||||
strictlyAssociative: true,
|
||||
bijective: true)
|
||||
|
||||
/// The bitwise `&` SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // mask & 2
|
||||
/// [Column("mask"), 2.databaseValue].joined(operator: .bitwiseAnd)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `bitwiseAnd` operator, used when
|
||||
/// joining an empty sequence, is `-1` (the signed 64-bit integer
|
||||
/// with all bits set).
|
||||
public static let bitwiseAnd = AssociativeBinaryOperator(
|
||||
sql: "&",
|
||||
neutralValue: (-1).databaseValue,
|
||||
strictlyAssociative: true,
|
||||
bijective: false)
|
||||
|
||||
/// The bitwise `|` SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // mask | 2
|
||||
/// [Column("mask"), 2.databaseValue].joined(operator: .bitwiseOr)
|
||||
/// ```
|
||||
///
|
||||
/// The neutral value of the `bitwiseOr` operator, used when
|
||||
/// joining an empty sequence, is `0`.
|
||||
public static let bitwiseOr = AssociativeBinaryOperator(
|
||||
sql: "|",
|
||||
neutralValue: 0.databaseValue,
|
||||
strictlyAssociative: true,
|
||||
bijective: false)
|
||||
}
|
||||
|
||||
/// `BinaryOperator` is an SQLite binary operator, such as `>`, `=`, etc.
|
||||
@@ -343,6 +417,12 @@ public struct SQLExpression {
|
||||
|
||||
/// The `MATCH` binary operator
|
||||
static let match = BinaryOperator("MATCH")
|
||||
|
||||
/// The `<<` bitwise left shift operator
|
||||
static let leftShift = BinaryOperator("<<")
|
||||
|
||||
/// The `>>` bitwise right shift operator
|
||||
static let rightShift = BinaryOperator(">>")
|
||||
}
|
||||
|
||||
/// `EscapableBinaryOperator` is an SQLite binary operator that accepts an
|
||||
@@ -399,19 +479,16 @@ public struct SQLExpression {
|
||||
/// The SQL operator
|
||||
let sql: String
|
||||
|
||||
/// If true GRDB puts a white space between the operator and the operand.
|
||||
let needsRightSpace: Bool
|
||||
|
||||
/// Creates an unary operator
|
||||
///
|
||||
/// UnaryOperator("~", needsRightSpace: false)
|
||||
init(_ sql: String, needsRightSpace: Bool) {
|
||||
/// Creates an unary operator.
|
||||
init(_ sql: String) {
|
||||
self.sql = sql
|
||||
self.needsRightSpace = needsRightSpace
|
||||
}
|
||||
|
||||
/// The `-` unary operator
|
||||
static let minus = UnaryOperator("-", needsRightSpace: false)
|
||||
static let minus = UnaryOperator("-")
|
||||
|
||||
/// The `~` unary operator
|
||||
static let bitwiseNot = UnaryOperator("~")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1021,9 +1098,7 @@ extension SQLExpression {
|
||||
return resultSQL
|
||||
|
||||
case let .unary(op, expression):
|
||||
var resultSQL = try op.sql
|
||||
+ (op.needsRightSpace ? " " : "")
|
||||
+ expression.sql(context, wrappedInParenthesis: true)
|
||||
var resultSQL = try op.sql + expression.sql(context, wrappedInParenthesis: true)
|
||||
if wrappedInParenthesis {
|
||||
resultSQL = "(\(resultSQL))"
|
||||
}
|
||||
@@ -1757,6 +1832,20 @@ extension SQLExpressible where Self == Column {
|
||||
/// - ``uppercased``
|
||||
/// - ``SQLDateModifier``
|
||||
///
|
||||
/// ### Create SQL Expressions from Sequences
|
||||
///
|
||||
/// - ``Swift/Sequence/contains(_:)-9i0ld``
|
||||
/// - ``Swift/Sequence/contains(_:)-o8ic``
|
||||
/// - ``Swift/Sequence/joined(operator:)-33dy5``
|
||||
/// - ``Swift/Sequence/joined(operator:)-4k88t``
|
||||
///
|
||||
/// ### Create SQL Expressions from Ranges
|
||||
///
|
||||
/// - ``Swift/ClosedRange/contains(_:)-64zwp``
|
||||
/// - ``Swift/ClosedRange/contains(_:)-19a6d``
|
||||
/// - ``Swift/Range/contains(_:)-11nr0``
|
||||
/// - ``Swift/Range/contains(_:)-3v32b``
|
||||
///
|
||||
/// ### Creating Ordering Terms
|
||||
///
|
||||
/// - ``asc``
|
||||
@@ -1824,13 +1913,8 @@ extension Sequence where Element: SQLSpecificExpressible {
|
||||
/// ```
|
||||
///
|
||||
/// When the sequence is empty, `joined(operator:)` returns the neutral
|
||||
/// value of the operator. It is:
|
||||
///
|
||||
/// - `0` for ``SQLExpression/AssociativeBinaryOperator/add``
|
||||
/// - `1` for ``SQLExpression/AssociativeBinaryOperator/multiply``
|
||||
/// - `false` for ``SQLExpression/AssociativeBinaryOperator/or``
|
||||
/// - `true` for ``SQLExpression/AssociativeBinaryOperator/and``
|
||||
/// - `""` for ``SQLExpression/AssociativeBinaryOperator/concat``
|
||||
/// value of the operator. See
|
||||
/// ``SQLExpression/AssociativeBinaryOperator`` for more information.
|
||||
public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression {
|
||||
.associativeBinary(`operator`, map(\.sqlExpression))
|
||||
}
|
||||
@@ -1842,7 +1926,7 @@ extension Sequence where Element == any SQLSpecificExpressible {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```
|
||||
/// ```swift
|
||||
/// // SELECT * FROM player
|
||||
/// // WHERE (registered
|
||||
/// // AND (score >= 1000)
|
||||
@@ -1855,13 +1939,8 @@ extension Sequence where Element == any SQLSpecificExpressible {
|
||||
/// ```
|
||||
///
|
||||
/// When the sequence is empty, `joined(operator:)` returns the neutral
|
||||
/// value of the operator. It is:
|
||||
///
|
||||
/// - `0` for ``SQLExpression/AssociativeBinaryOperator/add``
|
||||
/// - `1` for ``SQLExpression/AssociativeBinaryOperator/multiply``
|
||||
/// - `false` for ``SQLExpression/AssociativeBinaryOperator/or``
|
||||
/// - `true` for ``SQLExpression/AssociativeBinaryOperator/and``
|
||||
/// - `""` for ``SQLExpression/AssociativeBinaryOperator/concat``
|
||||
/// value of the operator. See
|
||||
/// ``SQLExpression/AssociativeBinaryOperator`` for more information.
|
||||
public func joined(operator: SQLExpression.AssociativeBinaryOperator) -> SQLExpression {
|
||||
.associativeBinary(`operator`, map(\.sqlExpression))
|
||||
}
|
||||
@@ -1936,7 +2015,7 @@ extension SQLSpecificExpressible {
|
||||
|
||||
/// Returns an aliased column with the same name as the coding key.
|
||||
///
|
||||
/// See ``forKey(_:)-3xk0``.
|
||||
/// See <doc:SQLSpecificExpressible/forKey(_:)-3xk0>.
|
||||
public func forKey(_ key: some CodingKey) -> SQLSelection {
|
||||
forKey(key.stringValue)
|
||||
}
|
||||
|
||||
@@ -436,6 +436,75 @@ extension SQLSpecificExpressible {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Bitwise Operators (&, |, ~, <<, >>)
|
||||
|
||||
extension SQLSpecificExpressible {
|
||||
/// The `&` SQL operator.
|
||||
public static func & (lhs: Self, rhs: some SQLExpressible) -> SQLExpression {
|
||||
.associativeBinary(.bitwiseAnd, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `&` SQL operator.
|
||||
public static func & (lhs: some SQLExpressible, rhs: Self) -> SQLExpression {
|
||||
.associativeBinary(.bitwiseAnd, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `&` SQL operator.
|
||||
public static func & (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.associativeBinary(.bitwiseAnd, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `|` SQL operator.
|
||||
public static func | (lhs: Self, rhs: some SQLExpressible) -> SQLExpression {
|
||||
.associativeBinary(.bitwiseOr, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `|` SQL operator.
|
||||
public static func | (lhs: some SQLExpressible, rhs: Self) -> SQLExpression {
|
||||
.associativeBinary(.bitwiseOr, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `|` SQL operator.
|
||||
public static func | (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.associativeBinary(.bitwiseOr, [lhs.sqlExpression, rhs.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `<<` SQL operator.
|
||||
public static func << (lhs: Self, rhs: some SQLExpressible) -> SQLExpression {
|
||||
.binary(.leftShift, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `<<` SQL operator.
|
||||
public static func << (lhs: some SQLExpressible, rhs: Self) -> SQLExpression {
|
||||
.binary(.leftShift, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `<<` SQL operator.
|
||||
public static func << (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.binary(.leftShift, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `>>` SQL operator.
|
||||
public static func >> (lhs: Self, rhs: some SQLExpressible) -> SQLExpression {
|
||||
.binary(.rightShift, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `>>` SQL operator.
|
||||
public static func >> (lhs: some SQLExpressible, rhs: Self) -> SQLExpression {
|
||||
.binary(.rightShift, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `>>` SQL operator.
|
||||
public static func >> (lhs: Self, rhs: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.binary(.rightShift, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `~` SQL operator.
|
||||
public static prefix func ~ (value: Self) -> SQLExpression {
|
||||
.unary(.bitwiseNot, value.sqlExpression)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Like Operator
|
||||
|
||||
extension SQLSpecificExpressible {
|
||||
|
||||
@@ -298,10 +298,10 @@ extension Table {
|
||||
/// let maxScore: Int = row[1]
|
||||
/// }
|
||||
/// ```
|
||||
public func select<RowDecoder>(
|
||||
public func select<T>(
|
||||
_ selection: [any SQLSelectable],
|
||||
as type: RowDecoder.Type = RowDecoder.self)
|
||||
-> QueryInterfaceRequest<RowDecoder>
|
||||
as type: T.Type = T.self)
|
||||
-> QueryInterfaceRequest<T>
|
||||
{
|
||||
all().select(selection, as: type)
|
||||
}
|
||||
@@ -328,10 +328,10 @@ extension Table {
|
||||
/// let maxScore: Int = row[1]
|
||||
/// }
|
||||
/// ```
|
||||
public func select<RowDecoder>(
|
||||
public func select<T>(
|
||||
_ selection: any SQLSelectable...,
|
||||
as type: RowDecoder.Type = RowDecoder.self)
|
||||
-> QueryInterfaceRequest<RowDecoder>
|
||||
as type: T.Type = T.self)
|
||||
-> QueryInterfaceRequest<T>
|
||||
{
|
||||
all().select(selection, as: type)
|
||||
}
|
||||
@@ -353,11 +353,11 @@ extension Table {
|
||||
/// let request = playerTable.select(sql: "IFNULL(name, ?)", arguments: [defaultName], as: String.self)
|
||||
/// let names = try request.fetchAll(db) // [String]
|
||||
/// ```
|
||||
public func select<RowDecoder>(
|
||||
public func select<T>(
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
as type: RowDecoder.Type = RowDecoder.self)
|
||||
-> QueryInterfaceRequest<RowDecoder>
|
||||
as type: T.Type = T.self)
|
||||
-> QueryInterfaceRequest<T>
|
||||
{
|
||||
all().select(SQL(sql: sql, arguments: arguments), as: type)
|
||||
}
|
||||
@@ -376,10 +376,10 @@ extension Table {
|
||||
/// let request = playerTable.select(literal: "IFNULL(name, \(defaultName))", as: String.self)
|
||||
/// let names = try request.fetchAll(db) // [String]
|
||||
/// ```
|
||||
public func select<RowDecoder>(
|
||||
public func select<T>(
|
||||
literal sqlLiteral: SQL,
|
||||
as type: RowDecoder.Type = RowDecoder.self)
|
||||
-> QueryInterfaceRequest<RowDecoder>
|
||||
as type: T.Type = T.self)
|
||||
-> QueryInterfaceRequest<T>
|
||||
{
|
||||
all().select(sqlLiteral, as: type)
|
||||
}
|
||||
|
||||
@@ -210,7 +210,7 @@ extension Database {
|
||||
/// t.column("score", .integer).indexed()
|
||||
/// ```
|
||||
///
|
||||
/// For extra index options, see ``create(index:on:columns:options:condition:)``.
|
||||
/// For extra index options, see ``create(indexOn:columns:options:condition:)``.
|
||||
///
|
||||
/// ### Generated columns
|
||||
///
|
||||
@@ -325,7 +325,8 @@ extension Database {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
|
||||
/// // CREATE INDEX index_player_on_email ON player(email)
|
||||
/// try db.create(index: "index_player_on_email", on: "player", columns: ["email"])
|
||||
/// ```
|
||||
///
|
||||
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
|
||||
@@ -340,7 +341,7 @@ extension Database {
|
||||
///
|
||||
/// - warning: This is a legacy interface that is preserved for backwards
|
||||
/// compatibility. Use of this interface is not recommended: prefer
|
||||
/// ``create(index:on:columns:options:condition:)`` instead.
|
||||
/// ``create(indexOn:columns:options:condition:)`` instead.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The index name.
|
||||
@@ -372,7 +373,15 @@ extension Database {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
|
||||
/// // CREATE INDEX index_player_on_email ON player(email)
|
||||
/// try db.create(index: "index_player_on_email", on: "player", columns: ["email"])
|
||||
/// ```
|
||||
///
|
||||
/// To create a unique index, specify the `.unique` option:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE UNIQUE INDEX index_player_on_email ON player(email)
|
||||
/// try db.create(index: "index_player_on_email", on: "player", columns: ["email"], options: .unique)
|
||||
/// ```
|
||||
///
|
||||
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
|
||||
@@ -411,15 +420,88 @@ extension Database {
|
||||
try execute(sql: sql)
|
||||
}
|
||||
|
||||
/// Creates an index on the specified table and columns.
|
||||
///
|
||||
/// The created index is named after the table and the column name(s):
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE INDEX index_player_on_email ON player(email)
|
||||
/// try db.create(indexOn: "player", columns: ["email"])
|
||||
/// ```
|
||||
///
|
||||
/// To create a unique index, specify the `.unique` option:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE UNIQUE INDEX index_player_on_email ON player(email)
|
||||
/// try db.create(indexOn: "player", columns: ["email"], options: .unique)
|
||||
/// ```
|
||||
///
|
||||
/// In order to specify the index name, use
|
||||
/// ``create(index:on:columns:options:condition:)`` instead.
|
||||
///
|
||||
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
|
||||
/// and use specific collations. To create such an index, use a raw SQL
|
||||
/// query:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.execute(sql: "CREATE INDEX ...")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - table: The name of the indexed table.
|
||||
/// - columns: The indexed columns.
|
||||
/// - options: Index creation options.
|
||||
/// - condition: If not nil, creates a partial index
|
||||
/// (see <https://www.sqlite.org/partialindex.html>).
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func create(
|
||||
indexOn table: String,
|
||||
columns: [String],
|
||||
options: IndexOptions = [],
|
||||
condition: (any SQLExpressible)? = nil)
|
||||
throws
|
||||
{
|
||||
try create(
|
||||
index: defaultIndexName(on: table, columns: columns),
|
||||
on: table,
|
||||
columns: columns,
|
||||
options: options,
|
||||
condition: condition)
|
||||
}
|
||||
|
||||
private func defaultIndexName(on table: String, columns: [String]) -> String {
|
||||
"index_\(table)_on_\(columns.joined(separator: "_"))"
|
||||
}
|
||||
|
||||
/// Deletes a database index.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_dropindex.html>
|
||||
///
|
||||
/// - parameter name: The index name.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func drop(index name: String) throws {
|
||||
try execute(sql: "DROP INDEX \(name.quotedDatabaseIdentifier)")
|
||||
}
|
||||
|
||||
/// Deletes the database index on the specified table and columns
|
||||
/// if exactly one such index exists.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - table: The name of the indexed table.
|
||||
/// - columns: The indexed columns.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func drop(indexOn table: String, columns: [String]) throws {
|
||||
let lowercasedColumns = columns.map { $0.lowercased() }
|
||||
let indexes = try indexes(on: table).filter { index in
|
||||
index.columns.map({ $0.lowercased() }) == lowercasedColumns
|
||||
}
|
||||
if let index = indexes.first, indexes.count == 1 {
|
||||
try drop(index: index.name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes and recreates from scratch all indices that use this collation.
|
||||
///
|
||||
/// This method is useful when the definition of a collation sequence
|
||||
@@ -510,7 +592,8 @@ public struct TableOptions: OptionSet {
|
||||
///
|
||||
/// ### Define Others Constraints
|
||||
///
|
||||
/// - ``check(_:)``
|
||||
/// - ``check(_:)-6u1za``
|
||||
/// - ``check(_:)-jpcg``
|
||||
/// - ``check(sql:)``
|
||||
/// - ``constraint(literal:)``
|
||||
/// - ``constraint(sql:)``
|
||||
@@ -908,10 +991,49 @@ public final class TableDefinition {
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#ckconst>
|
||||
///
|
||||
/// - parameter condition: The checked condition.
|
||||
@available(*, deprecated)
|
||||
public func check(_ condition: some SQLExpressible) {
|
||||
checkConstraints.append(condition.sqlExpression)
|
||||
}
|
||||
|
||||
/// Adds a check constraint.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE player (
|
||||
/// // personalPhone TEXT,
|
||||
/// // workPhone TEXT,
|
||||
/// // CHECK personalPhone IS NOT NULL OR workPhone IS NOT NULL
|
||||
/// // )
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.column("personalPhone", .text)
|
||||
/// t.column("workPhone", .text)
|
||||
/// let personalPhone = Column("personalPhone")
|
||||
/// let workPhone = Column("workPhone")
|
||||
/// t.check(personalPhone != nil || workPhone != nil)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When defining a check constraint on a single column, you can use the
|
||||
/// ``ColumnDefinition/check(_:)`` shortcut:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE player(
|
||||
/// // name TEXT CHECK (LENGTH(name) > 0)
|
||||
/// // )
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.column("name", .text).check { length($0) > 0 }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html#ckconst>
|
||||
///
|
||||
/// - parameter condition: The checked condition.
|
||||
public func check(_ condition: some SQLSpecificExpressible) {
|
||||
checkConstraints.append(condition.sqlExpression)
|
||||
}
|
||||
|
||||
/// Adds a check constraint.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -3,16 +3,71 @@ import Foundation
|
||||
extension FetchableRecord where Self: Decodable {
|
||||
/// Creates a record from `row`, using the `Decodable` conformance.
|
||||
public init(row: Row) throws {
|
||||
self = try RowDecoder().decode(from: row)
|
||||
self = try FetchableRecordDecoder().decode(Self.self, from: row)
|
||||
}
|
||||
}
|
||||
|
||||
// For testability. Not intended to become public as long as FetchableRecord has
|
||||
// a non-throwing row initializer, since this would open an undesired door.
|
||||
class RowDecoder {
|
||||
init() { }
|
||||
/// An object that decodes fetchable records from database rows.
|
||||
///
|
||||
/// The example below shows how to decode an instance of a simple `Player`
|
||||
/// type, that conforms to both ``FetchableRecord`` and `Decodable`, from a
|
||||
/// database row.
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: FetchableRecord, Decodable {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// if let row = try Row.fetchOne(db, sql: "SELECT * FROM player WHERE id = 42") {
|
||||
/// let decoder = FetchableRecordDecoder()
|
||||
/// let player = try decoder.decode(Player.self, from: row)
|
||||
/// print(player.name)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You will generally not need to create an instance of
|
||||
/// `FetchableRecordDecoder`. The above sample code is correct, but you will
|
||||
/// generally write instead:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// // Prefer the init(row:) initializer:
|
||||
/// if let row = try Row.fetchOne(db, sql: "SELECT * FROM player WHERE id = 42") {
|
||||
/// let player = try Player(row: row)
|
||||
/// print(player.name)
|
||||
/// }
|
||||
///
|
||||
/// // OR just directly fetch a player:
|
||||
/// if let player = try Player.fetchOne(db, sql: "SELECT * FROM player WHERE id = 42") {
|
||||
/// print(player.name)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The behavior of the decoder depends on the decoded type. See:
|
||||
///
|
||||
/// - ``FetchableRecord/databaseColumnDecodingStrategy-6uefz``
|
||||
/// - ``FetchableRecord/databaseDateDecodingStrategy-78y03``
|
||||
/// - ``FetchableRecord/databaseDecodingUserInfo-77jim``
|
||||
/// - ``FetchableRecord/databaseJSONDecoder(for:)-7lmxd``
|
||||
public class FetchableRecordDecoder {
|
||||
/// Creates a decoder for fetchable records.
|
||||
public init() { }
|
||||
|
||||
func decode<T: FetchableRecord & Decodable>(_ type: T.Type = T.self, from row: Row) throws -> T {
|
||||
/// Returns a record of the type you specify, decoded from a
|
||||
/// database row.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - type: The type of the record to decode from the supplied
|
||||
/// database row.
|
||||
/// - row: The database row to decode.
|
||||
/// - Returns: An instance of the specified record type, if the decoder
|
||||
/// can parse the database row.
|
||||
public func decode<T: FetchableRecord & Decodable>(_ type: T.Type, from row: Row) throws -> T {
|
||||
let decoder = _RowDecoder<T>(row: row, codingPath: [], columnDecodingStrategy: T.databaseColumnDecodingStrategy)
|
||||
return try T(from: decoder)
|
||||
}
|
||||
|
||||
@@ -98,6 +98,7 @@ import Foundation
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``RecordCursor``
|
||||
/// - ``FetchableRecordDecoder``
|
||||
public protocol FetchableRecord {
|
||||
|
||||
// MARK: - Row Decoding
|
||||
|
||||
@@ -434,6 +434,15 @@ extension MutablePersistableRecord {
|
||||
// Rowid is the last column
|
||||
let rowid: Int64 = row[row.count - 1]
|
||||
let returned = try decode(row)
|
||||
|
||||
// Now that we have fetched the values we need, we could stop
|
||||
// there. But let's make sure we fully consume the cursor
|
||||
// anyway, until SQLITE_DONE. This is necessary, for example,
|
||||
// for upserts in tables that are synchronized with an
|
||||
// FTS5 table.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1390>
|
||||
while try cursor.next() != nil { }
|
||||
|
||||
return (rowid, returned)
|
||||
}
|
||||
|
||||
|
||||
@@ -163,7 +163,7 @@ final class Pool<T> {
|
||||
|
||||
/// Blocks until no element is used, and runs the `barrier` function before
|
||||
/// any other element is dequeued.
|
||||
func barrier<T>(execute barrier: () throws -> T) rethrows -> T {
|
||||
func barrier<R>(execute barrier: () throws -> R) rethrows -> R {
|
||||
try barrierQueue.sync(flags: [.barrier]) {
|
||||
itemsGroup.wait()
|
||||
return try barrier()
|
||||
|
||||
@@ -101,6 +101,19 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
|
||||
}
|
||||
}
|
||||
|
||||
/// The fetching state for observation of constant regions.
|
||||
enum FetchingState {
|
||||
/// No need to fetch.
|
||||
case idle
|
||||
|
||||
/// Waiting for a fetched value.
|
||||
case fetching
|
||||
|
||||
/// Waiting for a fetched value, and for a subsequent fetch after
|
||||
/// that, because a change has been detected as we were fetching.
|
||||
case fetchingAndNeedsFetch
|
||||
}
|
||||
|
||||
/// Ability to notify observation events
|
||||
private struct NotificationCallbacks {
|
||||
let events: ValueObservationEvents
|
||||
@@ -132,6 +145,9 @@ final class ValueConcurrentObserver<Reducer: ValueReducer, Scheduler: ValueObser
|
||||
/// Ability to notify observation events, protected by `lock`.
|
||||
private var notificationCallbacks: NotificationCallbacks?
|
||||
|
||||
/// The fetching state for observation of constant regions.
|
||||
@LockedBox private var fetchingState = FetchingState.idle
|
||||
|
||||
/// Support for `TransactionObserver`, protected by the serialized writer
|
||||
/// dispatch queue.
|
||||
private var observationState = ObservationState.notObserving
|
||||
@@ -272,8 +288,18 @@ extension ValueConcurrentObserver {
|
||||
// We perform the initial read from a long-lived WAL snapshot
|
||||
// transaction, because it is a handy way to keep a read transaction
|
||||
// open until we grab a write access, and compare the database versions.
|
||||
let walSnapshotTransaction = try databaseAccess.dbPool.walSnapshotTransaction()
|
||||
let (fetchedValue, initialRegion) = try walSnapshotTransaction.read { db -> (Reducer.Fetched, DatabaseRegion) in
|
||||
let initialFetchTransaction: WALSnapshotTransaction
|
||||
do {
|
||||
initialFetchTransaction = try databaseAccess.dbPool.walSnapshotTransaction()
|
||||
} catch DatabaseError.SQLITE_ERROR {
|
||||
// We can't create a WAL snapshot. The WAL file is probably
|
||||
// missing, or is truncated. Let's degrade the observation
|
||||
// by not using any snapshot.
|
||||
// For more information, see <https://github.com/groue/GRDB.swift/issues/1383>
|
||||
return try syncStartWithoutWALSnapshot(from: databaseAccess)
|
||||
}
|
||||
|
||||
let (fetchedValue, initialRegion): (Reducer.Fetched, DatabaseRegion) = try initialFetchTransaction.read { db in
|
||||
switch trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
let fetchedValue = try databaseAccess.fetch(db)
|
||||
@@ -299,7 +325,7 @@ extension ValueConcurrentObserver {
|
||||
// Start observation
|
||||
asyncStartObservation(
|
||||
from: databaseAccess,
|
||||
walSnapshotTransaction: walSnapshotTransaction,
|
||||
initialFetchTransaction: initialFetchTransaction,
|
||||
initialRegion: initialRegion)
|
||||
|
||||
return initialValue
|
||||
@@ -318,15 +344,16 @@ extension ValueConcurrentObserver {
|
||||
// transaction, because it is a handy way to keep a read transaction
|
||||
// open until we grab a write access, and compare the database versions.
|
||||
databaseAccess.dbPool.asyncWALSnapshotTransaction { result in
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
let (isNotifying, databaseAccess) = self.lock.synchronized {
|
||||
(self.notificationCallbacks != nil, self.databaseAccess)
|
||||
}
|
||||
guard isNotifying, let databaseAccess else { return /* Cancelled */ }
|
||||
|
||||
do {
|
||||
// Fetch
|
||||
let walSnapshotTransaction = try result.get()
|
||||
let initialFetchTransaction = try result.get()
|
||||
// Second async jump because that's how
|
||||
// `DatabasePool.asyncWALSnapshotTransaction` has to be used.
|
||||
walSnapshotTransaction.asyncRead { db in
|
||||
initialFetchTransaction.asyncRead { db in
|
||||
do {
|
||||
let fetchedValue: Reducer.Fetched
|
||||
let initialRegion: DatabaseRegion
|
||||
@@ -369,12 +396,18 @@ extension ValueConcurrentObserver {
|
||||
// Start observation
|
||||
self.asyncStartObservation(
|
||||
from: databaseAccess,
|
||||
walSnapshotTransaction: walSnapshotTransaction,
|
||||
initialFetchTransaction: initialFetchTransaction,
|
||||
initialRegion: initialRegion)
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
}
|
||||
} catch DatabaseError.SQLITE_ERROR {
|
||||
// We can't create a WAL snapshot. The WAL file is probably
|
||||
// missing, or is truncated. Let's degrade the observation
|
||||
// by not using any snapshot.
|
||||
// For more information, see <https://github.com/groue/GRDB.swift/issues/1383>
|
||||
self.asyncStartWithoutWALSnapshot(from: databaseAccess)
|
||||
} catch {
|
||||
self.notifyError(error)
|
||||
}
|
||||
@@ -383,9 +416,26 @@ extension ValueConcurrentObserver {
|
||||
|
||||
private func asyncStartObservation(
|
||||
from databaseAccess: DatabaseAccess,
|
||||
walSnapshotTransaction: WALSnapshotTransaction,
|
||||
initialFetchTransaction: WALSnapshotTransaction,
|
||||
initialRegion: DatabaseRegion)
|
||||
{
|
||||
// We'll start the observation when we can access the writer
|
||||
// connection. Until then, maybe the database has been modified
|
||||
// since the initial fetch: we'll then need to notify a fresh value.
|
||||
//
|
||||
// To know if the database has been modified between the initial
|
||||
// fetch and the writer access, we'll compare WAL snapshots.
|
||||
//
|
||||
// WAL snapshots can only be compared if the database is not
|
||||
// checkpointed. That's why we'll keep `initialFetchTransaction`
|
||||
// alive until the comparison is done.
|
||||
//
|
||||
// However, we want to release `initialFetchTransaction` as soon as
|
||||
// possible, so that the reader connection it holds becomes
|
||||
// available for other reads. It will be released when this optional
|
||||
// is set to nil:
|
||||
var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction
|
||||
|
||||
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
|
||||
let events = self.lock.synchronized { self.notificationCallbacks?.events }
|
||||
guard let events else { return /* Cancelled */ }
|
||||
@@ -393,21 +443,22 @@ extension ValueConcurrentObserver {
|
||||
do {
|
||||
var observedRegion = initialRegion
|
||||
|
||||
// Transaction is needed for comparing version snapshots
|
||||
try writerDB.isolated(readOnly: true) {
|
||||
// Keep walSnapshotTransaction alive until we have
|
||||
// compared database versions. `WALSnapshot` alone is
|
||||
// not able to prevent database checkpointing, and keep
|
||||
// snapshots comparable.
|
||||
let isModified = withExtendedLifetime(walSnapshotTransaction) {
|
||||
guard let currentWALSnapshot = try? WALSnapshot(writerDB) else {
|
||||
return true
|
||||
}
|
||||
let ordering = walSnapshotTransaction.walSnapshot.compare(currentWALSnapshot)
|
||||
// Was the database modified since the initial fetch?
|
||||
let isModified: Bool
|
||||
if let currentWALSnapshot = try? WALSnapshot(writerDB) {
|
||||
let ordering = initialFetchTransaction!.walSnapshot.compare(currentWALSnapshot)
|
||||
assert(ordering <= 0, "Unexpected snapshot ordering")
|
||||
return ordering < 0
|
||||
isModified = ordering < 0
|
||||
} else {
|
||||
// Can't compare: assume the database was modified.
|
||||
isModified = true
|
||||
}
|
||||
|
||||
// Comparison done: end the WAL snapshot transaction
|
||||
// and release its reader connection.
|
||||
initialFetchTransaction = nil
|
||||
|
||||
if isModified {
|
||||
events.databaseDidChange?()
|
||||
|
||||
@@ -469,11 +520,22 @@ extension ValueConcurrentObserver {
|
||||
}
|
||||
}
|
||||
#else
|
||||
extension ValueConcurrentObserver {
|
||||
private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
|
||||
try syncStartWithoutWALSnapshot(from: databaseAccess)
|
||||
}
|
||||
|
||||
private func asyncStart(from databaseAccess: DatabaseAccess) {
|
||||
asyncStartWithoutWALSnapshot(from: databaseAccess)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension ValueConcurrentObserver {
|
||||
/// Synchronously starts the observation, and returns the initial value.
|
||||
///
|
||||
/// Unlike `asyncStart()`, this method does not notify the initial value or error.
|
||||
private func syncStart(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
|
||||
/// Unlike `asyncStartWithoutWALSnapshot()`, this method does not notify the initial value or error.
|
||||
private func syncStartWithoutWALSnapshot(from databaseAccess: DatabaseAccess) throws -> Reducer.Value {
|
||||
// Start from a read access. The whole point of using a DatabasePool
|
||||
// for observing the database is to be able to fetch the initial value
|
||||
// without having to wait for an eventual long-running write
|
||||
@@ -502,7 +564,7 @@ extension ValueConcurrentObserver {
|
||||
}
|
||||
|
||||
// Start observation
|
||||
asyncStartObservation(
|
||||
asyncStartObservationWithoutWALSnapshot(
|
||||
from: databaseAccess,
|
||||
initialRegion: initialRegion)
|
||||
|
||||
@@ -511,8 +573,8 @@ extension ValueConcurrentObserver {
|
||||
|
||||
/// Asynchronously starts the observation
|
||||
///
|
||||
/// Unlike `syncStart()`, this method does notify the initial value or error.
|
||||
private func asyncStart(from databaseAccess: DatabaseAccess) {
|
||||
/// Unlike `syncStartWithoutWALSnapshot()`, this method does notify the initial value or error.
|
||||
private func asyncStartWithoutWALSnapshot(from databaseAccess: DatabaseAccess) {
|
||||
// Start from a read access. The whole point of using a DatabasePool
|
||||
// for observing the database is to be able to fetch the initial value
|
||||
// without having to wait for an eventual long-running write
|
||||
@@ -562,7 +624,7 @@ extension ValueConcurrentObserver {
|
||||
}
|
||||
|
||||
// Start observation
|
||||
self.asyncStartObservation(
|
||||
self.asyncStartObservationWithoutWALSnapshot(
|
||||
from: databaseAccess,
|
||||
initialRegion: initialRegion)
|
||||
} catch {
|
||||
@@ -571,7 +633,7 @@ extension ValueConcurrentObserver {
|
||||
}
|
||||
}
|
||||
|
||||
private func asyncStartObservation(
|
||||
private func asyncStartObservationWithoutWALSnapshot(
|
||||
from databaseAccess: DatabaseAccess,
|
||||
initialRegion: DatabaseRegion)
|
||||
{
|
||||
@@ -636,7 +698,6 @@ extension ValueConcurrentObserver {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Observing Database Transactions
|
||||
|
||||
@@ -675,13 +736,10 @@ extension ValueConcurrentObserver: TransactionObserver {
|
||||
events.databaseDidChange?()
|
||||
|
||||
// Fetch
|
||||
let future: DatabaseFuture<Reducer.Fetched>
|
||||
|
||||
switch trackingMode {
|
||||
case .constantRegion, .constantRegionRecordedFromSelection:
|
||||
future = databaseAccess.dbPool.concurrentRead { db in
|
||||
try databaseAccess.fetch(db)
|
||||
}
|
||||
setNeedsFetching(databaseAccess: databaseAccess)
|
||||
|
||||
case .nonConstantRegionRecordedFromSelection:
|
||||
// When the tracked region is not constant, we can't perform
|
||||
// concurrent fetches of observed values.
|
||||
@@ -706,26 +764,63 @@ extension ValueConcurrentObserver: TransactionObserver {
|
||||
}
|
||||
|
||||
observationState.region = observedRegion
|
||||
future = DatabaseFuture(.success(fetchedValue))
|
||||
reduce(.success(fetchedValue))
|
||||
} catch {
|
||||
stopDatabaseObservation(writerDB)
|
||||
notifyError(error)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Reduce
|
||||
//
|
||||
// Reducing is performed asynchronously, so that we do not lock
|
||||
// the writer dispatch queue longer than necessary.
|
||||
//
|
||||
// Important: reduceQueue.async guarantees the same ordering between
|
||||
// transactions and notifications!
|
||||
}
|
||||
|
||||
private func setNeedsFetching(databaseAccess: DatabaseAccess) {
|
||||
$fetchingState.update { state in
|
||||
switch state {
|
||||
case .idle:
|
||||
state = .fetching
|
||||
asyncFetch(databaseAccess: databaseAccess)
|
||||
|
||||
case .fetching:
|
||||
state = .fetchingAndNeedsFetch
|
||||
|
||||
case .fetchingAndNeedsFetch:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func asyncFetch(databaseAccess: DatabaseAccess) {
|
||||
databaseAccess.dbPool.asyncRead { [self] dbResult in
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
let fetchResult = dbResult.flatMap { db in
|
||||
Result { try databaseAccess.fetch(db) }
|
||||
}
|
||||
|
||||
self.reduce(fetchResult)
|
||||
|
||||
$fetchingState.update { state in
|
||||
switch state {
|
||||
case .idle:
|
||||
// GRDB bug
|
||||
preconditionFailure()
|
||||
|
||||
case .fetching:
|
||||
state = .idle
|
||||
|
||||
case .fetchingAndNeedsFetch:
|
||||
state = .fetching
|
||||
asyncFetch(databaseAccess: databaseAccess)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func reduce(_ fetchResult: Result<Reducer.Fetched, Error>) {
|
||||
reduceQueue.async {
|
||||
do {
|
||||
// Wait until fetch has completed
|
||||
// TODO: find a way to guarantee correct ordering without waiting for a semaphore and blocking a thread.
|
||||
let fetchedValue = try future.wait()
|
||||
let fetchedValue = try fetchResult.get()
|
||||
|
||||
let isNotifying = self.lock.synchronized { self.notificationCallbacks != nil }
|
||||
guard isNotifying else { return /* Cancelled */ }
|
||||
|
||||
@@ -722,50 +722,53 @@ extension ValueObservation {
|
||||
///
|
||||
/// ```swift
|
||||
/// // Tracks the full database
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// region: .fullDatabase,
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks the full 'player' table
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// region: Player.all(),
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks the full 'player' table
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// region: Table("player"),
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks the row with id 42 in the 'player' table
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// region: Player.filter(id: 42),
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks the 'score' column in the 'player' table
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// region: Player.select(Column("score"),
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks the 'score' column in the 'player' table
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// region: SQLRequest("SELECT score FROM player"),
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks both the 'player' and 'team' tables
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// region: Player.all(), Team.all(),
|
||||
/// fetch: { db in ... })
|
||||
/// ```
|
||||
///
|
||||
/// - parameter region: A list of observed regions.
|
||||
/// - parameter region: A region to observe.
|
||||
/// - parameter otherRegions: A list of supplementary regions
|
||||
/// to observe.
|
||||
/// - parameter fetch: The closure that fetches the observed value.
|
||||
public static func tracking<Value>(
|
||||
region: any DatabaseRegionConvertible...,
|
||||
region: any DatabaseRegionConvertible,
|
||||
_ otherRegions: any DatabaseRegionConvertible...,
|
||||
fetch: @escaping (Database) throws -> Value)
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
tracking(regions: region, fetch: fetch)
|
||||
tracking(regions: [region] + otherRegions, fetch: fetch)
|
||||
}
|
||||
|
||||
/// Creates a `ValueObservation` that notifies the fetched value whenever
|
||||
@@ -778,37 +781,37 @@ extension ValueObservation {
|
||||
///
|
||||
/// ```swift
|
||||
/// // Tracks the full database
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// regions: [.fullDatabase],
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks the full 'player' table
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// regions: [Player.all()],
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks the full 'player' table
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// regions: [Table("player")],
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks the row with id 42 in the 'player' table
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// regions: [Player.filter(id: 42)],
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks the 'score' column in the 'player' table
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// regions: [Player.select(Column("score")],
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks the 'score' column in the 'player' table
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// regions: [SQLRequest("SELECT score FROM player")],
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks both the 'player' and 'team' tables
|
||||
/// let observation = ValueObservation.tracking
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// regions: [Player.all(), Team.all()],
|
||||
/// fetch: { db in ... })
|
||||
/// ```
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
562393751DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
|
||||
56256EDE25D1BC07008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256EDD25D1BC07008C2BDD /* ForeignKey.swift */; };
|
||||
562756461E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
562B58CE2A29BC0700E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */; };
|
||||
562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
|
||||
562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
|
||||
563082EA2430B6CD00C14A05 /* DatabaseCancellable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563082E82430B6CD00C14A05 /* DatabaseCancellable.swift */; };
|
||||
@@ -470,6 +471,7 @@
|
||||
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
|
||||
56256EDD25D1BC07008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
|
||||
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
|
||||
562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
|
||||
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
|
||||
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
|
||||
56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1057,6 +1059,7 @@
|
||||
563B06DB2185E04E00B38F35 /* ValueObservation */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */,
|
||||
560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */,
|
||||
563B06FE21861D9D00B38F35 /* ValueObservationCountTests.swift */,
|
||||
563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */,
|
||||
@@ -1793,6 +1796,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
562B58CE2A29BC0700E8C75D /* Issue1383.sqlite in Resources */,
|
||||
569BBA43229066CB00478429 /* InflectionsTests.json in Resources */,
|
||||
F3BA80CD1CFB2FDD003DC1BA /* Betty.jpeg in Resources */,
|
||||
);
|
||||
|
||||
|
After Width: | Height: | Size: 90 KiB |
@@ -52,14 +52,17 @@ MAX_IOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/
|
||||
MIN_TVOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/destination.rb | grep tvOS | sort -n | head -1 | cut -wf 3 | sed 's/\(.*\)/"platform=tvOS Simulator,id=\1"/')
|
||||
MAX_TVOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/destination.rb | grep tvOS | sort -rn | head -1 | cut -wf 3 | sed 's/\(.*\)/"platform=tvOS Simulator,id=\1"/')
|
||||
|
||||
# If xcbeautify or xcpretty is available, use it for xcodebuild output
|
||||
XCPRETTY =
|
||||
XCBEAUTIFY_PATH := $(shell command -v xcbeautify 2> /dev/null)
|
||||
XCPRETTY_PATH := $(shell command -v xcpretty 2> /dev/null)
|
||||
ifdef XCBEAUTIFY_PATH
|
||||
XCPRETTY = | xcbeautify
|
||||
else ifdef XCPRETTY_PATH
|
||||
XCPRETTY = | xcpretty -c
|
||||
# If xcbeautify or xcpretty is available, use it for xcodebuild output, except in CI.
|
||||
XCPRETTY =
|
||||
ifeq ($(CI),true)
|
||||
else
|
||||
XCBEAUTIFY_PATH := $(shell command -v xcbeautify 2> /dev/null)
|
||||
XCPRETTY_PATH := $(shell command -v xcpretty 2> /dev/null)
|
||||
ifdef XCBEAUTIFY_PATH
|
||||
XCPRETTY = | xcbeautify
|
||||
else ifdef XCPRETTY_PATH
|
||||
XCPRETTY = | xcpretty -c
|
||||
endif
|
||||
endif
|
||||
|
||||
# =====
|
||||
|
||||
@@ -73,6 +73,7 @@ let package = Package(
|
||||
resources: [
|
||||
.copy("GRDBTests/Betty.jpeg"),
|
||||
.copy("GRDBTests/InflectionsTests.json"),
|
||||
.copy("GRDBTests/Issue1383.sqlite"),
|
||||
],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings)
|
||||
|
||||
@@ -1,89 +1,66 @@
|
||||

|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/groue/GRDB.swift/master/GRDB~dark.png">
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/groue/GRDB.swift/master/GRDB.png">
|
||||
<img alt="GRDB: A toolkit for SQLite databases, with a focus on application development." src="https://raw.githubusercontent.com/groue/GRDB.swift/master/GRDB.png">
|
||||
</picture>
|
||||
|
||||
<p align="center"><strong>A toolkit for SQLite databases, with a focus on application development</strong></p>
|
||||
<p align="center">
|
||||
<strong>A toolkit for SQLite databases, with a focus on application development</strong><br>
|
||||
Proudly serving the community since 2015
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://developer.apple.com/swift/"><img alt="Swift 5.7" src="https://img.shields.io/badge/swift-5.7-orange.svg?style=flat"></a>
|
||||
<a href="https://developer.apple.com/swift/"><img alt="Platforms" src="https://img.shields.io/cocoapods/p/GRDB.swift.svg"></a>
|
||||
<a href="https://github.com/groue/GRDB.swift/blob/master/LICENSE"><img alt="License" src="https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000"></a>
|
||||
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
**Latest release**: April 10, 2023 • [version 6.10.2](https://github.com/groue/GRDB.swift/tree/v6.10.2) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
|
||||
**Latest release**: June 17, 2023 • [version 6.15.1](https://github.com/groue/GRDB.swift/tree/v6.15.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+
|
||||
|
||||
| Swift version | GRDB version |
|
||||
| -------------- | ----------------------------------------------------------- |
|
||||
| **Swift 5.7+** | **v6.10.2** |
|
||||
| Swift 5.3 | [v5.26.1](https://github.com/groue/GRDB.swift/tree/v5.26.1) |
|
||||
| Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) |
|
||||
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
| Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
| Swift 4.1 | [v3.7.0](https://github.com/groue/GRDB.swift/tree/v3.7.0) |
|
||||
| Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) |
|
||||
| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
|
||||
| Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
|
||||
| Swift 3 | [v1.0](https://github.com/groue/GRDB.swift/tree/v1.0) |
|
||||
| Swift 2.3 | [v0.81.2](https://github.com/groue/GRDB.swift/tree/v0.81.2) |
|
||||
| Swift 2.2 | [v0.80.2](https://github.com/groue/GRDB.swift/tree/v0.80.2) |
|
||||
|
||||
**Contact**:
|
||||
|
||||
- Release announcements and usage tips: follow [@groue](http://twitter.com/groue) on Twitter, [@groue@hachyderm.io](https://hachyderm.io/@groue) on Mastodon.
|
||||
- Report bugs in a [Github issue](https://github.com/groue/GRDB.swift/issues/new). Make sure you check the [existing issues](https://github.com/groue/GRDB.swift/issues?q=is%3Aopen) first.
|
||||
- A question? Looking for advice? Do you wonder how to contribute? Fancy a chat? Go to the [GRDB forums](https://forums.swift.org/c/related-projects/grdb), or open a [Github issue](https://github.com/groue/GRDB.swift/issues/new).
|
||||
- A question? Looking for advice? Do you wonder how to contribute? Fancy a chat? Go to the [GitHub discussions](https://github.com/groue/GRDB.swift/discussions), or the [GRDB forums](https://forums.swift.org/c/related-projects/grdb).
|
||||
|
||||
|
||||
## What is this?
|
||||
## What is GRDB?
|
||||
|
||||
GRDB provides raw access to SQL and advanced SQLite features, because one sometimes enjoys a sharp tool. It has robust concurrency primitives, so that multi-threaded applications can efficiently use their databases. It grants your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to.
|
||||
Use this library to save your application’s permanent data into SQLite databases. It comes with built-in tools that address common needs:
|
||||
|
||||
Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMDB](https://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications.
|
||||
- **SQL Generation**
|
||||
|
||||
Enhance your application models with persistence and fetching methods, so that you don't have to deal with SQL and raw database rows when you don't want to.
|
||||
|
||||
It comes with [up-to-date documentation](#documentation), [general guides](#general-guides--good-practices), and it is [fast](https://github.com/groue/GRDB.swift/wiki/Performance).
|
||||
- **Database Observation**
|
||||
|
||||
Get notifications when database values are modified.
|
||||
|
||||
See [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) if you are looking for your favorite database library.
|
||||
- **Robust Concurrency**
|
||||
|
||||
Multi-threaded applications can efficiently use their databases, including WAL databases that support concurrent reads and writes.
|
||||
|
||||
- **Migrations**
|
||||
|
||||
Evolve the schema of your database as you ship new versions of your application.
|
||||
|
||||
- **Leverage your SQLite skills**
|
||||
|
||||
Not all developers need advanced SQLite features. But when you do, GRDB is as sharp as you want it to be. Come with your SQL and SQLite skills, or learn new ones as you go!
|
||||
|
||||
---
|
||||
|
||||
<p align="center">
|
||||
<a href="#features">Features</a> •
|
||||
<a href="#usage">Usage</a> •
|
||||
<a href="#installation">Installation</a> •
|
||||
<a href="#documentation">Documentation</a> •
|
||||
<a href="#installation">Installation</a> •
|
||||
<a href="#faq">FAQ</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Features
|
||||
|
||||
Programming tools for both database beginners and SQLite experts:
|
||||
|
||||
- [Access to raw SQL and SQLite](#sqlite-api)
|
||||
- [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies.
|
||||
- [Query Interface](#the-query-interface): A swift way to avoid the SQL language.
|
||||
- [Associations]: Relations and joins between record types.
|
||||
- [WAL Mode Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool): Extra performance for multi-threaded applications.
|
||||
- [Migrations]: Transform your database as your application evolves.
|
||||
- [Database Observation]: Observe database changes and transactions.
|
||||
- [Full-Text Search]
|
||||
- [Encryption](#encryption)
|
||||
- [Support for Custom SQLite Builds](Documentation/CustomSQLiteBuilds.md)
|
||||
|
||||
In-depth integration with our programming environment:
|
||||
|
||||
- [Swift Concurrency](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency): `try await` your database.
|
||||
- [SwiftUI](https://github.com/groue/GRDBQuery): Access and observe the database from your SwiftUI views.
|
||||
- [Combine](Documentation/Combine.md): Access and observe the database with Combine publishers.
|
||||
- [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB): Access and observe the database with RxSwift observables.
|
||||
|
||||
## Usage
|
||||
|
||||
<details open>
|
||||
@@ -98,7 +75,7 @@ let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
// 2. Define the database schema
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
@@ -106,15 +83,15 @@ try dbQueue.write { db in
|
||||
|
||||
// 3. Define a record type
|
||||
struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
var id: Int64
|
||||
var id: String
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
// 4. Access the database
|
||||
// 4. Write and read in the database
|
||||
try dbQueue.write { db in
|
||||
try Player(id: 1, name: "Arthur", score: 100).insert(db)
|
||||
try Player(id: 2, name: "Barbara", score: 1000).insert(db)
|
||||
try Player(id: "1", name: "Arthur", score: 100).insert(db)
|
||||
try Player(id: "2", name: "Barbara", score: 1000).insert(db)
|
||||
}
|
||||
|
||||
let players: [Player] = try dbQueue.read { db in
|
||||
@@ -124,23 +101,6 @@ let players: [Player] = try dbQueue.read { db in
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Activate the WAL mode</summary>
|
||||
|
||||
```swift
|
||||
import GRDB
|
||||
|
||||
// Simple database connection
|
||||
let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
|
||||
// Enhanced multithreading based on SQLite's WAL mode
|
||||
let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
```
|
||||
|
||||
See [Database Connections]
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Access to raw SQL</summary>
|
||||
|
||||
@@ -308,7 +268,6 @@ See [Database Observation], [Combine Support], [RxGRDB].
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
Documentation
|
||||
=============
|
||||
|
||||
@@ -350,24 +309,17 @@ Documentation
|
||||
|
||||
#### Good to Know
|
||||
|
||||
- [Concurrency]: How to access databases in a multi-threaded application.
|
||||
- [SwiftUI](https://github.com/groue/GRDBQuery): Access and observe the database from your SwiftUI views.
|
||||
- [Combine](Documentation/Combine.md): Access and observe the database with Combine publishers.
|
||||
- [Avoiding SQL Injection](#avoiding-sql-injection)
|
||||
- [Error Handling](#error-handling)
|
||||
- [Unicode](#unicode)
|
||||
- [Memory Management](#memory-management)
|
||||
- [Data Protection](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections)
|
||||
- [Concurrency]
|
||||
|
||||
#### General Guides & Good Practices
|
||||
|
||||
- :bulb: [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
|
||||
- :bulb: [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
|
||||
- :bulb: [Issues tagged "best practices"](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22)
|
||||
- :question: [Issues tagged "question"](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion)
|
||||
- :blue_book: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md)
|
||||
- :blue_book: [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3)
|
||||
- :blue_book: [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e)
|
||||
- :blue_book: [Unexpected SQLite with Swift](https://hackernoon.com/unexpected-sqlite-with-swift-ddc6343bcbfc)
|
||||
|
||||
- :bulb: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md)
|
||||
- :bulb: [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
|
||||
|
||||
**[FAQ]**
|
||||
|
||||
@@ -4081,6 +4033,15 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli
|
||||
|
||||
When the sequence is empty, `joined(operator: .add)` returns 0, and `joined(operator: .multiply)` returns 1.
|
||||
|
||||
- `&`, `|`, `~`, `<<`, `>>`
|
||||
|
||||
Bitwise operations (bitwise and, or, not, left shift, right shift) are derived from their Swift equivalent:
|
||||
|
||||
```swift
|
||||
// SELECT mask & 2 AS isRocky FROM planet
|
||||
Planet.select((Column("mask") & 2).forKey("isRocky"))
|
||||
```
|
||||
|
||||
- `||`
|
||||
|
||||
Concatenate several strings:
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>6.10.2</string>
|
||||
<string>6.15.1</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -443,6 +443,8 @@
|
||||
564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; };
|
||||
565A27CC27871FFF00659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27CB27871FFF00659A62 /* BackupTestCase.swift */; };
|
||||
565A27CD27871FFF00659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27CB27871FFF00659A62 /* BackupTestCase.swift */; };
|
||||
567B23172A29BFA400C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23162A29BFA400C61174 /* Issue1383.sqlite */; };
|
||||
567B23182A29BFA500C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23162A29BFA400C61174 /* Issue1383.sqlite */; };
|
||||
5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
|
||||
5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
|
||||
56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; };
|
||||
@@ -676,6 +678,7 @@
|
||||
564A1F6F226B89D6001F64F1 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
|
||||
564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
565A27CB27871FFF00659A62 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = "<group>"; };
|
||||
567B23162A29BFA400C61174 /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
|
||||
5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
|
||||
56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||
56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
|
||||
@@ -775,6 +778,7 @@
|
||||
56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */,
|
||||
564A1F6F226B89D6001F64F1 /* Betty.jpeg */,
|
||||
56419CDA24A54058004967E1 /* InflectionsTests.json */,
|
||||
567B23162A29BFA400C61174 /* Issue1383.sqlite */,
|
||||
56419CE724A54058004967E1 /* AnyCursorTests.swift */,
|
||||
56419D2324A5405D004967E1 /* AssociationAggregateTests.swift */,
|
||||
56419CC124A54056004967E1 /* AssociationBelongsToDecodableRecordTests.swift */,
|
||||
@@ -1086,6 +1090,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
567B23172A29BFA400C61174 /* Issue1383.sqlite in Resources */,
|
||||
56419DE324A54062004967E1 /* InflectionsTests.json in Resources */,
|
||||
564A2026226B89E1001F64F1 /* Betty.jpeg in Resources */,
|
||||
);
|
||||
@@ -1095,6 +1100,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
567B23182A29BFA500C61174 /* Issue1383.sqlite in Resources */,
|
||||
56419DE424A54062004967E1 /* InflectionsTests.json in Resources */,
|
||||
564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */,
|
||||
);
|
||||
|
||||
@@ -445,6 +445,8 @@
|
||||
564A215A226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; };
|
||||
565A27C927871FE500659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27C827871FE500659A62 /* BackupTestCase.swift */; };
|
||||
565A27CA27871FE500659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27C827871FE500659A62 /* BackupTestCase.swift */; };
|
||||
567B231A2A29BFE100C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23192A29BFE100C61174 /* Issue1383.sqlite */; };
|
||||
567B231B2A29BFE100C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23192A29BFE100C61174 /* Issue1383.sqlite */; };
|
||||
5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
|
||||
5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
|
||||
56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; };
|
||||
@@ -679,6 +681,7 @@
|
||||
564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; };
|
||||
565A27C827871FE500659A62 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = "<group>"; };
|
||||
567B23192A29BFE100C61174 /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
|
||||
5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
|
||||
56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||
56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
|
||||
@@ -779,6 +782,7 @@
|
||||
564A1F6F226B89D6001F64F1 /* Betty.jpeg */,
|
||||
56419F4E24A54098004967E1 /* InflectionsTests.json */,
|
||||
564A2158226C8F24001F64F1 /* db.SQLCipher3 */,
|
||||
567B23192A29BFE100C61174 /* Issue1383.sqlite */,
|
||||
56419FA524A5409E004967E1 /* AnyCursorTests.swift */,
|
||||
56419F5A24A54098004967E1 /* AssociationAggregateTests.swift */,
|
||||
56419FBD24A540A0004967E1 /* AssociationBelongsToDecodableRecordTests.swift */,
|
||||
@@ -1090,6 +1094,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
567B231A2A29BFE100C61174 /* Issue1383.sqlite in Resources */,
|
||||
5641A06A24A540A1004967E1 /* InflectionsTests.json in Resources */,
|
||||
564A2026226B89E1001F64F1 /* Betty.jpeg in Resources */,
|
||||
564A2159226C8F25001F64F1 /* db.SQLCipher3 in Resources */,
|
||||
@@ -1100,6 +1105,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
567B231B2A29BFE100C61174 /* Issue1383.sqlite in Resources */,
|
||||
5641A06B24A540A1004967E1 /* InflectionsTests.json in Resources */,
|
||||
564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */,
|
||||
564A215A226C8F25001F64F1 /* db.SQLCipher3 in Resources */,
|
||||
|
||||
@@ -815,6 +815,31 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
try XCTAssertTrue(dbQueue.read { try $0.tableExists("t2") })
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1360>
|
||||
func testEraseDatabaseOnSchemaChangeIgnoresInternalSchemaObjects() throws {
|
||||
// Given a migrator with eraseDatabaseOnSchemaChange
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
migrator.registerMigration("1") { db in
|
||||
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY)")
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
// When we add an internal schema object (sqlite_stat1)
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: """
|
||||
INSERT INTO t DEFAULT VALUES;
|
||||
ANALYZE;
|
||||
""")
|
||||
try XCTAssertTrue(db.tableExists("sqlite_stat1"))
|
||||
}
|
||||
|
||||
// Then 2nd migration does not erase database
|
||||
try migrator.migrate(dbQueue)
|
||||
try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, sql: "SELECT id FROM t") }, 1)
|
||||
}
|
||||
|
||||
func testEraseDatabaseOnSchemaChangeWithRenamedMigration() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
|
||||
@@ -3,11 +3,112 @@ import GRDB
|
||||
|
||||
class DatabasePoolTests: GRDBTestCase {
|
||||
func testDatabasePoolCreatesWalShm() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
withExtendedLifetime(dbPool) {
|
||||
let dbPool = try makeDatabasePool(filename: "test")
|
||||
try withExtendedLifetime(dbPool) {
|
||||
let fm = FileManager()
|
||||
XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-wal"))
|
||||
XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-shm"))
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
// A non-empty wal file makes sure ValueObservation can use wal snapshots.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1383>
|
||||
let walURL = URL(fileURLWithPath: dbPool.path + "-wal")
|
||||
let walSize = try walURL.resourceValues(forKeys: [.fileSizeKey]).fileSize!
|
||||
XCTAssertGreaterThan(walSize, 0)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabasePoolCreatesWalShmFromNonWalDatabase() throws {
|
||||
do {
|
||||
let dbQueue = try makeDatabaseQueue(filename: "test")
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
}
|
||||
}
|
||||
do {
|
||||
let dbPool = try makeDatabasePool(filename: "test")
|
||||
try withExtendedLifetime(dbPool) {
|
||||
let fm = FileManager()
|
||||
XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-wal"))
|
||||
XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-shm"))
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
// A non-empty wal file makes sure ValueObservation can use wal snapshots.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1383>
|
||||
let walURL = URL(fileURLWithPath: dbPool.path + "-wal")
|
||||
let walSize = try walURL.resourceValues(forKeys: [.fileSizeKey]).fileSize!
|
||||
XCTAssertGreaterThan(walSize, 0)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabasePoolCreatesWalShmFromTruncatedWalFile() throws {
|
||||
do {
|
||||
let dbPool = try makeDatabasePool(filename: "test")
|
||||
try dbPool.writeWithoutTransaction { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
try db.checkpoint(.truncate)
|
||||
}
|
||||
}
|
||||
do {
|
||||
let dbPool = try makeDatabasePool(filename: "test")
|
||||
try withExtendedLifetime(dbPool) {
|
||||
let fm = FileManager()
|
||||
XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-wal"))
|
||||
XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-shm"))
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
// A non-empty wal file makes sure ValueObservation can use wal snapshots.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1383>
|
||||
let walURL = URL(fileURLWithPath: dbPool.path + "-wal")
|
||||
let walSize = try walURL.resourceValues(forKeys: [.fileSizeKey]).fileSize!
|
||||
XCTAssertGreaterThan(walSize, 0)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabasePoolCreatesWalShmFromIssue1383() throws {
|
||||
let url = testBundle.url(forResource: "Issue1383", withExtension: "sqlite")!
|
||||
// Delete files created by previous test runs
|
||||
try? FileManager.default.removeItem(at: url.deletingLastPathComponent().appendingPathComponent("Issue1383.sqlite-wal"))
|
||||
try? FileManager.default.removeItem(at: url.deletingLastPathComponent().appendingPathComponent("Issue1383.sqlite-shm"))
|
||||
|
||||
let dbPool = try DatabasePool(path: url.path)
|
||||
try withExtendedLifetime(dbPool) {
|
||||
let fm = FileManager()
|
||||
XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-wal"))
|
||||
XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-shm"))
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
// A non-empty wal file makes sure ValueObservation can use wal snapshots.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1383>
|
||||
let walURL = URL(fileURLWithPath: dbPool.path + "-wal")
|
||||
let walSize = try walURL.resourceValues(forKeys: [.fileSizeKey]).fileSize!
|
||||
XCTAssertGreaterThan(walSize, 0)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
func testCanReadFromNewInstance() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.read { _ in }
|
||||
}
|
||||
|
||||
func testCanReadFromTruncatedWalFile() throws {
|
||||
do {
|
||||
let dbPool = try makeDatabasePool(filename: "test")
|
||||
try dbPool.writeWithoutTransaction { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
try db.checkpoint(.truncate)
|
||||
}
|
||||
}
|
||||
do {
|
||||
let dbPool = try makeDatabasePool(filename: "test")
|
||||
let count = try dbPool.read(Table("t").fetchCount)
|
||||
XCTAssertEqual(count, 0)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -124,6 +124,30 @@ extension DerivableRequest<Book> {
|
||||
}
|
||||
|
||||
class DerivableRequestTests: GRDBTestCase {
|
||||
func testAll() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try libraryMigrator.migrate(dbQueue)
|
||||
try dbQueue.inDatabase { db in
|
||||
let baseRequest = Author.all().filter(country: "FR")
|
||||
let request = baseRequest.all()
|
||||
let (sql, arguments) = try request.build(db)
|
||||
XCTAssertEqual(sql, #"SELECT * FROM "author" WHERE "country" = ?"#)
|
||||
XCTAssertEqual(arguments, ["FR"])
|
||||
}
|
||||
}
|
||||
|
||||
func testNone() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try libraryMigrator.migrate(dbQueue)
|
||||
try dbQueue.inDatabase { db in
|
||||
let baseRequest = Author.all().filter(country: "FR")
|
||||
let request = baseRequest.none()
|
||||
let (sql, arguments) = try request.build(db)
|
||||
XCTAssertEqual(sql, #"SELECT * FROM "author" WHERE ("country" = ?) AND ?"#)
|
||||
XCTAssertEqual(arguments, ["FR", false])
|
||||
}
|
||||
}
|
||||
|
||||
func testFilteredRequest() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try libraryMigrator.migrate(dbQueue)
|
||||
|
||||
@@ -334,5 +334,43 @@ class FTS5TableBuilderTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1390>
|
||||
func testIssue1390() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
guard sqlite3_libversion_number() >= 3035000 else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
struct Content: Codable, Hashable, PersistableRecord {
|
||||
var id: String
|
||||
var text: String
|
||||
}
|
||||
|
||||
try db.create(table: "content") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("text", .text)
|
||||
}
|
||||
|
||||
try db.create(virtualTable: "fts", using: FTS5()) { t in
|
||||
t.tokenizer = .porter()
|
||||
t.synchronize(withTable: "content")
|
||||
t.column("id").notIndexed()
|
||||
t.column("text")
|
||||
}
|
||||
|
||||
try db.inTransaction {
|
||||
try Content(id: "foobar", text: "baz").upsert(db)
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -778,7 +778,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
let record = try RowDecoder().decode(Record.self, from: [
|
||||
let record = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"requiredId": 1,
|
||||
"optionalName": "test1",
|
||||
"requiredDates": "[128000]",
|
||||
@@ -794,7 +794,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
let record = try RowDecoder().decode(Record.self, from: [
|
||||
let record = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"REQUIREDID": 1,
|
||||
"OPTIONALNAME": "test1",
|
||||
"REQUIREDDATES": "[128000]",
|
||||
@@ -810,7 +810,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
let record = try RowDecoder().decode(Record.self, from: [
|
||||
let record = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"requiredId": 1,
|
||||
"optionalName": nil,
|
||||
"requiredDates": "[128000]",
|
||||
@@ -826,7 +826,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
let record = try RowDecoder().decode(Record.self, from: [
|
||||
let record = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"requiredId": 1,
|
||||
"requiredDates": "[128000]",
|
||||
"optionalDates": "[null, 128000]",
|
||||
@@ -840,7 +840,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
_ = try RowDecoder().decode(Record.self, from: [
|
||||
_ = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"required_id": 1,
|
||||
"optionalName": "test1",
|
||||
"requiredDates": "[128000]",
|
||||
@@ -874,7 +874,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
let record = try RowDecoder().decode(Record.self, from: [
|
||||
let record = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"required_id": 1,
|
||||
"optional_name": "test1",
|
||||
"required_dates": "[128000]",
|
||||
@@ -890,7 +890,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
let record = try RowDecoder().decode(Record.self, from: [
|
||||
let record = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"REQUIRED_ID": 1,
|
||||
"OPTIONAL_NAME": "test1",
|
||||
"REQUIRED_DATES": "[128000]",
|
||||
@@ -906,7 +906,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
let record = try RowDecoder().decode(Record.self, from: [
|
||||
let record = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"required_id": 1,
|
||||
"optional_name": nil,
|
||||
"required_dates": "[128000]",
|
||||
@@ -922,7 +922,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
let record = try RowDecoder().decode(Record.self, from: [
|
||||
let record = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"required_id": 1,
|
||||
"required_dates": "[128000]",
|
||||
"optional_dates": "[null, 128000]",
|
||||
@@ -937,7 +937,7 @@ extension FetchableRecordDecodableTests {
|
||||
|
||||
do {
|
||||
// Matches JSONDecoder.KeyDecodingStrategy.convertFromSnakeCase behavior
|
||||
let record = try RowDecoder().decode(Record.self, from: [
|
||||
let record = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"requiredId": 1,
|
||||
"optionalName": "test1",
|
||||
"requiredDates": "[128000]",
|
||||
@@ -953,7 +953,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
_ = try RowDecoder().decode(Record.self, from: [
|
||||
_ = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"required_idx": 1,
|
||||
"optional_name": "test1",
|
||||
"required_dates": "[128000]",
|
||||
@@ -970,7 +970,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
_ = try RowDecoder().decode(IncorrectRecord.self, from: [
|
||||
_ = try FetchableRecordDecoder().decode(IncorrectRecord.self, from: [
|
||||
"required_id": 1,
|
||||
"optional_name": "test1",
|
||||
"required_dates": "[128000]",
|
||||
@@ -1008,7 +1008,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
let record = try RowDecoder().decode(Record.self, from: [
|
||||
let record = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"_requiredId": 1,
|
||||
"_optionalName": "test1",
|
||||
"_requiredDates": "[128000]",
|
||||
@@ -1024,7 +1024,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
let record = try RowDecoder().decode(Record.self, from: [
|
||||
let record = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"_requiredId": 1,
|
||||
"_optionalName": nil,
|
||||
"_requiredDates": "[128000]",
|
||||
@@ -1040,7 +1040,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
let record = try RowDecoder().decode(Record.self, from: [
|
||||
let record = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"_requiredId": 1,
|
||||
"_requiredDates": "[128000]",
|
||||
"_optionalDates": "[null, 128000]",
|
||||
@@ -1054,7 +1054,7 @@ extension FetchableRecordDecodableTests {
|
||||
}
|
||||
|
||||
do {
|
||||
_ = try RowDecoder().decode(Record.self, from: [
|
||||
_ = try FetchableRecordDecoder().decode(Record.self, from: [
|
||||
"requiredId": 1,
|
||||
"_optionalName": "test1",
|
||||
"_requiredDates": "[128000]",
|
||||
@@ -1377,7 +1377,7 @@ extension FetchableRecordDecodableTests {
|
||||
// all optionals decode missing keys are nil. This is because GRDB
|
||||
// records accept rows with missing columns, and b and c may want to
|
||||
// decode columns.
|
||||
_ = try RowDecoder().decode(Composed.self, from: [:])
|
||||
_ = try FetchableRecordDecoder().decode(Composed.self, from: [:])
|
||||
}
|
||||
|
||||
// This is a regression test for https://github.com/groue/GRDB.swift/issues/664
|
||||
@@ -1389,7 +1389,7 @@ extension FetchableRecordDecodableTests {
|
||||
var b: B
|
||||
}
|
||||
do {
|
||||
_ = try RowDecoder().decode(Composed.self, from: [:])
|
||||
_ = try FetchableRecordDecoder().decode(Composed.self, from: [:])
|
||||
XCTFail("Expected error")
|
||||
} catch DecodingError.keyNotFound {
|
||||
// a or b can not be decoded because only one key is allowed to be missing
|
||||
@@ -1409,7 +1409,7 @@ extension FetchableRecordDecodableTests {
|
||||
// - a is present
|
||||
// - root is b and c is missing, or the opposite (two possible user intents)
|
||||
let row = try Row.fetchOne(db, sql: "SELECT NULL", adapter: ScopeAdapter(["a": EmptyRowAdapter()]))!
|
||||
_ = try RowDecoder().decode(Composed.self, from: row)
|
||||
_ = try FetchableRecordDecoder().decode(Composed.self, from: row)
|
||||
XCTFail("Expected error")
|
||||
} catch let DecodingError.keyNotFound(key, context) {
|
||||
XCTAssert(["b", "c"].contains(key.stringValue))
|
||||
@@ -1419,7 +1419,7 @@ extension FetchableRecordDecodableTests {
|
||||
// - b is present
|
||||
// - root is a and c is missing, or the opposite (two possible user intents)
|
||||
let row = try Row.fetchOne(db, sql: "SELECT NULL", adapter: ScopeAdapter(["b": EmptyRowAdapter()]))!
|
||||
_ = try RowDecoder().decode(Composed.self, from: row)
|
||||
_ = try FetchableRecordDecoder().decode(Composed.self, from: row)
|
||||
XCTFail("Expected error")
|
||||
} catch let DecodingError.keyNotFound(key, context) {
|
||||
XCTAssert(["a", "c"].contains(key.stringValue))
|
||||
@@ -1429,7 +1429,7 @@ extension FetchableRecordDecodableTests {
|
||||
// - c is present
|
||||
// - root is a and b is missing, or the opposite (two possible user intents)
|
||||
let row = try Row.fetchOne(db, sql: "SELECT NULL", adapter: ScopeAdapter(["c": EmptyRowAdapter()]))!
|
||||
_ = try RowDecoder().decode(Composed.self, from: row)
|
||||
_ = try FetchableRecordDecoder().decode(Composed.self, from: row)
|
||||
XCTFail("Expected error")
|
||||
} catch let DecodingError.keyNotFound(key, context) {
|
||||
XCTAssert(["a", "b"].contains(key.stringValue))
|
||||
@@ -1494,3 +1494,45 @@ extension FetchableRecordDecodableTests {
|
||||
fileprivate extension CodingUserInfoKey {
|
||||
static let testKey = CodingUserInfoKey(rawValue: "correct")!
|
||||
}
|
||||
|
||||
// MARK: - Decodable + custom init
|
||||
|
||||
extension FetchableRecordDecodableTests {
|
||||
// Test for <https://github.com/groue/GRDB.swift/issues/1366#issuecomment-1527280022>
|
||||
func testStructWithCustomizedRowInitializer() throws {
|
||||
struct Player: Decodable, FetchableRecord {
|
||||
var id: Int
|
||||
var name: String
|
||||
var isFetched: Bool = false
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, name
|
||||
}
|
||||
|
||||
init(id: Int, name: String) {
|
||||
self.id = id
|
||||
self.name = name
|
||||
self.isFetched = false
|
||||
}
|
||||
|
||||
init(row: Row) throws {
|
||||
self = try FetchableRecordDecoder().decode(Player.self, from: row)
|
||||
self.isFetched = true
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let player = Player(id: 1, name: "Arthur")
|
||||
XCTAssertEqual(player.id, 1)
|
||||
XCTAssertEqual(player.name, "Arthur")
|
||||
XCTAssertEqual(player.isFetched, false)
|
||||
}
|
||||
|
||||
do {
|
||||
let player = try Player(row: ["id": 2, "name": "Barbara"])
|
||||
XCTAssertEqual(player.id, 2)
|
||||
XCTAssertEqual(player.name, "Barbara")
|
||||
XCTAssertEqual(player.isFetched, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1311,6 +1311,156 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Bitwise expressions
|
||||
|
||||
func testPrefixBitwiseNotOperator() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(~Col.age)),
|
||||
"SELECT * FROM \"readers\" WHERE ~\"age\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(~(Col.age + 1))),
|
||||
"SELECT * FROM \"readers\" WHERE ~(\"age\" + 1)")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(~(~Col.age + 1))),
|
||||
"SELECT * FROM \"readers\" WHERE ~((~\"age\") + 1)")
|
||||
}
|
||||
|
||||
func testInfixLeftShiftOperator() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(Col.age << 2)),
|
||||
"SELECT * FROM \"readers\" WHERE \"age\" << 2")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(2 << Col.age)),
|
||||
"SELECT * FROM \"readers\" WHERE 2 << \"age\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filterWhenConnected { _ in 2 << 2 }),
|
||||
"SELECT * FROM \"readers\" WHERE 8")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(Col.age << Col.age)),
|
||||
"SELECT * FROM \"readers\" WHERE \"age\" << \"age\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter((Col.age << Col.age) << 1)),
|
||||
"SELECT * FROM \"readers\" WHERE (\"age\" << \"age\") << 1")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(1 << [Col.age > 1, Col.age == nil].joined(operator: .and))),
|
||||
"SELECT * FROM \"readers\" WHERE 1 << ((\"age\" > 1) AND (\"age\" IS NULL))")
|
||||
}
|
||||
|
||||
func testInfixRightShiftOperator() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(Col.age >> 2)),
|
||||
"SELECT * FROM \"readers\" WHERE \"age\" >> 2")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(2 >> Col.age)),
|
||||
"SELECT * FROM \"readers\" WHERE 2 >> \"age\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filterWhenConnected { _ in 8 >> 2 }),
|
||||
"SELECT * FROM \"readers\" WHERE 2")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(Col.age >> Col.age)),
|
||||
"SELECT * FROM \"readers\" WHERE \"age\" >> \"age\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter((Col.age >> Col.age) >> 1)),
|
||||
"SELECT * FROM \"readers\" WHERE (\"age\" >> \"age\") >> 1")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(1 >> [Col.age > 1, Col.age == nil].joined(operator: .and))),
|
||||
"SELECT * FROM \"readers\" WHERE 1 >> ((\"age\" > 1) AND (\"age\" IS NULL))")
|
||||
}
|
||||
|
||||
func testInfixBitwiseAndOperator() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(Col.age & 2)),
|
||||
"SELECT * FROM \"readers\" WHERE \"age\" & 2")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(2 & Col.age)),
|
||||
"SELECT * FROM \"readers\" WHERE 2 & \"age\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filterWhenConnected { _ in 2 & 2 }),
|
||||
"SELECT * FROM \"readers\" WHERE 2")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(Col.age & Col.age)),
|
||||
"SELECT * FROM \"readers\" WHERE \"age\" & \"age\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(2 & (Col.age & Col.age))),
|
||||
"SELECT * FROM \"readers\" WHERE 2 & \"age\" & \"age\"")
|
||||
}
|
||||
|
||||
func testJoinedBitwiseAndOperator() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select([].joined(operator: .bitwiseAnd))),
|
||||
"SELECT -1 FROM \"readers\"")
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select([Col.age, Col.age].joined(operator: .bitwiseAnd))),
|
||||
"SELECT \"age\" & \"age\" FROM \"readers\"")
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select([Col.age, 2.databaseValue, Col.age].joined(operator: .bitwiseAnd))),
|
||||
"SELECT \"age\" & 2 & \"age\" FROM \"readers\"")
|
||||
|
||||
// Flattened
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select([
|
||||
[Col.age, 1.databaseValue].joined(operator: .bitwiseAnd),
|
||||
[2.databaseValue, Col.age].joined(operator: .bitwiseAnd),
|
||||
].joined(operator: .bitwiseAnd))),
|
||||
"SELECT \"age\" & 1 & 2 & \"age\" FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testInfixBitwiseOrOperator() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(Col.age | 2)),
|
||||
"SELECT * FROM \"readers\" WHERE \"age\" | 2")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(2 | Col.age)),
|
||||
"SELECT * FROM \"readers\" WHERE 2 | \"age\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filterWhenConnected { _ in 2 | 2 }),
|
||||
"SELECT * FROM \"readers\" WHERE 2")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(Col.age | Col.age)),
|
||||
"SELECT * FROM \"readers\" WHERE \"age\" | \"age\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.filter(2 | (Col.age | Col.age))),
|
||||
"SELECT * FROM \"readers\" WHERE 2 | \"age\" | \"age\"")
|
||||
}
|
||||
|
||||
func testJoinedBitwiseOrOperator() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select([].joined(operator: .bitwiseOr))),
|
||||
"SELECT 0 FROM \"readers\"")
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select([Col.age, Col.age].joined(operator: .bitwiseOr))),
|
||||
"SELECT \"age\" | \"age\" FROM \"readers\"")
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select([Col.age, 2.databaseValue, Col.age].joined(operator: .bitwiseOr))),
|
||||
"SELECT \"age\" | 2 | \"age\" FROM \"readers\"")
|
||||
|
||||
// Flattened
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select([
|
||||
[Col.age, 1.databaseValue].joined(operator: .bitwiseOr),
|
||||
[2.databaseValue, Col.age].joined(operator: .bitwiseOr),
|
||||
].joined(operator: .bitwiseOr))),
|
||||
"SELECT \"age\" | 1 | 2 | \"age\" FROM \"readers\"")
|
||||
}
|
||||
|
||||
// MARK: - IFNULL expression
|
||||
|
||||
func testIfNull() throws {
|
||||
|
||||
@@ -545,6 +545,33 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated)
|
||||
func testTableCheck_deprecated() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "test") { t in
|
||||
// Deprecated because this does not what the user means!
|
||||
t.check("a < b")
|
||||
t.column("a", .integer)
|
||||
t.column("b", .integer)
|
||||
}
|
||||
assertEqualSQL(lastSQLQuery!, """
|
||||
CREATE TABLE "test" (\
|
||||
"a" INTEGER, \
|
||||
"b" INTEGER, \
|
||||
CHECK ('a < b')\
|
||||
)
|
||||
""")
|
||||
|
||||
// Sanity check: insert should fail because the 'a < b' string is false for SQLite
|
||||
do {
|
||||
try db.execute(sql: "INSERT INTO test (a, b) VALUES (0, 1)")
|
||||
XCTFail()
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testConstraintLiteral() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
@@ -894,6 +921,29 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testCreateIndexOn() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "test") { t in
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("a", .text)
|
||||
t.column("b", .text)
|
||||
}
|
||||
|
||||
try db.create(indexOn: "test", columns: ["a"])
|
||||
assertEqualSQL(lastSQLQuery!, "CREATE INDEX \"index_test_on_a\" ON \"test\"(\"a\")")
|
||||
|
||||
try db.create(indexOn: "test", columns: ["a", "b"], options: [.unique])
|
||||
assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX \"index_test_on_a_b\" ON \"test\"(\"a\", \"b\")")
|
||||
|
||||
try db.create(indexOn: "test", columns: ["b"], options: [.unique, .ifNotExists])
|
||||
assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"index_test_on_b\" ON \"test\"(\"b\")")
|
||||
|
||||
// Sanity check
|
||||
XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["index_test_on_a", "index_test_on_a_b", "index_test_on_b"])
|
||||
}
|
||||
}
|
||||
|
||||
func testCreatePartialIndex() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
@@ -928,6 +978,51 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testDropIndexOn() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "test") { t in
|
||||
t.primaryKey("id", .integer)
|
||||
t.column("a", .text)
|
||||
t.column("b", .text)
|
||||
t.column("c", .text)
|
||||
t.column("d", .text)
|
||||
}
|
||||
try db.create(index: "custom_name_a", on: "test", columns: ["a"])
|
||||
try db.create(index: "custom_name_b", on: "test", columns: ["a", "b"])
|
||||
try db.create(indexOn: "test", columns: ["c"])
|
||||
try db.create(indexOn: "test", columns: ["c", "d"])
|
||||
|
||||
// Custom name
|
||||
try db.drop(indexOn: "test", columns: ["a"])
|
||||
assertEqualSQL(lastSQLQuery!, "DROP INDEX \"custom_name_a\"")
|
||||
|
||||
// Custom name, case insensitivity
|
||||
try db.drop(indexOn: "TEST", columns: ["A", "B"])
|
||||
assertEqualSQL(lastSQLQuery!, "DROP INDEX \"custom_name_b\"")
|
||||
|
||||
// Default name
|
||||
try db.drop(indexOn: "test", columns: ["c"])
|
||||
assertEqualSQL(lastSQLQuery!, "DROP INDEX \"index_test_on_c\"")
|
||||
|
||||
// Default name, case insensitivity
|
||||
try db.drop(indexOn: "TEST", columns: ["C", "D"])
|
||||
assertEqualSQL(lastSQLQuery!, "DROP INDEX \"index_test_on_c_d\"")
|
||||
|
||||
// Non existing index: no error
|
||||
try db.drop(indexOn: "test", columns: ["a", "b", "c", "d"])
|
||||
|
||||
// Non existing table: error
|
||||
do {
|
||||
try db.drop(indexOn: "missing", columns: ["a"])
|
||||
XCTFail("Expected error")
|
||||
} catch { }
|
||||
|
||||
// Sanity check
|
||||
XCTAssertTrue(try db.indexes(on: "test").isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
func testReindex() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
|
||||
@@ -347,6 +347,110 @@ class TableRecordUpdateTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testAssignmentBitwiseAndAssign() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try Player.updateAll(db, Columns.score &= 1)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" & 1
|
||||
""")
|
||||
|
||||
try Player.updateAll(db, Columns.score &= Columns.bonus)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" & "bonus"
|
||||
""")
|
||||
|
||||
try Player.updateAll(db, Columns.score &= -Columns.bonus)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" & (-"bonus")
|
||||
""")
|
||||
|
||||
try Player.updateAll(db, Columns.score &= Columns.bonus * 2)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" & ("bonus" * 2)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testAssignmentBitwiseOrAssign() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try Player.updateAll(db, Columns.score |= 1)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" | 1
|
||||
""")
|
||||
|
||||
try Player.updateAll(db, Columns.score |= Columns.bonus)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" | "bonus"
|
||||
""")
|
||||
|
||||
try Player.updateAll(db, Columns.score |= -Columns.bonus)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" | (-"bonus")
|
||||
""")
|
||||
|
||||
try Player.updateAll(db, Columns.score |= Columns.bonus * 2)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" | ("bonus" * 2)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testAssignmentLeftShiftAssign() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try Player.updateAll(db, Columns.score <<= 1)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" << 1
|
||||
""")
|
||||
|
||||
try Player.updateAll(db, Columns.score <<= Columns.bonus)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" << "bonus"
|
||||
""")
|
||||
|
||||
try Player.updateAll(db, Columns.score <<= -Columns.bonus)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" << (-"bonus")
|
||||
""")
|
||||
|
||||
try Player.updateAll(db, Columns.score <<= Columns.bonus * 2)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" << ("bonus" * 2)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testAssignmentRightShiftAssign() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
try Player.updateAll(db, Columns.score >>= 1)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" >> 1
|
||||
""")
|
||||
|
||||
try Player.updateAll(db, Columns.score >>= Columns.bonus)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" >> "bonus"
|
||||
""")
|
||||
|
||||
try Player.updateAll(db, Columns.score >>= -Columns.bonus)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" >> (-"bonus")
|
||||
""")
|
||||
|
||||
try Player.updateAll(db, Columns.score >>= Columns.bonus * 2)
|
||||
XCTAssertEqual(self.lastSQLQuery, """
|
||||
UPDATE "player" SET "score" = "score" >> ("bonus" * 2)
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testMultipleAssignments() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try Player.createTable(db)
|
||||
|
||||
@@ -310,43 +310,43 @@ extension XCTestCase {
|
||||
/// - `[0, 1, 2]` (unexpected value)
|
||||
/// - `[1, 0, 1]` (unexpected value)
|
||||
func assertValueObservationRecordingMatch<R, E>(
|
||||
recorded recordedValues: R,
|
||||
expected expectedValues: E,
|
||||
allowMissingLastValue: Bool = false,
|
||||
recorded: R,
|
||||
expected: E,
|
||||
_ message: @autoclosure () -> String = "",
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
where
|
||||
R: BidirectionalCollection,
|
||||
E: BidirectionalCollection,
|
||||
R: Collection,
|
||||
E: Collection,
|
||||
R.Element == E.Element,
|
||||
R.Element: Equatable
|
||||
{
|
||||
guard let value = expectedValues.last else {
|
||||
if !recordedValues.isEmpty {
|
||||
XCTFail("unexpected recorded prefix \(Array(recordedValues)) - \(message())", file: file, line: line)
|
||||
}
|
||||
return
|
||||
XCTAssertTrue(
|
||||
valueObservationRecordingMatch(recorded: recorded, expected: expected),
|
||||
"Unexpected recording \(Array(recorded)) - \(message())",
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
func valueObservationRecordingMatch<R, E>(
|
||||
recorded: R,
|
||||
expected: E)
|
||||
-> Bool
|
||||
where R: Collection,
|
||||
E: Collection,
|
||||
R.Element == E.Element,
|
||||
R.Element: Equatable
|
||||
{
|
||||
guard let first = recorded.first else {
|
||||
return expected.isEmpty
|
||||
}
|
||||
|
||||
let recordedSuffix = recordedValues.reversed().prefix(while: { $0 == value })
|
||||
let expectedSuffix = expectedValues.reversed().prefix(while: { $0 == value })
|
||||
if !allowMissingLastValue {
|
||||
// Both missing and repeated values are allowed in the recorded values.
|
||||
// This is because of asynchronous DatabasePool observations.
|
||||
if recordedSuffix.isEmpty {
|
||||
XCTFail("missing expected value \(value) - \(message()) in \(recordedValues)", file: file, line: line)
|
||||
return expected.indices.lazy
|
||||
.filter { expected[$0] == first }
|
||||
.contains {
|
||||
valueObservationRecordingMatch(
|
||||
recorded: recorded.drop(while: { $0 == first }),
|
||||
expected: expected[$0...].dropFirst())
|
||||
}
|
||||
}
|
||||
|
||||
let remainingRecordedValues = recordedValues.prefix(recordedValues.count - recordedSuffix.count)
|
||||
let remainingExpectedValues = expectedValues.prefix(expectedValues.count - expectedSuffix.count)
|
||||
assertValueObservationRecordingMatch(
|
||||
recorded: remainingRecordedValues,
|
||||
expected: remainingExpectedValues,
|
||||
// Other values can be missed
|
||||
allowMissingLastValue: true,
|
||||
message(), file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -679,112 +679,105 @@ class ValueObservationRecorderTests: FailureTestCase {
|
||||
func testAssertValueObservationRecordingMatch() {
|
||||
do {
|
||||
let expected = [3]
|
||||
assertValueObservationRecordingMatch(recorded: [3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected)
|
||||
assertFailure("failed - missing expected value 3") {
|
||||
assertValueObservationRecordingMatch(recorded: [], expected: expected)
|
||||
}
|
||||
assertFailure("failed - unexpected recorded prefix [2]", "failed - missing expected value 3") {
|
||||
assertValueObservationRecordingMatch(recorded: [2], expected: expected)
|
||||
}
|
||||
assertFailure("failed - unexpected recorded prefix [2]") {
|
||||
assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected)
|
||||
}
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3, 3], expected: expected))
|
||||
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [2], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [2, 3], expected: expected))
|
||||
}
|
||||
do {
|
||||
let expected = [2, 3]
|
||||
assertValueObservationRecordingMatch(recorded: [3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [3, 3, 3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [2, 2, 3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [2, 2, 3, 3], expected: expected)
|
||||
assertFailure("failed - missing expected value 3") {
|
||||
assertValueObservationRecordingMatch(recorded: [], expected: expected)
|
||||
}
|
||||
assertFailure("failed - missing expected value 3") {
|
||||
assertValueObservationRecordingMatch(recorded: [2], expected: expected)
|
||||
}
|
||||
assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [3]") {
|
||||
assertValueObservationRecordingMatch(recorded: [3, 2], expected: expected)
|
||||
}
|
||||
assertFailure("failed - unexpected recorded prefix [1]") {
|
||||
assertValueObservationRecordingMatch(recorded: [1, 3], expected: expected)
|
||||
}
|
||||
assertFailure("failed - unexpected recorded prefix [1]") {
|
||||
assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected)
|
||||
}
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3, 3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3, 3, 3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 2, 3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 2, 3, 3], expected: expected))
|
||||
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [2], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [3, 2], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [1, 3], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected))
|
||||
}
|
||||
do {
|
||||
let expected = [3, 3]
|
||||
assertValueObservationRecordingMatch(recorded: [3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [3, 3, 3], expected: expected)
|
||||
assertFailure("failed - missing expected value 3") {
|
||||
assertValueObservationRecordingMatch(recorded: [], expected: expected)
|
||||
}
|
||||
assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [2]") {
|
||||
assertValueObservationRecordingMatch(recorded: [2], expected: expected)
|
||||
}
|
||||
assertFailure("failed - unexpected recorded prefix [2]") {
|
||||
assertValueObservationRecordingMatch(recorded: [2, 3], expected: expected)
|
||||
}
|
||||
assertFailure("failed - unexpected recorded prefix [2, 2]") {
|
||||
assertValueObservationRecordingMatch(recorded: [2, 2, 3], expected: expected)
|
||||
}
|
||||
assertFailure("failed - unexpected recorded prefix [1, 2]") {
|
||||
assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected)
|
||||
}
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3, 3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3, 3, 3], expected: expected))
|
||||
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [2], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [2, 3], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [2, 2, 3], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected))
|
||||
}
|
||||
do {
|
||||
let expected = [1, 2, 2, 3]
|
||||
assertValueObservationRecordingMatch(recorded: [3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [3, 3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [1, 3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [1, 3, 3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [1, 1, 3, 3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [1, 2, 2, 3], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected)
|
||||
assertFailure("failed - missing expected value 3") {
|
||||
assertValueObservationRecordingMatch(recorded: [], expected: expected)
|
||||
}
|
||||
assertFailure("failed - missing expected value 3") {
|
||||
assertValueObservationRecordingMatch(recorded: [2], expected: expected)
|
||||
}
|
||||
assertFailure("failed - missing expected value 3", "failed - unexpected recorded prefix [3]") {
|
||||
assertValueObservationRecordingMatch(recorded: [3, 2], expected: expected)
|
||||
}
|
||||
assertFailure("failed - unexpected recorded prefix [2]") {
|
||||
assertValueObservationRecordingMatch(recorded: [2, 1, 3], expected: expected)
|
||||
}
|
||||
assertFailure("failed - unexpected recorded prefix [0]") {
|
||||
assertValueObservationRecordingMatch(recorded: [0, 3], expected: expected)
|
||||
}
|
||||
assertFailure("failed - unexpected recorded prefix [0]") {
|
||||
assertValueObservationRecordingMatch(recorded: [0, 1, 2, 3], expected: expected)
|
||||
}
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3, 3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 3, 3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 1, 3, 3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 2, 2, 3], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 2, 3], expected: expected))
|
||||
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [2], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [3, 2], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [2, 1, 3], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [0, 3], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [0, 1, 2, 3], expected: expected))
|
||||
}
|
||||
do {
|
||||
let expected = [1, 2, 1]
|
||||
assertValueObservationRecordingMatch(recorded: [1], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [1, 1], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [2, 1], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [1, 2, 1], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [1, 1, 2, 1], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [1, 2, 1, 1], expected: expected)
|
||||
assertValueObservationRecordingMatch(recorded: [1, 2, 2, 1], expected: expected)
|
||||
assertFailure("failed - missing expected value 1") {
|
||||
assertValueObservationRecordingMatch(recorded: [], expected: expected)
|
||||
}
|
||||
assertFailure("failed - missing expected value 1") {
|
||||
assertValueObservationRecordingMatch(recorded: [2], expected: expected)
|
||||
}
|
||||
assertFailure("failed - missing expected value 1") {
|
||||
assertValueObservationRecordingMatch(recorded: [1, 2], expected: expected)
|
||||
}
|
||||
assertFailure("failed - unexpected recorded prefix [0]") {
|
||||
assertValueObservationRecordingMatch(recorded: [0, 1], expected: expected)
|
||||
}
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 2, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 1, 2, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 2, 1, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 2, 2, 1], expected: expected))
|
||||
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [2], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [1, 2], expected: expected))
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [0, 1], expected: expected))
|
||||
}
|
||||
do {
|
||||
let expected = [1, 2, 3, 2, 1]
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 2, 3, 2, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 3, 2, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 3, 2, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 2, 2, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3, 2, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 2, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 3, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 2, 1], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 3, 1], expected: expected))
|
||||
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [3, 1, 2, 1], expected: expected))
|
||||
}
|
||||
do {
|
||||
let expected = [1, 2, 1, 3, 1, 4]
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 2, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 1, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 3, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3, 1, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 3, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 2, 1, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 1, 1, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [1, 3, 1, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [3, 1, 1, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 1, 3, 4], expected: expected))
|
||||
XCTAssertTrue(valueObservationRecordingMatch(recorded: [2, 3, 1, 4], expected: expected))
|
||||
|
||||
XCTAssertFalse(valueObservationRecordingMatch(recorded: [3, 2, 4], expected: expected))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Start observation
|
||||
var errorCaught = false
|
||||
let cancellable = observation.start(
|
||||
@@ -52,7 +52,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
onError: { _ in
|
||||
errorCaught = true
|
||||
notificationExpectation.fulfill()
|
||||
},
|
||||
},
|
||||
onChange: {
|
||||
XCTAssertFalse(errorCaught)
|
||||
nextError = TestError()
|
||||
@@ -61,7 +61,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
try! dbWriter.writeWithoutTransaction { db in
|
||||
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
@@ -201,7 +201,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { _ in
|
||||
expectation.fulfill()
|
||||
})
|
||||
})
|
||||
try withExtendedLifetime(cancellable) {
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.execute(sql: """
|
||||
@@ -245,7 +245,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { _ in
|
||||
expectation.fulfill()
|
||||
})
|
||||
})
|
||||
try withExtendedLifetime(cancellable) {
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.execute(sql: """
|
||||
@@ -289,7 +289,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { _ in
|
||||
expectation.fulfill()
|
||||
})
|
||||
})
|
||||
try withExtendedLifetime(cancellable) {
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.execute(sql: """
|
||||
@@ -349,7 +349,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
onChange: { count in
|
||||
observedCounts.append(count)
|
||||
expectation.fulfill()
|
||||
})
|
||||
})
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
XCTAssertEqual(observedCounts, [0, 0])
|
||||
@@ -389,7 +389,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
onChange: { count in
|
||||
observedCounts.append(count)
|
||||
expectation.fulfill()
|
||||
})
|
||||
})
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
XCTAssertEqual(observedCounts, [0, 0])
|
||||
@@ -552,7 +552,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
cancellable = nil
|
||||
}
|
||||
notificationExpectation.fulfill()
|
||||
})
|
||||
})
|
||||
|
||||
// notified
|
||||
try dbQueue.write { db in
|
||||
@@ -598,7 +598,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
cancellable.cancel()
|
||||
}
|
||||
notificationExpectation.fulfill()
|
||||
})
|
||||
})
|
||||
|
||||
try withExtendedLifetime(cancellable) {
|
||||
// notified
|
||||
@@ -620,11 +620,11 @@ class ValueObservationTests: GRDBTestCase {
|
||||
// Test that observation stops when cancellable is deallocated
|
||||
func test(_ dbWriter: some DatabaseWriter) throws {
|
||||
try dbWriter.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
|
||||
|
||||
|
||||
let notificationExpectation = expectation(description: "notification")
|
||||
notificationExpectation.isInverted = true
|
||||
notificationExpectation.expectedFulfillmentCount = 2
|
||||
|
||||
|
||||
do {
|
||||
var cancellable: (any DatabaseCancellable)? = nil
|
||||
_ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning
|
||||
@@ -649,13 +649,13 @@ class ValueObservationTests: GRDBTestCase {
|
||||
notificationExpectation.fulfill()
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
try dbWriter.write { db in
|
||||
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
waitForExpectations(timeout: 2, handler: nil)
|
||||
}
|
||||
|
||||
|
||||
try test(makeDatabaseQueue())
|
||||
try test(makeDatabasePool())
|
||||
}
|
||||
@@ -769,7 +769,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
.trackingConstantRegion(Table("t").fetchCount)
|
||||
.handleEvents(didCancel: { cancellationExpectation.fulfill() })
|
||||
|
||||
for try await count in try observation.values(in: writer).prefix(while: { $0 < 3 }) {
|
||||
for try await count in try observation.values(in: writer).prefix(while: { $0 <= 3 }) {
|
||||
counts.append(count)
|
||||
try await writer.write { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") }
|
||||
}
|
||||
@@ -777,9 +777,9 @@ class ValueObservationTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
let counts = try await task.value
|
||||
|
||||
// All values were published
|
||||
assertValueObservationRecordingMatch(recorded: counts, expected: [0, 1, 2])
|
||||
XCTAssertTrue(counts.contains(0))
|
||||
XCTAssertTrue(counts.contains(where: { $0 >= 2 }))
|
||||
XCTAssertEqual(counts.sorted(), counts)
|
||||
|
||||
// Observation was ended
|
||||
#if compiler(>=5.8)
|
||||
@@ -807,7 +807,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
.trackingConstantRegion(Table("t").fetchCount)
|
||||
.handleEvents(didCancel: { cancellationExpectation.fulfill() })
|
||||
|
||||
for try await count in try observation.values(in: writer, scheduling: .immediate).prefix(while: { $0 < 3 }) {
|
||||
for try await count in try observation.values(in: writer, scheduling: .immediate).prefix(while: { $0 <= 3 }) {
|
||||
counts.append(count)
|
||||
try await writer.write { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") }
|
||||
}
|
||||
@@ -815,9 +815,9 @@ class ValueObservationTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
let counts = try await task.value
|
||||
|
||||
// All values were published
|
||||
assertValueObservationRecordingMatch(recorded: counts, expected: [0, 1, 2])
|
||||
XCTAssertTrue(counts.contains(0))
|
||||
XCTAssertTrue(counts.contains(where: { $0 >= 2 }))
|
||||
XCTAssertEqual(counts.sorted(), counts)
|
||||
|
||||
// Observation was ended
|
||||
#if compiler(>=5.8)
|
||||
@@ -847,7 +847,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
|
||||
for try await count in observation.values(in: writer) {
|
||||
counts.append(count)
|
||||
if count == 2 {
|
||||
if count > 3 {
|
||||
break
|
||||
} else {
|
||||
try await writer.write { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") }
|
||||
@@ -857,9 +857,9 @@ class ValueObservationTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
let counts = try await task.value
|
||||
|
||||
// All values were published
|
||||
assertValueObservationRecordingMatch(recorded: counts, expected: [0, 1, 2])
|
||||
XCTAssertTrue(counts.contains(0))
|
||||
XCTAssertTrue(counts.contains(where: { $0 >= 2 }))
|
||||
XCTAssertEqual(counts.sorted(), counts)
|
||||
|
||||
// Observation was ended
|
||||
#if compiler(>=5.8)
|
||||
@@ -936,7 +936,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
Task {
|
||||
let observation = ValueObservation.trackingConstantRegion(Table("t").fetchCount)
|
||||
for try await count in observation.values(in: writer) {
|
||||
if count == 3 {
|
||||
if count >= 3 {
|
||||
cancelledTask.cancel()
|
||||
break
|
||||
} else {
|
||||
@@ -963,4 +963,267 @@ class ValueObservationTests: GRDBTestCase {
|
||||
try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
|
||||
try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
}
|
||||
|
||||
// An attempt at finding a regression test for <https://github.com/groue/GRDB.swift/issues/1362>
|
||||
func testManyObservations() throws {
|
||||
// We'll start many observations
|
||||
let observationCount = 100
|
||||
dbConfiguration.maximumReaderCount = 5
|
||||
|
||||
func test(_ writer: some DatabaseWriter, scheduling scheduler: some ValueObservationScheduler) throws {
|
||||
try writer.write {
|
||||
try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
let observation = ValueObservation.tracking {
|
||||
try Table("t").fetchCount($0)
|
||||
}
|
||||
|
||||
let initialValueExpectation = self.expectation(description: "")
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
initialValueExpectation.assertForOverFulfill = true
|
||||
#else
|
||||
// ValueObservation on DatabasePool will notify the first value twice
|
||||
initialValueExpectation.assertForOverFulfill = false
|
||||
#endif
|
||||
initialValueExpectation.expectedFulfillmentCount = observationCount
|
||||
|
||||
let secondValueExpectation = self.expectation(description: "")
|
||||
secondValueExpectation.expectedFulfillmentCount = observationCount
|
||||
|
||||
var cancellables: [AnyDatabaseCancellable] = []
|
||||
for _ in 0..<observationCount {
|
||||
let cancellable = observation.start(in: writer, scheduling: scheduler) { error in
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
} onChange: { count in
|
||||
if count == 0 {
|
||||
initialValueExpectation.fulfill()
|
||||
} else {
|
||||
secondValueExpectation.fulfill()
|
||||
}
|
||||
}
|
||||
cancellables.append(cancellable)
|
||||
}
|
||||
|
||||
try withExtendedLifetime(cancellables) {
|
||||
wait(for: [initialValueExpectation], timeout: 2)
|
||||
try writer.write {
|
||||
try $0.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
wait(for: [secondValueExpectation], timeout: 2)
|
||||
}
|
||||
}
|
||||
|
||||
try Test(test).run { try (DatabaseQueue(), .immediate) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .immediate) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .immediate) }
|
||||
|
||||
try Test(test).run { try (DatabaseQueue(), .async(onQueue: .main)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .async(onQueue: .main)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .async(onQueue: .main)) }
|
||||
}
|
||||
|
||||
// An attempt at finding a regression test for <https://github.com/groue/GRDB.swift/issues/1362>
|
||||
func testManyObservationsWithLongConcurrentWrite() throws {
|
||||
// We'll start many observations
|
||||
let observationCount = 100
|
||||
dbConfiguration.maximumReaderCount = 5
|
||||
|
||||
func test(_ writer: some DatabaseWriter, scheduling scheduler: some ValueObservationScheduler) throws {
|
||||
try writer.write {
|
||||
try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
|
||||
}
|
||||
let observation = ValueObservation.tracking {
|
||||
return try Table("t").fetchCount($0)
|
||||
}
|
||||
|
||||
let initialValueExpectation = self.expectation(description: "")
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
initialValueExpectation.assertForOverFulfill = true
|
||||
#else
|
||||
// ValueObservation on DatabasePool will notify the first value twice
|
||||
initialValueExpectation.assertForOverFulfill = false
|
||||
#endif
|
||||
initialValueExpectation.expectedFulfillmentCount = observationCount
|
||||
|
||||
let secondValueExpectation = self.expectation(description: "")
|
||||
secondValueExpectation.expectedFulfillmentCount = observationCount
|
||||
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
writer.asyncWriteWithoutTransaction { db in
|
||||
semaphore.signal()
|
||||
Thread.sleep(forTimeInterval: 0.5)
|
||||
}
|
||||
semaphore.wait()
|
||||
|
||||
var cancellables: [AnyDatabaseCancellable] = []
|
||||
for _ in 0..<observationCount {
|
||||
let cancellable = observation.start(in: writer, scheduling: scheduler) { error in
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
} onChange: { count in
|
||||
if count == 0 {
|
||||
initialValueExpectation.fulfill()
|
||||
} else {
|
||||
secondValueExpectation.fulfill()
|
||||
}
|
||||
}
|
||||
cancellables.append(cancellable)
|
||||
}
|
||||
|
||||
try withExtendedLifetime(cancellables) {
|
||||
wait(for: [initialValueExpectation], timeout: 2)
|
||||
try writer.write {
|
||||
try $0.execute(sql: "INSERT INTO t DEFAULT VALUES")
|
||||
}
|
||||
wait(for: [secondValueExpectation], timeout: 2)
|
||||
}
|
||||
}
|
||||
|
||||
try Test(test).run { try (DatabaseQueue(), .async(onQueue: .main)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .async(onQueue: .main)) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .async(onQueue: .main)) }
|
||||
|
||||
try Test(test).run { try (DatabaseQueue(), .immediate) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabaseQueue(path: $0), .immediate) }
|
||||
try Test(test).runAtTemporaryDatabasePath { try (DatabasePool(path: $0), .immediate) }
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1362>
|
||||
func testIssue1362() throws {
|
||||
func test(_ writer: some DatabaseWriter) throws {
|
||||
try writer.write { try $0.execute(sql: "CREATE TABLE s(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
|
||||
var cancellables = [AnyDatabaseCancellable]()
|
||||
|
||||
// Start an observation and wait until it has installed its
|
||||
// transaction observer.
|
||||
let installedExpectation = expectation(description: "transaction observer installed")
|
||||
let finalExpectation = expectation(description: "final value")
|
||||
let initialObservation = ValueObservation.trackingConstantRegion(Table("s").fetchCount)
|
||||
let cancellable = initialObservation.start(
|
||||
in: writer,
|
||||
// Immediate initial value so that the next value comes
|
||||
// from the write access that installs the transaction observer.
|
||||
scheduling: .immediate,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { count in
|
||||
if count == 1 {
|
||||
installedExpectation.fulfill()
|
||||
}
|
||||
if count == 2 {
|
||||
finalExpectation.fulfill()
|
||||
}
|
||||
})
|
||||
cancellables.append(cancellable)
|
||||
try writer.write { try $0.execute(sql: "INSERT INTO s DEFAULT VALUES") } // count = 1
|
||||
wait(for: [installedExpectation], timeout: 2)
|
||||
|
||||
// Start a write that will trigger initialObservation when we decide.
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
writer.asyncWriteWithoutTransaction { db in
|
||||
semaphore.wait()
|
||||
do {
|
||||
try db.execute(sql: "INSERT INTO s DEFAULT VALUES") // count = 2
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
// Start as many observations as there are readers
|
||||
for _ in 0..<writer.configuration.maximumReaderCount {
|
||||
let observation = ValueObservation.trackingConstantRegion(Table("s").fetchCount)
|
||||
let cancellable = observation.start(
|
||||
in: writer,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { _ in })
|
||||
cancellables.append(cancellable)
|
||||
}
|
||||
|
||||
// Wait until all observations are waiting for the writer so
|
||||
// that they can install their transaction observer.
|
||||
Thread.sleep(forTimeInterval: 0.5)
|
||||
|
||||
// Perform the write that triggers initialObservation
|
||||
semaphore.signal()
|
||||
|
||||
// initialObservation should get its final value
|
||||
wait(for: [finalExpectation], timeout: 2)
|
||||
|
||||
withExtendedLifetime(cancellables) {}
|
||||
}
|
||||
|
||||
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1383>
|
||||
func testIssue1383() throws {
|
||||
do {
|
||||
let dbPool = try makeDatabasePool(filename: "test")
|
||||
try dbPool.writeWithoutTransaction { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
// Truncate the wal file (size zero)
|
||||
try db.checkpoint(.truncate)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let dbPool = try makeDatabasePool(filename: "test")
|
||||
let observation = ValueObservation.tracking(Table("t").fetchCount)
|
||||
_ = observation.start(
|
||||
in: dbPool, scheduling: .immediate,
|
||||
onError: { error in
|
||||
XCTFail("Unexpected error \(error)")
|
||||
},
|
||||
onChange: { _ in
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1383>
|
||||
func testIssue1383_async() throws {
|
||||
do {
|
||||
let dbPool = try makeDatabasePool(filename: "test")
|
||||
try dbPool.writeWithoutTransaction { db in
|
||||
try db.execute(sql: "CREATE TABLE t(a)")
|
||||
// Truncate the wal file (size zero)
|
||||
try db.checkpoint(.truncate)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let dbPool = try makeDatabasePool(filename: "test")
|
||||
let observation = ValueObservation.tracking(Table("t").fetchCount)
|
||||
let expectation = self.expectation(description: "completion")
|
||||
expectation.assertForOverFulfill = false
|
||||
let cancellable = observation.start(
|
||||
in: dbPool,
|
||||
onError: { error in
|
||||
XCTFail("Unexpected error \(error)")
|
||||
expectation.fulfill()
|
||||
},
|
||||
onChange: { _ in
|
||||
expectation.fulfill()
|
||||
})
|
||||
withExtendedLifetime(cancellable) { _ in
|
||||
wait(for: [expectation], timeout: 2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1383>
|
||||
func testIssue1383_createWal() throws {
|
||||
let url = testBundle.url(forResource: "Issue1383", withExtension: "sqlite")!
|
||||
// Delete files created by previous test runs
|
||||
try? FileManager.default.removeItem(at: url.deletingLastPathComponent().appendingPathComponent("Issue1383.sqlite-wal"))
|
||||
try? FileManager.default.removeItem(at: url.deletingLastPathComponent().appendingPathComponent("Issue1383.sqlite-shm"))
|
||||
|
||||
let dbPool = try DatabasePool(path: url.path)
|
||||
let observation = ValueObservation.tracking(Table("t").fetchCount)
|
||||
_ = observation.start(
|
||||
in: dbPool, scheduling: .immediate,
|
||||
onError: { error in
|
||||
XCTFail("Unexpected error \(error)")
|
||||
},
|
||||
onChange: { _ in
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
@@ -14,8 +14,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/realm-core.git",
|
||||
"state" : {
|
||||
"revision" : "dd91f5f967c4ae89c37e24ab2a0315c31106648f",
|
||||
"version" : "13.6.0"
|
||||
"revision" : "f0045b71f9d3e9a6d82c711828f14222811fa6e9",
|
||||
"version" : "13.9.4"
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -23,8 +23,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/realm/realm-swift.git",
|
||||
"state" : {
|
||||
"revision" : "8ac6fe1aa5d0fb0100062d80863416a4d70de8ca",
|
||||
"version" : "10.37.0"
|
||||
"revision" : "00e098a61acdf5e8cee4e2a6292c9ec6762ba1b4",
|
||||
"version" : "10.38.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -54,7 +54,7 @@ SPM_CHECKOUTS = File.join(DERIVED_DATA, 'SourcePackages', 'checkouts')
|
||||
GRDB_VERSION = info_plist_version('Support/Info.plist')
|
||||
FMDB_VERSION = info_plist_version("#{SPM_CHECKOUTS}/fmdb/src/fmdb/Info.plist")
|
||||
SQLITE_SWIFT_VERSION = git_tag_version("#{SPM_CHECKOUTS}/SQLite.swift")
|
||||
REALM_VERSION = git_tag_version("#{SPM_CHECKOUTS}/realm-cocoa")
|
||||
REALM_VERSION = git_tag_version("#{SPM_CHECKOUTS}/realm-swift")
|
||||
|
||||
`xcodebuild -version` =~ /Xcode (.*)$/
|
||||
XCODE_VERSION = $1
|
||||
|
||||