mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-28 04:24:20 +00:00
Merge branch 'development'
This commit is contained in:
commit
06ac26a213
28 files changed
+1958
-239
No files matched your search
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
- `6.22.x` Releases - [6.22.0](#6220)
|
||||
- `6.21.x` Releases - [6.21.0](#6210)
|
||||
- `6.20.x` Releases - [6.20.0](#6200) - [6.20.1](#6201) - [6.20.2](#6202)
|
||||
- `6.19.x` Releases - [6.19.0](#6190)
|
||||
@@ -119,6 +120,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 6.22.0
|
||||
|
||||
Released November 26, 2023
|
||||
|
||||
- **New**: [#1452](https://github.com/groue/GRDB.swift/pull/1452) by [@groue](https://github.com/groue): SQLite 3.44.0, FILTER and ORDER BY clauses in aggregate functions
|
||||
- **New**: [#1460](https://github.com/groue/GRDB.swift/pull/1460) by [@groue](https://github.com/groue): Explicit change notifications help applications deal with undetected database changes.
|
||||
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
|
||||
|
||||
## 6.21.0
|
||||
|
||||
Released October 29, 2023
|
||||
|
||||
@@ -3,7 +3,7 @@ Custom SQLite Builds
|
||||
|
||||
By default, GRDB uses the version of SQLite that ships with the target operating system.
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.42.0](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.44.0](https://www.sqlite.org/changes.html).**
|
||||
|
||||
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.21.0'
|
||||
s.version = '6.22.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -57,6 +57,14 @@ extension Database {
|
||||
case let .attached(name): return "\(name).sqlite_master"
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the master sqlite table, without the schema name.
|
||||
var unqualifiedMasterTableName: String { // swiftlint:disable:this inclusive_language
|
||||
switch self {
|
||||
case .main, .attached: return "sqlite_master"
|
||||
case .temp: return "sqlite_temp_master"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier of a database table or view.
|
||||
@@ -658,9 +666,17 @@ extension Database {
|
||||
/// attached database.
|
||||
func canonicalTableName(_ tableName: String) throws -> String? {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
// Regular tables
|
||||
if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) {
|
||||
return result
|
||||
}
|
||||
|
||||
// Master table (sqlite_master, sqlite_temp_master)
|
||||
// swiftlint:disable:next inclusive_language
|
||||
let masterTableName = schemaIdentifier.unqualifiedMasterTableName
|
||||
if tableName.lowercased() == masterTableName.lowercased() {
|
||||
return masterTableName
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1367,7 +1383,7 @@ struct SchemaObject: Hashable, FetchableRecord {
|
||||
|
||||
/// All objects in a database schema (tables, views, indexes, triggers).
|
||||
struct SchemaInfo: Equatable {
|
||||
private var objects: Set<SchemaObject>
|
||||
let objects: Set<SchemaObject>
|
||||
|
||||
/// Returns whether there exists a object of given type with this name
|
||||
/// (case-insensitive).
|
||||
|
||||
@@ -79,6 +79,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``add(transactionObserver:extent:)``
|
||||
/// - ``remove(transactionObserver:)``
|
||||
/// - ``afterNextTransaction(onCommit:onRollback:)``
|
||||
/// - ``notifyChanges(in:)``
|
||||
/// - ``registerAccess(to:)``
|
||||
///
|
||||
/// ### Collations
|
||||
@@ -820,6 +821,65 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
/// Notifies that some changes were performed in the provided
|
||||
/// database region.
|
||||
///
|
||||
/// This method makes it possible to notify undetected changes, such as
|
||||
/// changes performed by another process, changes performed by
|
||||
/// direct calls to SQLite C functions, or changes to the
|
||||
/// database schema.
|
||||
/// See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
|
||||
/// for a detailed list of undetected database modifications.
|
||||
///
|
||||
/// It triggers active transaction observers (``TransactionObserver``).
|
||||
/// In particular, ``ValueObservation`` that observe the input `region`
|
||||
/// will fetch and notify a fresh value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// // Notify observers that some changes were performed in the database
|
||||
/// try db.notifyChanges(in: .fullDatabase)
|
||||
///
|
||||
/// // Notify observers that some changes were performed in the player table
|
||||
/// try db.notifyChanges(in: Player.all())
|
||||
///
|
||||
/// // Equivalent alternative
|
||||
/// try db.notifyChanges(in: Table("player"))
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This method has no effect when called from a read-only
|
||||
/// database access.
|
||||
///
|
||||
/// > Caveat: Individual rowids in the input region are ignored.
|
||||
/// > Notifying a change to a specific rowid is the same as notifying a
|
||||
/// > change in the whole table:
|
||||
/// >
|
||||
/// > ```swift
|
||||
/// > try dbQueue.write { db in
|
||||
/// > // Equivalent
|
||||
/// > try db.notifyChanges(in: Player.all())
|
||||
/// > try db.notifyChanges(in: Player.filter(id: 1))
|
||||
/// > }
|
||||
/// > ```
|
||||
public func notifyChanges(in region: some DatabaseRegionConvertible) throws {
|
||||
// Don't do anything when read-only, because read-only transactions
|
||||
// are not notified. We don't want to notify transactions observers
|
||||
// of changes, and have them wait for a commit notification that
|
||||
// will never come.
|
||||
if !isReadOnly, let observationBroker {
|
||||
let eventKinds = try region
|
||||
.databaseRegion(self)
|
||||
// Use canonical table names for case insensitivity of the input.
|
||||
.canonicalTables(self)
|
||||
.impactfulEventKinds(self)
|
||||
|
||||
try observationBroker.notifyChanges(withEventsOfKind: eventKinds)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extends the `region` argument with the database region selected by all
|
||||
/// statements executed by the closure, and all regions explicitly tracked
|
||||
/// with the ``registerAccess(to:)`` method.
|
||||
|
||||
@@ -34,19 +34,6 @@ public final class DatabaseFunction: Hashable {
|
||||
private let kind: Kind
|
||||
private var eTextRep: CInt { (SQLITE_UTF8 | (isPure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
|
||||
var functionFlags: SQLFunctionFlags {
|
||||
var flags = SQLFunctionFlags(isPure: isPure)
|
||||
|
||||
switch kind {
|
||||
case .function:
|
||||
break
|
||||
case .aggregate:
|
||||
flags.isAggregate = true
|
||||
}
|
||||
|
||||
return flags
|
||||
}
|
||||
|
||||
/// Creates an SQL function.
|
||||
///
|
||||
/// For example:
|
||||
@@ -157,6 +144,7 @@ public final class DatabaseFunction: Hashable {
|
||||
self.kind = .aggregate { Aggregate() }
|
||||
}
|
||||
|
||||
// TODO: GRDB7 -> expose ORDER BY and FILTER when we have distinct types for simple functions and aggregates.
|
||||
/// Returns an SQL expression that applies the function.
|
||||
///
|
||||
/// You can use a `DatabaseFunction` as a regular Swift function. It returns
|
||||
@@ -183,9 +171,24 @@ public final class DatabaseFunction: Hashable {
|
||||
/// }
|
||||
/// ```
|
||||
public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression {
|
||||
.function(name, arguments.map(\.sqlExpression), flags: functionFlags)
|
||||
switch kind {
|
||||
case .function:
|
||||
return .simpleFunction(
|
||||
name,
|
||||
arguments.map(\.sqlExpression),
|
||||
isPure: isPure,
|
||||
isJSONValue: false)
|
||||
case .aggregate:
|
||||
return .aggregateFunction(
|
||||
name,
|
||||
arguments.map(\.sqlExpression),
|
||||
isDistinct: false,
|
||||
ordering: nil,
|
||||
filter: nil,
|
||||
isJSONValue: false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See <https://sqlite.org/c3ref/create_function.html>
|
||||
func install(in db: Database) {
|
||||
|
||||
@@ -169,16 +169,16 @@ public struct DatabaseRegion {
|
||||
// the observed region, we optimize database observation.
|
||||
//
|
||||
// And by canonicalizing table names, we remove views, and help the
|
||||
// `isModified` methods.
|
||||
// `isModified` methods. (TODO: is this comment still accurate?
|
||||
// Isn't it about providing TransactionObserver.observes() with
|
||||
// real tables names, instead?)
|
||||
try ignoringInternalSQLiteTables().canonicalTables(db)
|
||||
}
|
||||
|
||||
/// Returns a region only made of actual tables with their canonical names.
|
||||
/// Canonical names help the `isModified` methods.
|
||||
///
|
||||
/// This method removes views (assuming no table exists with the same name
|
||||
/// as a view).
|
||||
private func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
/// This method removes views.
|
||||
func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
guard let tableRegions else { return .fullDatabase }
|
||||
var region = DatabaseRegion()
|
||||
for (table, tableRegion) in tableRegions {
|
||||
@@ -233,6 +233,44 @@ extension DatabaseRegion {
|
||||
}
|
||||
return tableRegion.contains(rowID: event.rowID)
|
||||
}
|
||||
|
||||
/// Returns an array of all event kinds that can impact this region.
|
||||
///
|
||||
/// - precondition: the region is canonical.
|
||||
func impactfulEventKinds(_ db: Database) throws -> [DatabaseEventKind] {
|
||||
if let tableRegions {
|
||||
return try tableRegions.flatMap { (table, tableRegion) -> [DatabaseEventKind] in
|
||||
let tableName = table.rawValue // canonical table name
|
||||
let columnNames: Set<String>
|
||||
if let columns = tableRegion.columns {
|
||||
columnNames = Set(columns.map(\.rawValue))
|
||||
} else {
|
||||
columnNames = try Set(db.columns(in: tableName).map(\.name))
|
||||
}
|
||||
|
||||
return [
|
||||
DatabaseEventKind.delete(tableName: tableName),
|
||||
DatabaseEventKind.insert(tableName: tableName),
|
||||
DatabaseEventKind.update(tableName: tableName, columnNames: columnNames),
|
||||
]
|
||||
}
|
||||
} else {
|
||||
// full database
|
||||
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
|
||||
let schema = try db.schema(schemaIdentifier)
|
||||
return try schema.objects
|
||||
.filter { $0.type == .table }
|
||||
.flatMap { table in
|
||||
let columnNames = try Set(db.columns(in: table.name).map(\.name))
|
||||
return [
|
||||
DatabaseEventKind.delete(tableName: table.name),
|
||||
DatabaseEventKind.insert(tableName: table.name),
|
||||
DatabaseEventKind.update(tableName: table.name, columnNames: columnNames),
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseRegion: Equatable {
|
||||
|
||||
@@ -161,6 +161,11 @@ private class DatabaseRegionObserver: TransactionObserver {
|
||||
region.isModified(byEventsOfKind: eventKind)
|
||||
}
|
||||
|
||||
func databaseDidChange() {
|
||||
isChanged = true
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if region.isModified(by: event) {
|
||||
isChanged = true
|
||||
|
||||
@@ -282,6 +282,20 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
func notifyChanges(withEventsOfKind eventKinds: [DatabaseEventKind]) throws {
|
||||
// Support for stopObservingDatabaseChangesUntilNextTransaction()
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = self
|
||||
defer {
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
}
|
||||
|
||||
for observation in transactionObservations where observation.isEnabled {
|
||||
if eventKinds.contains(where: { observation.observes(eventsOfKind: $0) }) {
|
||||
observation.databaseDidChange()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Statement execution
|
||||
|
||||
/// Returns true if there exists some transaction observer interested in
|
||||
@@ -566,6 +580,11 @@ class DatabaseObservationBroker {
|
||||
// even if we actually execute an empty deferred transaction.
|
||||
//
|
||||
// For better or for worse, let's simulate a transaction:
|
||||
//
|
||||
// 2023-11-26: I'm glad we did, because that's how we support calls
|
||||
// to `Database.notifyChanges(in:)` from an empty transaction, as a
|
||||
// way to tell transaction observers about changes performed by some
|
||||
// external connection.
|
||||
|
||||
do {
|
||||
try databaseWillCommit()
|
||||
@@ -782,6 +801,16 @@ public protocol TransactionObserver: AnyObject {
|
||||
/// from being applied on the observed tables.
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
|
||||
/// Called when the database was modified in some unspecified way.
|
||||
///
|
||||
/// This method allows a transaction observer to handle changes that are
|
||||
/// not automatically detected. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
|
||||
/// and ``Database/notifyChanges(in:)`` for more information.
|
||||
///
|
||||
/// The exact nature of changes is unknown, but they comply to the
|
||||
/// ``observes(eventsOfKind:)`` test.
|
||||
func databaseDidChange()
|
||||
|
||||
/// Called when the database is changed by an insert, update, or
|
||||
/// delete event.
|
||||
///
|
||||
@@ -857,6 +886,9 @@ extension TransactionObserver {
|
||||
public func databaseWillChange(with event: DatabasePreUpdateEvent) { }
|
||||
#endif
|
||||
|
||||
/// The default implementation does nothing.
|
||||
public func databaseDidChange() { }
|
||||
|
||||
/// Prevents the observer from receiving further change notifications until
|
||||
/// the next transaction.
|
||||
///
|
||||
@@ -889,7 +921,7 @@ extension TransactionObserver {
|
||||
guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else {
|
||||
fatalError("""
|
||||
stopObservingDatabaseChangesUntilNextTransaction must be called \
|
||||
from the databaseDidChange method
|
||||
from the `databaseDidChange()` or `databaseDidChange(with:)` methods
|
||||
""")
|
||||
}
|
||||
broker.disableUntilNextTransaction(transactionObserver: self)
|
||||
@@ -942,6 +974,11 @@ final class TransactionObservation {
|
||||
}
|
||||
#endif
|
||||
|
||||
func databaseDidChange() {
|
||||
guard isEnabled else { return }
|
||||
observer?.databaseDidChange()
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
guard isEnabled else { return }
|
||||
observer?.databaseDidChange(with: event)
|
||||
|
||||
@@ -228,9 +228,7 @@ In applications that use the background modes supported by iOS, post `resumeNoti
|
||||
|
||||
<doc:DatabaseObservation> features are not able to detect database changes performed by other processes.
|
||||
|
||||
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
|
||||
|
||||
You can trigger those notifications automatically with ``DatabaseRegionObservation``:
|
||||
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter]. You can trigger those notifications automatically with ``DatabaseRegionObservation``:
|
||||
|
||||
```swift
|
||||
// Notify all changes made to the database
|
||||
@@ -246,6 +244,8 @@ let observer = try observation.start(in: dbPool) { db in
|
||||
}
|
||||
```
|
||||
|
||||
The processes that observe the database can catch those notifications, and deal with the notified changes. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes> for some related techniques.
|
||||
|
||||
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
|
||||
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
|
||||
[WAL mode]: https://www.sqlite.org/wal.html
|
||||
|
||||
@@ -6,11 +6,7 @@
|
||||
|
||||
`DatabaseRegionObservation` tracks insertions, updates, and deletions that impact the tracked region, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
The only changes that are not notified are:
|
||||
|
||||
- Changes performed by external database connections.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
See <doc:GRDB/DatabaseRegionObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
|
||||
|
||||
`DatabaseRegionObservation` calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check ``ValueObservation`` before using `DatabaseRegionObservation`.
|
||||
|
||||
@@ -78,6 +74,30 @@ let observation = DatabaseRegionObservation(
|
||||
tracking: .fullDatabase)
|
||||
```
|
||||
|
||||
## Dealing with Undetected Changes
|
||||
|
||||
`DatabaseRegionObservation` will not notify impactful transactions whenever the database is modified in an undetectable way:
|
||||
|
||||
- Changes performed by external database connections.
|
||||
- Changes performed by SQLite statements that are not compiled and executed by GRDB.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
|
||||
To have observations notify such undetected changes, applications can take explicit action: call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Notify observations that some changes were performed in the database
|
||||
try db.notifyChanges(in: .fullDatabase)
|
||||
|
||||
// Notify observations that some changes were performed in the player table
|
||||
try db.notifyChanges(in: Player.all())
|
||||
|
||||
// Equivalent alternative
|
||||
try db.notifyChanges(in: Table("player"))
|
||||
}
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating DatabaseRegionObservation
|
||||
|
||||
@@ -25,13 +25,7 @@ Database changes are notified to the ``databaseDidChange(with:)`` callback. This
|
||||
|
||||
Transaction completions are notified to the ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
|
||||
|
||||
The only changes and transactions that are not notified are:
|
||||
|
||||
- Read-only transactions.
|
||||
- Changes and transactions performed by external database connections.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
|
||||
> Important: Some changes and transactions are not automatically notified. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes> below.
|
||||
|
||||
Notified changes are not actually written to disk until the transaction commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation:
|
||||
|
||||
@@ -189,7 +183,7 @@ class PlayerObserver: TransactionObserver {
|
||||
}
|
||||
```
|
||||
|
||||
### Support for SQLite Pre-Update Hooks
|
||||
## Support for SQLite Pre-Update Hooks
|
||||
|
||||
When SQLite is built with the `SQLITE_ENABLE_PREUPDATE_HOOK` option, `TransactionObserver` gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
|
||||
|
||||
@@ -235,6 +229,41 @@ This extra API can be activated in two ways:
|
||||
|
||||
2. Use a [custom SQLite build](http://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option.
|
||||
|
||||
## Dealing with Undetected Changes
|
||||
|
||||
The changes and transactions that are not automatically notified to transaction observers are:
|
||||
|
||||
- Read-only transactions.
|
||||
- Changes and transactions performed by external database connections.
|
||||
- Changes performed by SQLite statements that are not both compiled and executed through GRDB APIs.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
|
||||
|
||||
To notify undetected changes to transaction observers, perform an explicit call to the ``Database/notifyChanges(in:)`` `Database` method. The ``databaseDidChange()-7olv7`` callback will be called accordingly. For example:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Notify observers that some changes were performed in the database
|
||||
try db.notifyChanges(in: .fullDatabase)
|
||||
|
||||
// Notify observers that some changes were performed in the player table
|
||||
try db.notifyChanges(in: Player.all())
|
||||
|
||||
// Equivalent alternative
|
||||
try db.notifyChanges(in: Table("player"))
|
||||
}
|
||||
```
|
||||
|
||||
To notify a change in the database schema, notify a change to the `sqlite_master` table:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Notify all observers of the sqlite_master table
|
||||
try db.notifyChanges(in: Table("sqlite_master"))
|
||||
}
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Filtering Database Changes
|
||||
@@ -244,6 +273,7 @@ This extra API can be activated in two ways:
|
||||
|
||||
### Handling Database Changes
|
||||
|
||||
- ``databaseDidChange()-7olv7``
|
||||
- ``databaseDidChange(with:)``
|
||||
- ``stopObservingDatabaseChangesUntilNextTransaction()``
|
||||
- ``DatabaseEvent``
|
||||
|
||||
@@ -6,11 +6,7 @@
|
||||
|
||||
`ValueObservation` tracks insertions, updates, and deletions that impact the tracked value, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
The only changes that are not notified are:
|
||||
|
||||
- Changes performed by external database connections. See <doc:DatabaseSharing#How-to-perform-cross-process-database-observation> for more information.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
See <doc:GRDB/ValueObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
|
||||
|
||||
## ValueObservation Usage
|
||||
|
||||
@@ -174,6 +170,30 @@ let observation = ValueObservation.tracking(
|
||||
|
||||
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.
|
||||
|
||||
## Dealing with Undetected Changes
|
||||
|
||||
`ValueObservation` will not fetch and notify a fresh value whenever the database is modified in an undetectable way:
|
||||
|
||||
- Changes performed by external database connections.
|
||||
- Changes performed by SQLite statements that are not compiled and executed by GRDB.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
|
||||
To have observations notify a fresh values after such an undetected change was performed, applications can take explicit action. For example, cancel and restart observations. Alternatively, call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Notify observations that some changes were performed in the database
|
||||
try db.notifyChanges(in: .fullDatabase)
|
||||
|
||||
// Notify observations that some changes were performed in the player table
|
||||
try db.notifyChanges(in: Player.all())
|
||||
|
||||
// Equivalent alternative
|
||||
try db.notifyChanges(in: Table("player"))
|
||||
}
|
||||
```
|
||||
|
||||
## ValueObservation Performance
|
||||
|
||||
This section further describes runtime aspects of `ValueObservation`, and provides some optimization tips for demanding applications.
|
||||
|
||||
@@ -133,8 +133,8 @@ The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` pro
|
||||
- ``Database/jsonArray(_:)-469db``
|
||||
- ``Database/jsonObject(_:)``
|
||||
- ``Database/jsonQuote(_:)``
|
||||
- ``Database/jsonGroupArray(_:)``
|
||||
- ``Database/jsonGroupObject(key:value:)``
|
||||
- ``Database/jsonGroupArray(_:filter:)``
|
||||
- ``Database/jsonGroupObject(key:value:filter:)``
|
||||
|
||||
### Modify JSON values at the SQL level
|
||||
|
||||
|
||||
@@ -373,16 +373,61 @@ extension Database {
|
||||
|
||||
/// The `JSON_GROUP_ARRAY` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name")))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name ORDER BY name) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name"), orderBy: Column("name")))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
public static func jsonGroupArray(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_GROUP_ARRAY", [value.sqlExpression.jsonBuilderExpression])
|
||||
public static func jsonGroupArray(
|
||||
_ value: some SQLExpressible,
|
||||
orderBy ordering: (any SQLOrderingTerm)? = nil,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"JSON_GROUP_ARRAY",
|
||||
[value.sqlExpression.jsonBuilderExpression],
|
||||
ordering: ordering?.sqlOrdering,
|
||||
filter: filter?.sqlExpression,
|
||||
isJSONValue: true)
|
||||
}
|
||||
|
||||
/// The `JSON_GROUP_OBJECT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FROM player
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score")))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score"),
|
||||
/// filter: Column("score") > 0))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
public static func jsonGroupObject(key: some SQLExpressible, value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_GROUP_OBJECT", [key.sqlExpression, value.sqlExpression.jsonBuilderExpression])
|
||||
public static func jsonGroupObject(
|
||||
key: some SQLExpressible,
|
||||
value: some SQLExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil
|
||||
) -> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"JSON_GROUP_OBJECT",
|
||||
[key.sqlExpression, value.sqlExpression.jsonBuilderExpression],
|
||||
filter: filter?.sqlExpression,
|
||||
isJSONValue: true)
|
||||
}
|
||||
}
|
||||
#else
|
||||
@@ -779,18 +824,58 @@ extension Database {
|
||||
|
||||
/// The `JSON_GROUP_ARRAY` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name")))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonGroupArray(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_GROUP_ARRAY", [value.sqlExpression.jsonBuilderExpression])
|
||||
public static func jsonGroupArray(
|
||||
_ value: some SQLExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"JSON_GROUP_ARRAY",
|
||||
[value.sqlExpression.jsonBuilderExpression],
|
||||
filter: filter?.sqlExpression,
|
||||
isJSONValue: true)
|
||||
}
|
||||
|
||||
/// The `JSON_GROUP_OBJECT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FROM player
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score")))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score"),
|
||||
/// filter: Column("score") > 0))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonGroupObject(key: some SQLExpressible, value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_GROUP_OBJECT", [key.sqlExpression, value.sqlExpression.jsonBuilderExpression])
|
||||
public static func jsonGroupObject(
|
||||
key: some SQLExpressible,
|
||||
value: some SQLExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil
|
||||
) -> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"JSON_GROUP_OBJECT",
|
||||
[key.sqlExpression, value.sqlExpression.jsonBuilderExpression],
|
||||
filter: filter?.sqlExpression,
|
||||
isJSONValue: true)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -165,8 +165,14 @@ public struct SQLExpression {
|
||||
///
|
||||
/// <function>(<argument>, ...)
|
||||
/// <function>(DISTINCT <argument>)
|
||||
case function(String, flags: SQLFunctionFlags, arguments: [SQLExpression])
|
||||
indirect case simpleFunction(SQLSimpleFunctionInvocation)
|
||||
|
||||
/// An aggregate function call.
|
||||
///
|
||||
/// <function>(<argument>, ...)
|
||||
/// <function>(DISTINCT <argument>)
|
||||
indirect case aggregateFunction(SQLAggregateFunctionInvocation)
|
||||
|
||||
/// An expression that checks for zero or positive values.
|
||||
///
|
||||
/// <expression> = 0
|
||||
@@ -268,11 +274,11 @@ public struct SQLExpression {
|
||||
case .countAll:
|
||||
return .countAll
|
||||
|
||||
case let .function(name, flags: flags, arguments: arguments):
|
||||
return .function(
|
||||
name,
|
||||
flags: flags,
|
||||
arguments: arguments.map { $0.qualified(with: alias) })
|
||||
case let .simpleFunction(invocation):
|
||||
return .simpleFunction(invocation.qualified(with: alias))
|
||||
|
||||
case let .aggregateFunction(invocation):
|
||||
return .aggregateFunction(invocation.qualified(with: alias))
|
||||
|
||||
case let .isEmpty(expression, isNegated: isNegated):
|
||||
return .isEmpty(expression.qualified(with: alias), isNegated: isNegated)
|
||||
@@ -916,9 +922,154 @@ extension SQLExpression {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
// TODO: add missing pure functions:
|
||||
// https://www.sqlite.org/lang_aggfunc.html
|
||||
// https://www.sqlite.org/lang_datefunc.html
|
||||
// https://www.sqlite.org/lang_mathfunc.html
|
||||
private static let knownPureFunctions: Set<String> = [
|
||||
"ABS",
|
||||
"CHAR",
|
||||
"COALESCE",
|
||||
"GLOB",
|
||||
"HEX",
|
||||
"IFNULL",
|
||||
"IIF",
|
||||
"INSTR",
|
||||
"JSON",
|
||||
"JSON_ARRAY",
|
||||
"JSON_GROUP_ARRAY",
|
||||
"JSON_GROUP_OBJECT",
|
||||
"JSON_INSERT",
|
||||
"JSON_OBJECT",
|
||||
"JSON_PATCH",
|
||||
"JSON_REMOVE",
|
||||
"JSON_REPLACE",
|
||||
"JSON_SET",
|
||||
"JSON_QUOTE",
|
||||
"LENGTH",
|
||||
"LIKE",
|
||||
"LIKELIHOOD",
|
||||
"LIKELY",
|
||||
"LOAD_EXTENSION",
|
||||
"LOWER",
|
||||
"LTRIM",
|
||||
"NULLIF",
|
||||
"PRINTF",
|
||||
"QUOTE",
|
||||
"REPLACE",
|
||||
"ROUND",
|
||||
"RTRIM",
|
||||
"SOUNDEX",
|
||||
"SQLITE_COMPILEOPTION_GET",
|
||||
"SQLITE_COMPILEOPTION_USED",
|
||||
"SQLITE_SOURCE_ID",
|
||||
"SQLITE_VERSION",
|
||||
"SUBSTR",
|
||||
"TRIM",
|
||||
"TYPEOF",
|
||||
"UNICODE",
|
||||
"UNLIKELY",
|
||||
"UPPER",
|
||||
"ZEROBLOB",
|
||||
]
|
||||
|
||||
private static let knownAggregateFunctions: Set<String> = [
|
||||
"AVG",
|
||||
"COUNT",
|
||||
"GROUP_CONCAT",
|
||||
"JSON_GROUP_ARRAY",
|
||||
"JSON_GROUP_OBJECT",
|
||||
"MAX", // when single argument
|
||||
"MIN", // when single argument
|
||||
"SUM",
|
||||
"TOTAL",
|
||||
]
|
||||
|
||||
private static let knownFunctionsReturningJSONValue: Set<String> = [
|
||||
"JSON",
|
||||
"JSON_ARRAY",
|
||||
"JSON_GROUP_ARRAY",
|
||||
"JSON_GROUP_OBJECT",
|
||||
"JSON_INSERT",
|
||||
"JSON_OBJECT",
|
||||
"JSON_PATCH",
|
||||
"JSON_REMOVE",
|
||||
"JSON_REPLACE",
|
||||
"JSON_SET",
|
||||
"JSON_QUOTE",
|
||||
]
|
||||
|
||||
/// The `COUNT(*)` expression.
|
||||
static let countAll = SQLExpression(impl: .countAll)
|
||||
|
||||
/// A function call.
|
||||
static func function(_ functionName: String, _ arguments: [SQLExpression]) -> Self {
|
||||
let name = functionName.uppercased()
|
||||
|
||||
if (name == "MAX" || name == "MIN") && arguments.count > 1 {
|
||||
return .simpleFunction(
|
||||
functionName,
|
||||
arguments,
|
||||
isPure: true,
|
||||
isJSONValue: false)
|
||||
|
||||
} else if Self.knownAggregateFunctions.contains(name) {
|
||||
return .aggregateFunction(
|
||||
functionName,
|
||||
arguments,
|
||||
isJSONValue: Self.knownFunctionsReturningJSONValue.contains(name))
|
||||
|
||||
} else {
|
||||
let isJSONValue: Bool
|
||||
if name == "JSON_EXTRACT" && arguments.count > 2 {
|
||||
isJSONValue = true
|
||||
} else {
|
||||
isJSONValue = Self.knownFunctionsReturningJSONValue.contains(name)
|
||||
}
|
||||
|
||||
return .simpleFunction(
|
||||
functionName, arguments,
|
||||
isPure: Self.knownPureFunctions.contains(name),
|
||||
isJSONValue: isJSONValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// A simple function call.
|
||||
///
|
||||
/// - warning: Don't use this method for aggregate functions!
|
||||
static func simpleFunction(
|
||||
_ name: String,
|
||||
_ arguments: [SQLExpression],
|
||||
isPure: Bool = false,
|
||||
isJSONValue: Bool = false)
|
||||
-> Self
|
||||
{
|
||||
.init(impl: .simpleFunction(SQLSimpleFunctionInvocation(
|
||||
name: name,
|
||||
arguments: arguments,
|
||||
isPure: isPure,
|
||||
isJSONValue: isJSONValue)))
|
||||
}
|
||||
|
||||
/// An aggregate function call.
|
||||
static func aggregateFunction(
|
||||
_ name: String,
|
||||
_ arguments: [SQLExpression],
|
||||
isDistinct: Bool = false,
|
||||
ordering: SQLOrdering? = nil,
|
||||
filter: SQLExpression? = nil,
|
||||
isJSONValue: Bool = false)
|
||||
-> Self
|
||||
{
|
||||
.init(impl: .aggregateFunction(.init(
|
||||
name: name,
|
||||
arguments: arguments,
|
||||
isDistinct: isDistinct,
|
||||
ordering: ordering,
|
||||
filter: filter,
|
||||
isJSONValue: isJSONValue)))
|
||||
}
|
||||
|
||||
/// The `COUNT` function.
|
||||
///
|
||||
/// COUNT(<expression>)
|
||||
@@ -930,24 +1081,7 @@ extension SQLExpression {
|
||||
///
|
||||
/// COUNT(DISTINCT <expression>)
|
||||
static func countDistinct(_ expression: SQLExpression) -> Self {
|
||||
function("COUNT", [expression], flags: .init(isAggregate: true, isDistinct: true))
|
||||
}
|
||||
|
||||
/// A function call.
|
||||
///
|
||||
/// <function>(<argument>, ...)
|
||||
static func function(_ name: String, _ arguments: [SQLExpression]) -> Self {
|
||||
.init(impl: .function(
|
||||
name,
|
||||
flags: .defaultFlags(for: name, argumentCount: arguments.count),
|
||||
arguments: arguments))
|
||||
}
|
||||
|
||||
/// A function call with explicit flags.
|
||||
///
|
||||
/// <function>(<argument>, ...)
|
||||
static func function(_ name: String, _ arguments: [SQLExpression], flags: SQLFunctionFlags) -> Self {
|
||||
.init(impl: .function(name, flags: flags, arguments: arguments))
|
||||
aggregateFunction("COUNT", [expression], isDistinct: true)
|
||||
}
|
||||
|
||||
/// An expression that checks for zero or positive values.
|
||||
@@ -1071,18 +1205,8 @@ extension SQLExpression {
|
||||
case let .collated(expression, _):
|
||||
return try expression.column(db, for: alias, acceptsBijection: acceptsBijection)
|
||||
|
||||
case let .function(name, flags: flags, arguments: arguments) where !flags.isAggregate:
|
||||
guard acceptsBijection else {
|
||||
return nil
|
||||
}
|
||||
let name = name.uppercased()
|
||||
if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 {
|
||||
return try arguments[0].column(db, for: alias, acceptsBijection: acceptsBijection)
|
||||
} else if name == "IFNULL" && arguments.count == 2 && arguments[1].isConstantInRequest {
|
||||
return try arguments[0].column(db, for: alias, acceptsBijection: acceptsBijection)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
case let .simpleFunction(invocation) where acceptsBijection:
|
||||
return try invocation.column(db, for: alias)
|
||||
|
||||
case let .qualifiedFastPrimaryKey(a):
|
||||
if alias == a {
|
||||
@@ -1266,13 +1390,11 @@ extension SQLExpression {
|
||||
case .countAll:
|
||||
return "COUNT(*)"
|
||||
|
||||
case let .function(name, flags: flags, arguments: arguments):
|
||||
assert(!flags.isDistinct || flags.isAggregate, "distinct requires aggregate")
|
||||
assert(!flags.isDistinct || arguments.count == 1, "distinct requires a single argument")
|
||||
return try name
|
||||
+ (flags.isDistinct ? "(DISTINCT " : "(")
|
||||
+ arguments.map { try $0.sql(context) }.joined(separator: ", ")
|
||||
+ ")"
|
||||
case let .simpleFunction(invocation):
|
||||
return try invocation.sql(context)
|
||||
|
||||
case let .aggregateFunction(invocation):
|
||||
return try invocation.sql(context, wrappedInParenthesis: wrappedInParenthesis)
|
||||
|
||||
case let .isEmpty(expression, isNegated: isNegated):
|
||||
var resultSQL = try """
|
||||
@@ -1721,10 +1843,8 @@ extension SQLExpression {
|
||||
let .collated(expression, _):
|
||||
return expression.isConstantInRequest
|
||||
|
||||
case let .function(_, flags: flags, arguments: arguments)
|
||||
where flags.isPure && !flags.isAggregate:
|
||||
|
||||
return arguments.allSatisfy(\.isConstantInRequest)
|
||||
case let .simpleFunction(invocation):
|
||||
return invocation.isConstantInRequest
|
||||
|
||||
default:
|
||||
return false
|
||||
@@ -1783,7 +1903,7 @@ extension SQLExpression {
|
||||
case .countAll:
|
||||
return true
|
||||
|
||||
case let .function(_, flags: flags, arguments: _) where flags.isAggregate:
|
||||
case .aggregateFunction:
|
||||
return true
|
||||
|
||||
default:
|
||||
@@ -1792,131 +1912,108 @@ extension SQLExpression {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Function Flags
|
||||
|
||||
/// Information about a function
|
||||
struct SQLFunctionFlags {
|
||||
/// https://www.sqlite.org/syntax/simple-function-invocation.html
|
||||
struct SQLSimpleFunctionInvocation {
|
||||
var name: String
|
||||
var arguments: [SQLExpression]
|
||||
|
||||
/// A boolean value indicating if a function is known to be pure.
|
||||
///
|
||||
/// A false value does not provide any information.
|
||||
var isPure = false
|
||||
|
||||
/// A boolean value indicating if a function is known to be
|
||||
/// an aggregate.
|
||||
///
|
||||
/// A false value does not provide any information.
|
||||
var isAggregate = false
|
||||
|
||||
/// A boolean value indicating if the function should have `DISTINCT`
|
||||
/// in its SQL generation (as in `COUNT(DISTINCT ...)`).
|
||||
var isDistinct = false
|
||||
var isPure: Bool
|
||||
|
||||
/// A boolean value indicating if a function is known to return a
|
||||
/// JSON value.
|
||||
///
|
||||
/// A false value does not provide any information.
|
||||
var isJSONValue = false
|
||||
var isJSONValue: Bool
|
||||
|
||||
var isConstantInRequest: Bool {
|
||||
isPure && arguments.allSatisfy(\.isConstantInRequest)
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> Self {
|
||||
SQLSimpleFunctionInvocation(
|
||||
name: name,
|
||||
arguments: arguments.map { $0.qualified(with: alias) },
|
||||
isPure: isPure,
|
||||
isJSONValue: isJSONValue)
|
||||
}
|
||||
|
||||
func column(_ db: Database, for alias: TableAlias) throws -> String? {
|
||||
let name = name.uppercased()
|
||||
if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 {
|
||||
return try arguments[0].column(db, for: alias, acceptsBijection: true)
|
||||
} else if name == "IFNULL" && arguments.count == 2 && arguments[1].isConstantInRequest {
|
||||
return try arguments[0].column(db, for: alias, acceptsBijection: true)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
var sql = name
|
||||
sql += "("
|
||||
sql += try arguments
|
||||
.map { try $0.sql(context) }
|
||||
.joined(separator: ", ")
|
||||
sql += ")"
|
||||
return sql
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLFunctionFlags {
|
||||
// TODO: add missing pure functions:
|
||||
// https://www.sqlite.org/lang_aggfunc.html
|
||||
// https://www.sqlite.org/lang_datefunc.html
|
||||
// https://www.sqlite.org/lang_mathfunc.html
|
||||
private static let knownPureFunctions: Set<String> = [
|
||||
"ABS",
|
||||
"CHAR",
|
||||
"COALESCE",
|
||||
"GLOB",
|
||||
"HEX",
|
||||
"IFNULL",
|
||||
"IIF",
|
||||
"INSTR",
|
||||
"JSON",
|
||||
"JSON_ARRAY",
|
||||
"JSON_GROUP_ARRAY",
|
||||
"JSON_GROUP_OBJECT",
|
||||
"JSON_INSERT",
|
||||
"JSON_OBJECT",
|
||||
"JSON_PATCH",
|
||||
"JSON_REMOVE",
|
||||
"JSON_REPLACE",
|
||||
"JSON_SET",
|
||||
"JSON_QUOTE",
|
||||
"LENGTH",
|
||||
"LIKE",
|
||||
"LIKELIHOOD",
|
||||
"LIKELY",
|
||||
"LOAD_EXTENSION",
|
||||
"LOWER",
|
||||
"LTRIM",
|
||||
"NULLIF",
|
||||
"PRINTF",
|
||||
"QUOTE",
|
||||
"REPLACE",
|
||||
"ROUND",
|
||||
"RTRIM",
|
||||
"SOUNDEX",
|
||||
"SQLITE_COMPILEOPTION_GET",
|
||||
"SQLITE_COMPILEOPTION_USED",
|
||||
"SQLITE_SOURCE_ID",
|
||||
"SQLITE_VERSION",
|
||||
"SUBSTR",
|
||||
"TRIM",
|
||||
"TYPEOF",
|
||||
"UNICODE",
|
||||
"UNLIKELY",
|
||||
"UPPER",
|
||||
"ZEROBLOB",
|
||||
]
|
||||
/// https://www.sqlite.org/syntax/aggregate-function-invocation.html
|
||||
struct SQLAggregateFunctionInvocation {
|
||||
var name: String
|
||||
var arguments: [SQLExpression]
|
||||
var isDistinct = false
|
||||
var ordering: SQLOrdering? = nil // SQLite 3.44.0+
|
||||
var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) SQLite 3.30+
|
||||
|
||||
private static let knownAggregateFunctions: Set<String> = [
|
||||
"AVG",
|
||||
"COUNT",
|
||||
"GROUP_CONCAT",
|
||||
"JSON_GROUP_ARRAY",
|
||||
"JSON_GROUP_OBJECT",
|
||||
"MAX", // when single argument
|
||||
"MIN", // when single argument
|
||||
"SUM",
|
||||
"TOTAL",
|
||||
]
|
||||
/// A boolean value indicating if a function is known to return a
|
||||
/// JSON value.
|
||||
///
|
||||
/// A false value does not provide any information.
|
||||
var isJSONValue: Bool
|
||||
|
||||
private static let knownFunctionsReturningJSONValue: Set<String> = [
|
||||
"JSON",
|
||||
"JSON_ARRAY",
|
||||
"JSON_GROUP_ARRAY",
|
||||
"JSON_GROUP_OBJECT",
|
||||
"JSON_INSERT",
|
||||
"JSON_OBJECT",
|
||||
"JSON_PATCH",
|
||||
"JSON_REMOVE",
|
||||
"JSON_REPLACE",
|
||||
"JSON_SET",
|
||||
"JSON_QUOTE",
|
||||
]
|
||||
func qualified(with alias: TableAlias) -> Self {
|
||||
SQLAggregateFunctionInvocation(
|
||||
name: name,
|
||||
arguments: arguments.map { $0.qualified(with: alias) },
|
||||
isDistinct: isDistinct,
|
||||
ordering: ordering?.qualified(with: alias),
|
||||
filter: filter?.qualified(with: alias),
|
||||
isJSONValue: isJSONValue)
|
||||
}
|
||||
|
||||
/// Infers flags from the function name and number of arguments.
|
||||
static func defaultFlags(for functionName: String, argumentCount: Int) -> Self {
|
||||
var flags = SQLFunctionFlags()
|
||||
func sql(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
var sql = name
|
||||
|
||||
let name = functionName.uppercased()
|
||||
|
||||
flags.isPure = Self.knownPureFunctions.contains(name)
|
||||
|
||||
if (name == "MAX" || name == "MIN") && argumentCount > 1 {
|
||||
flags.isPure = true
|
||||
if isDistinct {
|
||||
sql += "(DISTINCT "
|
||||
} else {
|
||||
flags.isAggregate = Self.knownAggregateFunctions.contains(name.uppercased())
|
||||
sql += "("
|
||||
}
|
||||
|
||||
if name == "JSON_EXTRACT" && argumentCount > 2 {
|
||||
flags.isJSONValue = true
|
||||
} else {
|
||||
flags.isJSONValue = Self.knownFunctionsReturningJSONValue.contains(name)
|
||||
sql += try arguments
|
||||
.map { try $0.sql(context) }
|
||||
.joined(separator: ", ")
|
||||
|
||||
if let ordering {
|
||||
sql += try " ORDER BY \(ordering.sql(context))"
|
||||
}
|
||||
|
||||
return flags
|
||||
sql += ")"
|
||||
|
||||
if let filter {
|
||||
sql += try " FILTER (WHERE \(filter.sql(context)))"
|
||||
}
|
||||
|
||||
if wrappedInParenthesis && filter != nil {
|
||||
return "(\(sql))"
|
||||
} else {
|
||||
return sql
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1960,8 +2057,11 @@ extension SQLExpression {
|
||||
case let .collated(expression, _):
|
||||
return expression.isJSONValue
|
||||
|
||||
case let .function(_, flags: flags, arguments: _):
|
||||
return flags.isJSONValue
|
||||
case let .simpleFunction(invocation):
|
||||
return invocation.isJSONValue
|
||||
|
||||
case let .aggregateFunction(invocation):
|
||||
return invocation.isJSONValue
|
||||
|
||||
default:
|
||||
return false
|
||||
@@ -2044,6 +2144,7 @@ extension SQLExpressible where Self == Column {
|
||||
///
|
||||
/// - ``abs(_:)-5l6xp``
|
||||
/// - ``average(_:)``
|
||||
/// - ``average(_:filter:)``
|
||||
/// - ``capitalized``
|
||||
/// - ``count(_:)``
|
||||
/// - ``count(distinct:)``
|
||||
@@ -2056,9 +2157,13 @@ extension SQLExpressible where Self == Column {
|
||||
/// - ``localizedUppercased``
|
||||
/// - ``lowercased``
|
||||
/// - ``min(_:)``
|
||||
/// - ``min(_:filter:)``
|
||||
/// - ``max(_:)``
|
||||
/// - ``max(_:filter:)``
|
||||
/// - ``sum(_:)``
|
||||
/// - ``sum(_:filter:)``
|
||||
/// - ``total(_:)``
|
||||
/// - ``total(_:filter:)``
|
||||
/// - ``uppercased``
|
||||
/// - ``SQLDateModifier``
|
||||
///
|
||||
|
||||
@@ -10,6 +10,40 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.function("ABS", [value.sqlExpression])
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `AVG` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // AVG(length)
|
||||
/// average(Column("length"))
|
||||
/// ```
|
||||
public func average(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction("AVG", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `AVG` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // AVG(length) FILTER (WHERE length > 0)
|
||||
/// average(Column("length"), filter: Column("length") > 0)
|
||||
/// ```
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
|
||||
public func average(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: some SQLSpecificExpressible)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"AVG", [value.sqlExpression],
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `AVG` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
@@ -19,8 +53,9 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
/// average(Column("length"))
|
||||
/// ```
|
||||
public func average(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.function("AVG", [value.sqlExpression])
|
||||
.aggregateFunction("AVG", [value.sqlExpression])
|
||||
}
|
||||
#endif
|
||||
|
||||
/// The `COUNT` SQL function.
|
||||
///
|
||||
@@ -72,6 +107,38 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.function("LENGTH", [value.sqlExpression])
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `MAX` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // MAX(score)
|
||||
/// max(Column("score"))
|
||||
/// ```
|
||||
public func max(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction("MAX", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `MAX` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // MAX(score) FILTER (WHERE score < 0)
|
||||
/// max(Column("score"), filter: Column("score") < 0)
|
||||
/// ```
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
|
||||
public func max(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: some SQLSpecificExpressible)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction("MAX", [value.sqlExpression], filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `MAX` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
@@ -81,7 +148,40 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
/// max(Column("score"))
|
||||
/// ```
|
||||
public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.function("MAX", [value.sqlExpression])
|
||||
.aggregateFunction("MAX", [value.sqlExpression])
|
||||
}
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `MIN` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // MIN(score)
|
||||
/// min(Column("score"))
|
||||
/// ```
|
||||
public func min(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction("MIN", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `MIN` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // MIN(score) FILTER (WHERE score > 0)
|
||||
/// min(Column("score"), filter: Column("score") > 0)
|
||||
/// ```
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
|
||||
public func min(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: some SQLSpecificExpressible)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction("MIN", [value.sqlExpression], filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `MIN` SQL function.
|
||||
@@ -93,7 +193,55 @@ public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
/// min(Column("score"))
|
||||
/// ```
|
||||
public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.function("MIN", [value.sqlExpression])
|
||||
.aggregateFunction("MIN", [value.sqlExpression])
|
||||
}
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `SUM` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SUM(amount)
|
||||
/// sum(Column("amount"))
|
||||
/// ```
|
||||
///
|
||||
/// See also ``total(_:)``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
public func sum(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
orderBy ordering: (any SQLOrderingTerm)? = nil,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression
|
||||
{
|
||||
.aggregateFunction(
|
||||
"SUM", [value.sqlExpression],
|
||||
ordering: ordering?.sqlOrdering,
|
||||
filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `SUM` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SUM(amount) FILTER (WHERE amount > 0)
|
||||
/// sum(Column("amount"), filter: Column("amount") > 0)
|
||||
/// ```
|
||||
///
|
||||
/// See also ``total(_:)``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
|
||||
public func sum(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: some SQLSpecificExpressible)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"SUM", [value.sqlExpression],
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `SUM` SQL function.
|
||||
@@ -109,7 +257,55 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.function("SUM", [value.sqlExpression])
|
||||
.aggregateFunction("SUM", [value.sqlExpression])
|
||||
}
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `TOTAL` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // TOTAL(amount)
|
||||
/// total(Column("amount"))
|
||||
/// ```
|
||||
///
|
||||
/// See also ``sum(_:)``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
public func total(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
orderBy ordering: (any SQLOrderingTerm)? = nil,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression
|
||||
{
|
||||
.aggregateFunction(
|
||||
"TOTAL", [value.sqlExpression],
|
||||
ordering: ordering?.sqlOrdering,
|
||||
filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `TOTAL` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // TOTAL(amount) FILTER (WHERE amount > 0)
|
||||
/// total(Column("amount"), filter: Column("amount") > 0)
|
||||
/// ```
|
||||
///
|
||||
/// See also ``total(_:)``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
|
||||
public func total(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: some SQLSpecificExpressible)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"TOTAL", [value.sqlExpression],
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `TOTAL` SQL function.
|
||||
@@ -125,8 +321,9 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
public func total(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.function("TOTAL", [value.sqlExpression])
|
||||
.aggregateFunction("TOTAL", [value.sqlExpression])
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - String functions
|
||||
|
||||
|
||||
@@ -710,6 +710,13 @@ extension ValueConcurrentObserver: TransactionObserver {
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidChange() {
|
||||
// Database was modified!
|
||||
observationState.isModified = true
|
||||
// We can stop observing the current transaction
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if let region = observationState.region, region.isModified(by: event) {
|
||||
// Database was modified!
|
||||
|
||||
@@ -345,6 +345,13 @@ extension ValueWriteOnlyObserver: TransactionObserver {
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidChange() {
|
||||
// Database was modified!
|
||||
observationState.isModified = true
|
||||
// We can stop observing the current transaction
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if let region = observationState.region, region.isModified(by: event) {
|
||||
// Database was modified!
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<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**: October 29, 2023 • [version 6.21.0](https://github.com/groue/GRDB.swift/tree/v6.21.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
|
||||
**Latest release**: November 26, 2023 • [version 6.22.0](https://github.com/groue/GRDB.swift/tree/v6.22.0) • [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+
|
||||
|
||||
|
||||
+1
-1
Submodule SQLiteCustom/src updated: 59f4dc65f0...31e6aa6618.
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>6.21.0</string>
|
||||
<string>6.22.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -224,6 +224,42 @@ class DatabaseRegionObservationTests: GRDBTestCase {
|
||||
XCTAssertEqual(count, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func test_DatabaseRegionObservation_is_triggered_by_explicit_change_notification() throws {
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
try dbQueue1.write { db in
|
||||
try db.execute(sql: "CREATE TABLE test(a)")
|
||||
}
|
||||
|
||||
let undetectedExpectation = expectation(description: "undetected")
|
||||
undetectedExpectation.isInverted = true
|
||||
|
||||
let detectedExpectation = expectation(description: "detected")
|
||||
|
||||
let observation = DatabaseRegionObservation(tracking: Table("test"))
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue1,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { _ in
|
||||
undetectedExpectation.fulfill()
|
||||
detectedExpectation.fulfill()
|
||||
})
|
||||
|
||||
try withExtendedLifetime(cancellable) {
|
||||
// Change performed from external connection is not detected...
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
try dbQueue2.write { db in
|
||||
try db.execute(sql: "INSERT INTO test (a) VALUES (1)")
|
||||
}
|
||||
wait(for: [undetectedExpectation], timeout: 2)
|
||||
|
||||
// ... until we perform an explicit change notification
|
||||
try dbQueue1.write { db in
|
||||
try db.notifyChanges(in: Table("test"))
|
||||
}
|
||||
wait(for: [detectedExpectation], timeout: 2)
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for https://github.com/groue/GRDB.swift/issues/514
|
||||
// TODO: uncomment and make this test pass.
|
||||
|
||||
@@ -395,4 +395,27 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
try await test(setup(makeDatabaseQueue()))
|
||||
try await test(setup(makeDatabasePool()))
|
||||
}
|
||||
|
||||
/// A test related to <https://github.com/groue/GRDB.swift/issues/1456>
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
func testAsyncWriteThenRead() async throws {
|
||||
/// An async read performed after an async write should see the write.
|
||||
func test(_ dbWriter: some DatabaseWriter) async throws {
|
||||
try await dbWriter.write { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t (id INTEGER PRIMARY KEY);
|
||||
INSERT INTO t VALUES (1);
|
||||
""")
|
||||
}
|
||||
|
||||
let count = try await dbWriter.read { db in
|
||||
try Table("t").fetchCount(db)
|
||||
}
|
||||
|
||||
XCTAssertEqual(count, 1)
|
||||
}
|
||||
|
||||
try await test(makeDatabaseQueue())
|
||||
try await test(makeDatabasePool())
|
||||
}
|
||||
}
|
||||
@@ -1211,6 +1211,72 @@ final class JSONExpressionsTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_Database_jsonGroupArray_filter() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
guard sqlite3_libversion_number() >= 3038000 else {
|
||||
throw XCTSkip("JSON support is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else {
|
||||
throw XCTSkip("JSON support is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
try makeDatabaseQueue().inDatabase { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.column("name", .text)
|
||||
t.column("info", .jsonText)
|
||||
}
|
||||
let player = Table("player")
|
||||
let nameColumn = Column("name")
|
||||
let infoColumn = JSONColumn("info")
|
||||
|
||||
try assertEqualSQL(db, player.select(Database.jsonGroupArray(nameColumn, filter: length(nameColumn) > 0)), """
|
||||
SELECT JSON_GROUP_ARRAY("name") FILTER (WHERE LENGTH("name") > 0) FROM "player"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, player.select(Database.jsonGroupArray(infoColumn, filter: length(nameColumn) > 0)), """
|
||||
SELECT JSON_GROUP_ARRAY(JSON("info")) FILTER (WHERE LENGTH("name") > 0) FROM "player"
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
func test_Database_jsonGroupArray_order() throws {
|
||||
// Prevent SQLCipher failures
|
||||
guard sqlite3_libversion_number() >= 3044000 else {
|
||||
throw XCTSkip("JSON support is not available")
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().inDatabase { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.column("name", .text)
|
||||
t.column("info", .jsonText)
|
||||
}
|
||||
let player = Table("player")
|
||||
let nameColumn = Column("name")
|
||||
let infoColumn = JSONColumn("info")
|
||||
|
||||
try assertEqualSQL(db, player.select(Database.jsonGroupArray(nameColumn, orderBy: nameColumn)), """
|
||||
SELECT JSON_GROUP_ARRAY("name" ORDER BY "name") FROM "player"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, player.select(Database.jsonGroupArray(infoColumn, orderBy: nameColumn.desc)), """
|
||||
SELECT JSON_GROUP_ARRAY(JSON("info") ORDER BY "name" DESC) FROM "player"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, player.select(Database.jsonGroupArray(nameColumn, orderBy: nameColumn, filter: length(nameColumn) > 0)), """
|
||||
SELECT JSON_GROUP_ARRAY("name" ORDER BY "name") FILTER (WHERE LENGTH("name") > 0) FROM "player"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, player.select(Database.jsonGroupArray(infoColumn, orderBy: nameColumn.desc, filter: length(nameColumn) > 0)), """
|
||||
SELECT JSON_GROUP_ARRAY(JSON("info") ORDER BY "name" DESC) FILTER (WHERE LENGTH("name") > 0) FROM "player"
|
||||
""")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func test_Database_jsonGroupObject() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
@@ -1238,6 +1304,33 @@ final class JSONExpressionsTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_Database_jsonGroupObject_filter() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
guard sqlite3_libversion_number() >= 3038000 else {
|
||||
throw XCTSkip("JSON support is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else {
|
||||
throw XCTSkip("JSON support is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
try makeDatabaseQueue().inDatabase { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.column("key", .text)
|
||||
t.column("value", .jsonText)
|
||||
}
|
||||
let player = Table("player")
|
||||
let keyColumn = Column("key")
|
||||
let valueColumn = JSONColumn("value")
|
||||
|
||||
try assertEqualSQL(db, player.select(Database.jsonGroupObject(key: keyColumn, value: valueColumn, filter: length(valueColumn) > 0)), """
|
||||
SELECT JSON_GROUP_OBJECT("key", JSON("value")) FILTER (WHERE LENGTH("value") > 0) FROM "player"
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func test_index_and_generated_columns() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
|
||||
@@ -1505,6 +1505,28 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT AVG(\"age\" / 2) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testAvgExpression_filter() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
guard sqlite3_libversion_number() >= 3030000 else {
|
||||
throw XCTSkip("FILTER clause on aggregate functions is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else {
|
||||
throw XCTSkip("FILTER clause on aggregate functions is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(average(Col.age, filter: Col.age > 0))),
|
||||
"SELECT AVG(\"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(average(Col.age / 2, filter: Col.age > 0))),
|
||||
"SELECT AVG(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testLengthExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -1524,6 +1546,28 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT MIN(\"age\" / 2) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testMinExpression_filter() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
guard sqlite3_libversion_number() >= 3030000 else {
|
||||
throw XCTSkip("FILTER clause on aggregate functions is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else {
|
||||
throw XCTSkip("FILTER clause on aggregate functions is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(min(Col.age, filter: Col.age > 0))),
|
||||
"SELECT MIN(\"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(min(Col.age / 2, filter: Col.age > 0))),
|
||||
"SELECT MIN(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testMaxExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -1535,6 +1579,28 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT MAX(\"age\" / 2) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testMaxExpression_filter() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
guard sqlite3_libversion_number() >= 3030000 else {
|
||||
throw XCTSkip("FILTER clause on aggregate functions is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else {
|
||||
throw XCTSkip("FILTER clause on aggregate functions is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(max(Col.age, filter: Col.age < 0))),
|
||||
"SELECT MAX(\"age\") FILTER (WHERE \"age\" < 0) FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(max(Col.age / 2, filter: Col.age < 0))),
|
||||
"SELECT MAX(\"age\" / 2) FILTER (WHERE \"age\" < 0) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testSumExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -1546,6 +1612,52 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT SUM(\"age\" / 2) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testSumExpression_filter() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
guard sqlite3_libversion_number() >= 3030000 else {
|
||||
throw XCTSkip("FILTER clause on aggregate functions is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else {
|
||||
throw XCTSkip("FILTER clause on aggregate functions is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(sum(Col.age, filter: Col.age > 0))),
|
||||
"SELECT SUM(\"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(sum(Col.age / 2, filter: Col.age > 0))),
|
||||
"SELECT SUM(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
func testSumExpression_order() throws {
|
||||
// Prevent SQLCipher failures
|
||||
guard sqlite3_libversion_number() >= 3044000 else {
|
||||
throw XCTSkip("ORDER BY clause on aggregate functions is not available")
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(sum(Col.age, orderBy: Col.age))),
|
||||
"SELECT SUM(\"age\" ORDER BY \"age\") FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(sum(Col.age / 2, orderBy: Col.age.desc))),
|
||||
"SELECT SUM(\"age\" / 2 ORDER BY \"age\" DESC) FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(sum(Col.age, orderBy: Col.age, filter: Col.age > 0))),
|
||||
"SELECT SUM(\"age\" ORDER BY \"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(sum(Col.age / 2, orderBy: Col.age.desc, filter: Col.age > 0))),
|
||||
"SELECT SUM(\"age\" / 2 ORDER BY \"age\" DESC) FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
}
|
||||
#endif
|
||||
|
||||
func testTotalExpression() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -1557,6 +1669,51 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
|
||||
"SELECT TOTAL(\"age\" / 2) FROM \"readers\"")
|
||||
}
|
||||
|
||||
func testTotalExpression_filter() throws {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Prevent SQLCipher failures
|
||||
guard sqlite3_libversion_number() >= 3030000 else {
|
||||
throw XCTSkip("FILTER clause on aggregate functions is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else {
|
||||
throw XCTSkip("FILTER clause on aggregate functions is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(total(Col.age, filter: Col.age > 0))),
|
||||
"SELECT TOTAL(\"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(total(Col.age / 2, filter: Col.age > 0))),
|
||||
"SELECT TOTAL(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
func testTotalExpression_order() throws {
|
||||
// Prevent SQLCipher failures
|
||||
guard sqlite3_libversion_number() >= 3044000 else {
|
||||
throw XCTSkip("ORDER BY clause on aggregate functions is not available")
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(total(Col.age, orderBy: Col.age))),
|
||||
"SELECT TOTAL(\"age\" ORDER BY \"age\") FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(total(Col.age / 2, orderBy: Col.age.desc))),
|
||||
"SELECT TOTAL(\"age\" / 2 ORDER BY \"age\" DESC) FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(total(Col.age, orderBy: Col.age, filter: Col.age > 0))),
|
||||
"SELECT TOTAL(\"age\" ORDER BY \"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
XCTAssertEqual(
|
||||
sql(dbQueue, tableRequest.select(total(Col.age / 2, orderBy: Col.age.desc, filter: Col.age > 0))),
|
||||
"SELECT TOTAL(\"age\" / 2 ORDER BY \"age\" DESC) FILTER (WHERE \"age\" > 0) FROM \"readers\"")
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - LIKE operator
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -523,6 +523,49 @@ class ValueObservationTests: GRDBTestCase {
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Unspecified Changes
|
||||
|
||||
func test_ValueObservation_is_triggered_by_explicit_change_notification() throws {
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
try dbQueue1.write { db in
|
||||
try db.execute(sql: "CREATE TABLE test(a)")
|
||||
}
|
||||
|
||||
let undetectedExpectation = expectation(description: "undetected")
|
||||
undetectedExpectation.expectedFulfillmentCount = 2 // initial value and change
|
||||
undetectedExpectation.isInverted = true
|
||||
|
||||
let detectedExpectation = expectation(description: "detected")
|
||||
detectedExpectation.expectedFulfillmentCount = 2 // initial value and change
|
||||
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try Table("test").fetchCount(db)
|
||||
}
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue1,
|
||||
scheduling: .immediate,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { _ in
|
||||
undetectedExpectation.fulfill()
|
||||
detectedExpectation.fulfill()
|
||||
})
|
||||
|
||||
try withExtendedLifetime(cancellable) {
|
||||
// Change performed from external connection is not detected...
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
try dbQueue2.write { db in
|
||||
try db.execute(sql: "INSERT INTO test (a) VALUES (1)")
|
||||
}
|
||||
wait(for: [undetectedExpectation], timeout: 2)
|
||||
|
||||
// ... until we perform an explicit change notification
|
||||
try dbQueue1.write { db in
|
||||
try db.notifyChanges(in: Table("test"))
|
||||
}
|
||||
wait(for: [detectedExpectation], timeout: 2)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cancellation
|
||||
|
||||
func testCancellableLifetime() throws {
|
||||
|
||||
Reference in new issue
Block a user