Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2019-08-06 12:10:28 +02:00
commit fb54c2ae45
171 files changed
+6289 -2492

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
included:
- GRDB
disabled_rules:
- cyclomatic_complexity
- file_length
- force_cast
- force_try
- function_body_length
- function_parameter_count
- identifier_name
- is_disjoint
- nesting
- opening_brace
- redundant_optional_initialization
- syntactic_sugar
- todo
- trailing_comma
- trailing_whitespace
- type_body_length
- type_name
- unused_setter_value
opt_in_rules:
- anyobject_protocol
- array_init
- attributes
- closure_spacing
- collection_alignment
- contains_over_first_not_nil
- convenience_type
- empty_count
- empty_string
- explicit_init
- fatal_error_message
- first_where
- joined_default_parameter
- last_where
- legacy_multiple
- legacy_random
- modifier_order
- no_extension_access_modifier
- overridden_super_call
- pattern_matching_keywords
- prohibited_super_call
- reduce_into
- redundant_type_annotation
- sorted_first_last
- toggle_bool
- unused_declaration
- unused_import
- unused_private_declaration
- yoda_condition
vertical_whitespace:
max_empty_lines: 2
+31 -15
View File
@@ -146,8 +146,16 @@ jobs:
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.2
env:
- TID=CocoaPods GRDB
script: make test_install_GRDB_CocoaPods
- TID=CocoaPods GRDB (framework)
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- stage: Test Installation Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.2
env:
- TID=CocoaPods GRDB (static)
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- stage: Test Installation Xcode 10.2
@@ -297,10 +305,10 @@ jobs:
# env:
# - TID=SQLCipher 4
# script: make test_framework_SQLCipher4
#
# ###########################################
# ## Test Installation Xcode 10
#
###########################################
## Test Installation Xcode 10
# # Manual Install
# - stage: Test Installation Xcode 10
# gemfile: .ci/gemfiles/Gemfile.travis
@@ -316,15 +324,23 @@ jobs:
# env:
# - TID=CocoaPods Lint
# script: make test_CocoaPodsLint_GRDB
#
# # CocoaPods Install GRDB
# - stage: Test Installation Xcode 10
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10
# env:
# - TID=CocoaPods GRDB
# script: make test_install_GRDB_CocoaPods
#
# CocoaPods Install GRDB
- stage: Test Installation Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=CocoaPods GRDB (framework)
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- stage: Test Installation Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=CocoaPods GRDB (static)
script: make test_install_GRDB_CocoaPods_static
# # SPM Install
# - stage: Test Installation Xcode 10
# gemfile: .ci/gemfiles/Gemfile.travis
+98
View File
@@ -5,12 +5,15 @@ All notable changes to this project will be documented in this file.
GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library.
<!--
[Next Release](#next-release)
-->
#### 4.x Releases
- `4.2.x` Releases - [4.2.0](#420)
- `4.1.x` Releases - [4.1.0](#410) | [4.1.1](#411)
- `4.0.x` Releases - [4.0.0](#400) | [4.0.1](#401)
@@ -51,10 +54,105 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection:
- [0.110.0](#01100), ...
<!--
## Next Release
-->
## 4.2.0
Released August 6, 2019 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v4.1.1...v4.2.0)
**New**
- [#570](https://github.com/groue/GRDB.swift/pull/570) by [@chrisballinger](https://github.com/chrisballinger): Allow Swift static library integration via CocoaPods
- [#576](https://github.com/groue/GRDB.swift/pull/576): Expose table name and full-text filtering methods to DerivableRequest
- [#586](https://github.com/groue/GRDB.swift/pull/586): Automatic region tracking for ValueObservation
**Fixed**
- [#560](https://github.com/groue/GRDB.swift/pull/560) by [@bellebethcooper](https://github.com/bellebethcooper): Minor typo fix
- [#562](https://github.com/groue/GRDB.swift/pull/562): Fix crash when using more than one DatabaseCollation
- [#577](https://github.com/groue/GRDB.swift/pull/577): Rename `aliased(_:)` methods to `forKey(_:)`
- [#585](https://github.com/groue/GRDB.swift/pull/585): Fix use of SQLite authorizers
**Other**
- [#563](https://github.com/groue/GRDB.swift/pull/563): More tests for eager loading of hasMany associations
- [#574](https://github.com/groue/GRDB.swift/pull/574): SwiftLint
### Documentation Diff
The [ValueObservation](README.md#valueobservation) chapter has been updated so that it fosters the new `ValueObservation.tracking(value:)` method. Other ways to define observations are now described as optimizations.
### API Diff
```diff
-protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest { }
+protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { }
-extension QueryInterfaceRequest {
- func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<T>
-}
-extension QueryInterfaceRequest {
- func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<T>
-}
+extension TableRequest where Self: FilteredRequest {
+ func matching(_ pattern: FTS3Pattern?) -> Self
+}
+extension TableRequest where Self: FilteredRequest {
+ func matching(_ pattern: FTS5Pattern?) -> Self
+}
protocol Association: DerivableRequest {
- associatedtype OriginRowDecoder
+ associatedtype OriginRowDecoder: TableRecord
}
-struct BelongsToAssociation<Origin, Destination>: AssociationToOne { }
-struct HasManyAssociation<Origin, Destination>: AssociationToMany { }
-struct HasManyThroughAssociation<Origin, Destination>: AssociationToMany { }
-struct HasOneAssociation<Origin, Destination>: AssociationToOne { }
-struct HasOneThroughAssociation<Origin, Destination>: AssociationToOne { }
+struct BelongsToAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToOne { }
+struct HasManyAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToMany { }
+struct HasManyThroughAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToMany { }
+struct HasOneAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToOne { }
+struct HasOneThroughAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToOne { }
-struct QueryInterfaceRequest<T>: DerivableRequest { }
+struct QueryInterfaceRequest<T>: FilteredRequest, OrderedRequest, SelectionRequest, TableRequuest { }
+extension QueryInterfaceRequest: JoinableRequest where T: TableRecord { }
+extension QueryInterfaceRequest: DerivableRequest where T: TableRecord { }
extension AssociationAggregate {
+ @available(*, deprecated, renamed: "forKey(_:)")
func aliased(_ name: String) -> AssociationAggregate<RowDecoder>
+ func forKey(_ name: String) -> AssociationAggregate<RowDecoder>
+ @available(*, deprecated, renamed: "forKey(_:)")
func aliased(_ key: CodingKey) -> AssociationAggregate<RowDecoder>
+ func forKey(_ key: CodingKey) -> AssociationAggregate<RowDecoder>
}
extension SQLSpecificExpressible {
+ @available(*, deprecated, renamed: "forKey(_:)")
func aliased(_ name: String) -> SQLSelectable
+ func forKey(_ name: String) -> SQLSelectable
+ @available(*, deprecated, renamed: "forKey(_:)")
func aliased(_ key: CodingKey) -> SQLSelectable
+ func forKey(_ key: CodingKey) -> SQLSelectable
}
extension ValueObservation where Reducer == Void {
+ static func tracking<Value>(fetch: @escaping (Database) throws -> Value) -> ValueObservation<ValueReducers.Fetch<Value>>
}
```
## 4.1.1
Released June 22, 2019 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v4.1.0...v4.1.1)
+5 -11
View File
@@ -88,7 +88,6 @@ The ideas, in alphabetical order:
- [Reactive Database Observation]
- [SQL Console in the Debugger]
- [SQLCipher in a Shared App Container]
- [Static Library]
- [Typed Expressions]
@@ -292,14 +291,16 @@ There are several SQLite features that GRDB could natively support:
- [Windows Functions](https://www.sqlite.org/windowfunctions.html)
- [More ideas](https://www.sqlite.org/lang.html)
See [issue #575](https://github.com/groue/GRDB.swift/issues/575) for more information and guidance about the implementation of extra table alterations.
### Reactive Database Observation
:baby: Starter Task
We already have the [RxGRDB] companion library, which offers [RxSwift](https://github.com/ReactiveX/RxSwift) bindings.
We already have the [GRDBCombine](http://github.com/groue/GRDBCombine) and [RxGRDB] companion libraries.
We need more choices of reactive engines.
More choices of reactive engines would help more developers enjoy GRDB.
### SQL Console in the Debugger
@@ -316,13 +317,6 @@ Sometimes one needs, in lldb, a console similar to the [Command Line Shell For S
See issue [#302](https://github.com/groue/GRDB.swift/issues/302).
### Static Library
:question: Unknown Difficulty :hammer: Tooling
It would be nice to be able to integrate GRDB as a static library.
### Typed Expressions
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
@@ -376,12 +370,12 @@ Features that blur this focus are non-goals:
[JSON]: #json
[Linux]: #linux
[More SQL Generation]: #more-sql-generation
[Reactive Database Observation]: #reactive-database-observation
[Records: Splitting Database Encoding from Ability to Write in the Database]: #records-splitting-database-encoding-from-ability-to-write-in-the-database
[Non-Goals]: #non-goals
[Report Bugs]: #report-bugs
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[Concurrency]: #concurrency
[Static Library]: #static-library
[Sponsoring and Professional Support]: #sponsoring-and-professional-support
[SQL Console in the Debugger]: #sql-console-in-the-debugger
[SQLCipher in a Shared App Container]: #sqlcipher-in-a-shared-app-container
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -71,7 +71,10 @@ class PlayersViewController: UITableViewController {
private func configureTitle() {
// Track changes in the number of players
playerCountObserver = playersRequest.observationForCount().start(
let observation = ValueObservation.tracking { db in
try Player.fetchCount(db)
}
playerCountObserver = observation.start(
in: dbQueue,
onError: { error in
fatalError("Unexpected error: \(error)")
+9 -22
View File
@@ -822,19 +822,6 @@ let novels = try author
.fetchAll(db) // [Book]
```
Those requests can also turn out useful when you want to track their changes with [database observation tools] like [ValueObservation]:
```swift
// Track changes in the author's books:
let author: Author = ...
author.books.observationForAll().start(
in: dbQueue,
onError: { error in ... },
onChange: { (books: [Book]) in
print("Author's book have changed")
})
```
## Joining And Prefetching Associated Records
@@ -1791,14 +1778,14 @@ The default name is built from the aggregating method, the **[association key](#
Those default names are lost whenever an aggregate is modified (negated, added, multiplied, whatever).
You can name or rename aggregates with the `aliased` method:
You can name or rename aggregates with the `forKey` method:
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var numberOfBooks: Int
}
let numberOfBooks = Author.books.count.aliased("numberOfBooks") // <--
let numberOfBooks = Author.books.count.forKey("numberOfBooks") // <--
let request = Author.annotated(with: numberOfBooks)
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
@@ -1806,7 +1793,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var hasBooks: Bool
}
let hasBooks = (Author.books.isEmpty == false).aliased("hasBooks") // <--
let hasBooks = (Author.books.isEmpty == false).forKey("hasBooks") // <--
let request = Author.annotated(with: hasBooks)
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
@@ -1814,7 +1801,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var workCount: Int
}
let workCount = (Author.books.count + Author.paintings.count).aliased("workCount") // <--
let workCount = (Author.books.count + Author.paintings.count).forKey("workCount") // <--
let request = Author.annotated(with: workCount)
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
@@ -1827,7 +1814,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
var numberOfBooks: Int
static func all() -> QueryInterfaceRequest<AuthorInfo> {
let numberOfBooks = Author.books.count.aliased(CodingKey.numberOfBooks) // <--
let numberOfBooks = Author.books.count.forKey(CodingKey.numberOfBooks) // <--
return Author
.annotated(with: numberOfBooks)
.asRequest(of: AuthorInfo.self)
@@ -2041,7 +2028,7 @@ Aggregates can be modified and combined with Swift operators:
```swift
let workCount = Author.books.count + Author.paintings.count)
let request = Author.annotated(with: workCount.aliased("workCount"))
let request = Author.annotated(with: workCount.forKey("workCount"))
```
- IFNULL operator `??`
@@ -2133,7 +2120,7 @@ In this other example, the `Author.books` and `Author.paintings` have the distin
let aggregate = Author.books.count + // association key "books"
Author.paintings.count // association key "paintings"
let request = Author.annotated(with: aggregate.aliased("workCount"))
let request = Author.annotated(with: aggregate.forKey("workCount"))
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
@@ -2201,11 +2188,11 @@ But in the following example, we use the same association `Author.books` twice,
let novelCount = Author.books // association key "books"
.filter(Column("kind") == "novel")
.count
.aliased("novelCount")
.forKey("novelCount")
let theatrePlayCount = Author.books // association key "books"
.filter(Column("kind") == "theatrePlay")
.count
.aliased("theatrePlayCount")
.forKey("theatrePlayCount")
let request = Author.annotated(with: novelCount, theatrePlayCount)
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
+1 -1
View File
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```sh
cd [GRDB directory]
git checkout v4.1.1
git checkout v4.2.0
git submodule update --init SQLiteCustom/src
````
+4 -5
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '4.1.1'
s.version = '4.2.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
@@ -9,21 +9,20 @@ Pod::Spec.new do |s|
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
s.module_name = 'GRDB'
s.swift_versions = ['4.2', '5']
s.swift_versions = ['4.2', '5.0']
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.9'
s.watchos.deployment_target = '2.0'
s.module_map = 'Support/module.modulemap'
s.default_subspec = 'standard'
s.subspec 'standard' do |ss|
ss.source_files = 'GRDB/**/*.swift', 'Support/*.h'
ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h'
ss.framework = 'Foundation'
ss.library = 'sqlite3'
end
s.subspec 'SQLCipher' do |ss|
ss.source_files = 'GRDB/**/*.swift', 'Support/*.h'
ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h'
ss.framework = 'Foundation'
ss.dependency 'SQLCipher', '>= 3.4.0'
ss.xcconfig = {
+51 -4
View File
@@ -461,6 +461,8 @@
5674A7231F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; };
5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; };
5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; };
5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */; };
5676FBA722F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */; };
567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
567DAF1F1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
@@ -1129,6 +1131,7 @@
5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = "<group>"; };
5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = "<group>"; };
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = "<group>"; };
5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
@@ -1233,8 +1236,8 @@
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = "<group>"; };
56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-10.2.1/Realm.framework"; sourceTree = "<group>"; };
56B8C2411CA1758F00510325 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = "Realm/build/osx/swift-10.2.1/RealmSwift.framework"; sourceTree = "<group>"; };
56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-10.3/Realm.framework"; sourceTree = "<group>"; };
56B8C2411CA1758F00510325 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = "Realm/build/osx/swift-10.3/RealmSwift.framework"; sourceTree = "<group>"; };
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = "<group>"; };
56B9649C1DA51B4C0002DA19 /* FTS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5.swift; sourceTree = "<group>"; };
56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerDescriptor.swift; sourceTree = "<group>"; };
@@ -1628,6 +1631,7 @@
563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */,
563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */,
563B06BC2185CCD300B38F35 /* ValueObservationReducerTests.swift */,
5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */,
563B0704218627F700B38F35 /* ValueObservationRowTests.swift */,
563B06C12185D29F00B38F35 /* ValueObservationSchedulingTests.swift */,
);
@@ -2313,6 +2317,7 @@
56E5D7C61B4D3FED00430942 /* Frameworks */,
56E5D7C71B4D3FED00430942 /* Headers */,
56E5D7C81B4D3FED00430942 /* Resources */,
56EB54FA22C9115E00850069 /* Swiftlint */,
);
buildRules = (
);
@@ -2367,6 +2372,7 @@
DC3773EF19C8CBB3004FCF85 /* Frameworks */,
DC3773F019C8CBB3004FCF85 /* Headers */,
DC3773F119C8CBB3004FCF85 /* Resources */,
56EB54F322C8ED5100850069 /* Swiftlint */,
);
buildRules = (
);
@@ -2559,6 +2565,45 @@
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
56EB54F322C8ED5100850069 /* Swiftlint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = Swiftlint;
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n";
};
56EB54FA22C9115E00850069 /* Swiftlint */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
name = Swiftlint;
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi\n";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
560C97D41C0E22D300BF8471 /* Sources */ = {
isa = PBXSourcesBuildPhase;
@@ -3051,6 +3096,7 @@
568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */,
56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
5676FBA722F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */,
5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */,
569BBA28228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */,
@@ -3250,6 +3296,7 @@
5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */,
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */,
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */,
56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */,
56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */,
569BBA27228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */,
@@ -3497,7 +3544,7 @@
DEBUG_INFORMATION_FORMAT = dwarf;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.2.1",
"$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.3",
);
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = Tests/Info.plist;
@@ -3520,7 +3567,7 @@
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.2.1",
"$(PROJECT_DIR)/Tests/Performance/Realm/build/osx/swift-10.3",
);
GCC_NO_COMMON_BLOCKS = YES;
INFOPLIST_FILE = Tests/Info.plist;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
LastUpgradeVersion = "1030"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+7 -7
View File
@@ -1,11 +1,11 @@
import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// Configuration for a DatabaseQueue or DatabasePool.
@@ -85,7 +85,7 @@ public struct Configuration {
public var passphrase: String?
#endif
/// If set, allows custom configuration to be run every time
/// a new connection is opened.
///
@@ -181,9 +181,9 @@ public struct Configuration {
// MARK: - Not Public
var threadingMode: Database.ThreadingMode = .`default`
var SQLiteConnectionDidOpen: (() -> ())?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> ())?
var SQLiteConnectionDidClose: (() -> ())?
var SQLiteConnectionDidOpen: (() -> Void)?
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
var SQLiteConnectionDidClose: (() -> Void)?
var SQLiteOpenFlags: Int32 {
let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
return threadingMode.SQLiteOpenFlags | readWriteFlags
+27 -16
View File
@@ -29,7 +29,10 @@ extension Sequence {
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>> {
public func flatMap<SegmentOfResult: Cursor>(
_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult)
-> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>>
{
return AnyCursor(self).flatMap(transform)
}
}
@@ -76,7 +79,7 @@ extension Set {
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
/// `suffix`.
public protocol Cursor : class {
public protocol Cursor: AnyObject {
/// The type of element traversed by the cursor.
associatedtype Element
@@ -141,7 +144,9 @@ extension Cursor {
/// Returns a cursor over the concatenated non-nil results of mapping
/// transform over this cursor.
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
public func compactMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?)
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
{
return map(transform).filter { $0 != nil }.map { $0! }
}
@@ -190,7 +195,7 @@ extension Cursor {
public func dropFirst() -> DropFirstCursor<Self> {
return dropFirst(1)
}
/// Returns an array containing all but the given number of final
/// elements.
///
@@ -243,13 +248,19 @@ extension Cursor {
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>> {
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
-> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>>
where SegmentOfResult: Sequence
{
return flatMap { try AnyCursor(transform($0)) }
}
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, SegmentOfResult>> {
public func flatMap<SegmentOfResult>(_ transform: @escaping (Element) throws -> SegmentOfResult)
-> FlattenCursor<MapCursor<Self, SegmentOfResult>>
where SegmentOfResult: Cursor
{
return map(transform).joined()
}
@@ -503,7 +514,7 @@ extension Cursor where Element: StringProtocol {
/// This cursor forwards its next() method to an arbitrary underlying cursor
/// having the same Element type, hiding the specifics of the underlying
/// cursor.
public final class AnyCursor<Element> : Cursor {
public final class AnyCursor<Element>: Cursor {
private let element: () throws -> Element?
/// Creates a cursor that wraps a base cursor but whose type depends only on
@@ -539,11 +550,11 @@ public final class AnyCursor<Element> : Cursor {
}
/// :nodoc:
public final class DropFirstCursor<Base: Cursor> : Cursor {
public final class DropFirstCursor<Base: Cursor>: Cursor {
private let base: Base
private let limit: Int
private var dropped: Int = 0
init(_ base: Base, limit: Int) {
GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor")
self.base = base
@@ -566,7 +577,7 @@ public final class DropFirstCursor<Base: Cursor> : Cursor {
/// consecutive elements of some base cursor that satisfy a given predicate.
///
/// :nodoc:
public final class DropWhileCursor<Base: Cursor> : Cursor {
public final class DropWhileCursor<Base: Cursor>: Cursor {
private let base: Base
private let predicate: (Base.Element) throws -> Bool
private var predicateHasFailed = false
@@ -605,7 +616,7 @@ public final class DropWhileCursor<Base: Cursor> : Cursor {
/// // Prints: "1: bar"
///
/// :nodoc:
public final class EnumeratedCursor<Base: Cursor> : Cursor {
public final class EnumeratedCursor<Base: Cursor>: Cursor {
private let base: Base
private var index: Int
@@ -628,7 +639,7 @@ public final class EnumeratedCursor<Base: Cursor> : Cursor {
/// also satisfy a given predicate.
///
/// :nodoc:
public final class FilterCursor<Base: Cursor> : Cursor {
public final class FilterCursor<Base: Cursor>: Cursor {
private let base: Base
private let isIncluded: (Base.Element) throws -> Bool
@@ -656,7 +667,7 @@ public final class FilterCursor<Base: Cursor> : Cursor {
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
///
/// :nodoc:
public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Cursor {
public final class FlattenCursor<Base: Cursor>: Cursor where Base.Element: Cursor {
private let base: Base
private var inner: Base.Element?
@@ -686,7 +697,7 @@ public final class FlattenCursor<Base: Cursor> : Cursor where Base.Element: Curs
/// See Cursor.map(_:)
///
/// :nodoc:
public final class MapCursor<Base: Cursor, Element> : Cursor {
public final class MapCursor<Base: Cursor, Element>: Cursor {
private let base: Base
private let transform: (Base.Element) throws -> Element
@@ -708,7 +719,7 @@ public final class MapCursor<Base: Cursor, Element> : Cursor {
/// `Base` cursor.
///
/// :nodoc:
public final class PrefixCursor<Base: Cursor> : Cursor {
public final class PrefixCursor<Base: Cursor>: Cursor {
private let base: Base
private let maxLength: Int
private var taken = 0
@@ -735,7 +746,7 @@ public final class PrefixCursor<Base: Cursor> : Cursor {
/// some base cursor that satisfy a given predicate.
///
/// :nodoc:
public final class PrefixWhileCursor<Base: Cursor> : Cursor {
public final class PrefixWhileCursor<Base: Cursor>: Cursor {
private let base: Base
private let predicate: (Base.Element) throws -> Bool
private var predicateHasFailed = false
+40 -18
View File
@@ -1,15 +1,15 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
extension Database {
// MARK: - Database Schema
/// Clears the database schema cache.
///
/// You may need to clear the cache manually if the database schema is
@@ -71,7 +71,7 @@ extension Database {
.names(ofType: type)
.contains { $0.lowercased() == name }
}
/// The primary key for table named `tableName`.
///
/// All tables have a primary key, even when it is not explicit. When a
@@ -203,7 +203,12 @@ extension Database {
/// True if a sequence of columns uniquely identifies a row, that is to say
/// if the columns are the primary key, or if there is a unique index on them.
public func table<T: Sequence>(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String {
public func table<T: Sequence>(
_ tableName: String,
hasUniqueKey columns: T)
throws -> Bool
where T.Iterator.Element == String
{
return try columnsForUniqueKey(Array(columns), in: tableName) != nil
}
@@ -213,7 +218,9 @@ extension Database {
return foreignKeys
}
var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = []
var rawForeignKeys: [(
destinationTable: String,
mapping: [(origin: String, destination: String?, seq: Int)])] = []
var previousId: Int? = nil
for row in try Row.fetchAll(self, sql: "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
// row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."]
@@ -224,9 +231,13 @@ extension Database {
let destination: String? = row[4]
if previousId == id {
rawForeignKeys[rawForeignKeys.count - 1].mapping.append((origin: origin, destination: destination, seq: seq))
rawForeignKeys[rawForeignKeys.count - 1]
.mapping
.append((origin: origin, destination: destination, seq: seq))
} else {
rawForeignKeys.append((destinationTable: table, mapping: [(origin: origin, destination: destination, seq: seq)]))
rawForeignKeys.append((
destinationTable: table,
mapping: [(origin: origin, destination: destination, seq: seq)]))
previousId = id
}
}
@@ -281,7 +292,7 @@ extension Database {
}
extension Database {
/// The columns in the table named `tableName`
///
/// - throws: A DatabaseError if table does not exist.
@@ -313,7 +324,7 @@ extension Database {
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
if sqlite3_libversion_number() < 3008005 {
// Work around a bug in SQLite where PRAGMA table_info would
// return a result even after the table was deleted.
@@ -324,7 +335,7 @@ extension Database {
let columns = try ColumnInfo
.fetchAll(self, sql: "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
.sorted(by: { $0.cid < $1.cid })
guard columns.count > 0 else {
if columns.isEmpty {
throw DatabaseError(message: "no such table: \(tableName)")
}
@@ -335,14 +346,25 @@ extension Database {
/// If there exists a unique key on columns, return the columns
/// ordered as the matching index (or primay key). Case of returned columns
/// is not guaranteed.
func columnsForUniqueKey<T: Sequence>(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String {
let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist
func columnsForUniqueKey<T: Sequence>(
_ columns: T,
in tableName: String)
throws -> [String]?
where T.Iterator.Element == String
{
// Check primaryKey first, so that we fail early if the table does not exist
let primaryKey = try self.primaryKey(tableName)
let lowercasedColumns = Set(columns.map { $0.lowercased() })
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
return primaryKey.columns
}
if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) {
// There is an explicit unique index on the columns
// Is there is an explicit unique index on the columns?
let indexes = try self.indexes(on: tableName)
let matchingIndex = indexes.first { index in
index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns
}
if let index = matchingIndex {
return index.columns
}
return nil
@@ -366,7 +388,7 @@ extension Database {
/// 2 score INTEGER 0 NULL 0
///
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
public struct ColumnInfo : FetchableRecord {
public struct ColumnInfo: FetchableRecord {
let cid: Int
/// The column name
+88 -22
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
extension Database {
@@ -36,7 +36,7 @@ extension Database {
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement {
return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
return try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
@@ -85,7 +85,7 @@ extension Database {
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement {
return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
return try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
@@ -180,16 +180,15 @@ extension Database {
// Compile
do {
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
authorizer = statementCompilationAuthorizer
defer { authorizer = nil }
nextStatement = try UpdateStatement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: 0,
authorizer: statementCompilationAuthorizer)
let authorizer = StatementCompilationAuthorizer()
nextStatement = try withAuthorizer(authorizer) {
try UpdateStatement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: 0,
authorizer: authorizer)
}
}
guard let statement = nextStatement else {
@@ -213,18 +212,63 @@ extension Database {
// Check that all arguments were consumed: it is a programmer error to
// provide arguments that do not match the statement.
if arguments.values.isEmpty == false {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)")
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "wrong number of statement arguments: \(initialValuesCount)")
}
}
}
extension Database {
func updateStatementWillExecute(_ statement: UpdateStatement) {
observationBroker.updateStatementWillExecute(statement)
func executeUpdateStatement(_ statement: UpdateStatement) throws {
let authorizer = observationBroker.updateStatementWillExecute(statement)
let sqliteStatement = statement.sqliteStatement
var code: Int32 = SQLITE_OK
withAuthorizer(authorizer) {
while true {
code = sqlite3_step(sqliteStatement)
if code == SQLITE_ROW {
// Statement returns a row, but the user ignores the
// content of this row:
//
// try db.execute(sql: "SELECT ...")
//
// That's OK: maybe the selected rows perform side effects.
// For example:
//
// try db.execute(sql: "SELECT sqlcipher_export(...)")
//
// Or maybe the user doesn't know that the executed statement
// return rows (https://github.com/groue/GRDB.swift/issues/15);
//
// try db.execute(sql: "PRAGMA journal_mode=WAL")
//
// It is thus important that we consume *all* rows.
continue
} else {
break
}
}
}
// Statement has been fully executed, and authorizer has been reset.
// We can now move on further tasks.
if code == SQLITE_DONE {
try updateStatementDidExecute(statement)
} else {
assert(code != SQLITE_ROW)
try updateStatementDidFail(statement)
throw DatabaseError(
resultCode: code,
message: lastErrorMessage,
sql: statement.sql,
arguments: statement.arguments)
}
}
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
private func updateStatementDidExecute(_ statement: UpdateStatement) throws {
if statement.invalidatesDatabaseSchemaCache {
clearSchemaCache()
}
@@ -232,7 +276,7 @@ extension Database {
try observationBroker.updateStatementDidExecute(statement)
}
func updateStatementDidFail(_ statement: UpdateStatement) throws {
private func updateStatementDidFail(_ statement: UpdateStatement) throws {
// Failed statements can not be reused, because sqlite3_reset won't
// be able to restore the statement to its initial state:
// https://www.sqlite.org/c3ref/reset.html
@@ -244,6 +288,28 @@ extension Database {
try observationBroker.updateStatementDidFail(statement)
}
@inline(__always)
func selectStatementWillExecute(_ statement: SelectStatement) {
if _isRecordingSelectedRegion {
// Don't record schema introspection queries, which may be
// run, or not, depending on the state of the schema cache.
//
// This gives us a quick way to make sure that the observation
// below, which runs schema introspection queries as a side effect,
// only tracks the "player" table:
//
// let observation = ValueObservation.tracking { db in
// try Player.fetchOne(db, key: 1)
// }
//
// Strictly speaking, this prevents the recording of all schema
// queries. But we assume, until proven wrong, that such recording
// isn't needed by anyone.
let region = statement.databaseRegion.ignoringInternalSQLiteTables()
_selectedRegion.formUnion(region)
}
}
func selectStatementDidFail(_ statement: SelectStatement) {
// Failed statements can not be reused, because sqlite3_reset won't
// be able to restore the statement to its initial state:
@@ -294,7 +360,7 @@ struct StatementCache {
selectStatements[sql] = statement
return statement
}
mutating func updateStatement(_ sql: String) throws -> UpdateStatement {
if let statement = updateStatements[sql] {
return statement
+163 -95
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// A raw SQLite connection, suitable for the SQLite C API.
@@ -36,7 +36,7 @@ public final class Database {
public let sqliteConnection: SQLiteConnection
// MARK: - Configuration
/// The error logging function.
///
/// Quoting https://www.sqlite.org/errlog.html:
@@ -53,7 +53,7 @@ public final class Database {
if logError != nil {
registerErrorLogCallback { (_, code, message) in
guard let logError = Database.logError else { return }
guard let message = message.map({ String(cString: $0) }) else { return }
guard let message = message.map(String.init) else { return }
let resultCode = ResultCode(rawValue: code)
logError(resultCode, message)
}
@@ -129,24 +129,8 @@ public final class Database {
var lastErrorCode: ResultCode { return ResultCode(rawValue: sqlite3_errcode(sqliteConnection)) }
var lastErrorMessage: String? { return String(cString: sqlite3_errmsg(sqliteConnection)) }
// Statement authorizer
var authorizer: StatementAuthorizer? {
didSet {
switch (oldValue, authorizer) {
case (.some, nil):
sqlite3_set_authorizer(sqliteConnection, nil, nil)
case (nil, .some):
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_set_authorizer(sqliteConnection, { (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
guard let dbPointer = dbPointer else { return SQLITE_OK }
let db = Unmanaged<Database>.fromOpaque(dbPointer).takeUnretainedValue()
return db.authorizer!.authorize(actionCode, cString1, cString2, cString3, cString4)
}, dbPointer)
default:
break
}
}
}
/// Statement authorizer. Use withAuthorizer(_:_:).
fileprivate var _authorizer: StatementAuthorizer?
// Transaction observers management
lazy var observationBroker = DatabaseObservationBroker(self)
@@ -156,6 +140,11 @@ public final class Database {
try! Set(String.fetchCursor($0, sql: "PRAGMA COMPILE_OPTIONS"))
}
/// If true, select statement execution is recorded.
/// Use recordingSelectedRegion(_:), see `selectStatementWillExecute(_:)`
var _isRecordingSelectedRegion: Bool = false
var _selectedRegion = DatabaseRegion()
// MARK: - Private properties
private var busyCallback: BusyCallback?
@@ -164,9 +153,9 @@ public final class Database {
private var collations = Set<DatabaseCollation>()
private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly
private var isClosed: Bool = false
// MARK: - Initializer
init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws {
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
self.configuration = configuration
@@ -179,7 +168,7 @@ public final class Database {
}
extension Database {
// MARK: - Database Opening
private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection {
@@ -207,7 +196,7 @@ extension Database {
}
extension Database {
// MARK: - Database Setup
/// This method must be called after database initialization
@@ -218,16 +207,17 @@ extension Database {
setupBusyMode()
setupDefaultFunctions()
setupDefaultCollations()
setupAuthorizer()
observationBroker.installCommitAndRollbackHooks()
try activateExtendedCodes()
#if SQLITE_HAS_CODEC
try validateSQLCipher()
if let passphrase = configuration.passphrase {
try setCipherPassphrase(passphrase)
}
#endif
// Last step before we can start accessing the database.
// This is the opportunity to run SQLCipher configuration
// pragmas such as cipher_page_size, for example.
@@ -240,24 +230,34 @@ extension Database {
guard configuration.trace != nil else {
return
}
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 http://www.sqlite.org/changes.html#version_3_14
// It is available from iOS 10.0 and OS X 10.12 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
// http://www.sqlite.org/changes.html#version_3_14
// It is available from iOS 10.0 and OS X 10.12
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
}, dbPointer)
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(
sqliteConnection,
UInt32(SQLITE_TRACE_STMT),
{ (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
},
dbPointer)
#elseif os(Linux)
setupTrace_v1()
setupTrace_v1()
#else
if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
return Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
}, dbPointer)
} else {
setupTrace_v1()
}
if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace_v2(
sqliteConnection,
UInt32(SQLITE_TRACE_STMT),
{ (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
},
dbPointer)
} else {
setupTrace_v1()
}
#endif
}
@@ -265,7 +265,7 @@ extension Database {
private func setupTrace_v1() {
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
guard let sql = sql.map({ String(cString: $0) }) else { return }
guard let sql = sql.map(String.init) else { return }
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
db.configuration.trace!(sql)
}, dbPointer)
@@ -339,6 +339,29 @@ extension Database {
add(collation: .localizedStandardCompare)
}
private func setupAuthorizer() {
// SQLite authorizer is set only once per database connection.
//
// This is because authorizer changes have SQLite invalidate statements,
// with undesired side effects. See:
//
// - DatabaseCursorTests.testIssue583()
// - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html
// swiftlint:disable:previous line_length
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_set_authorizer(
sqliteConnection,
{ (dbPointer, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
let db = Unmanaged<Database>.fromOpaque(dbPointer.unsafelyUnwrapped).takeUnretainedValue()
guard let authorizer = db._authorizer else {
return SQLITE_OK
}
return authorizer.authorize(actionCode, cString1, cString2, cString3, cString4)
},
dbPointer)
}
private func activateExtendedCodes() throws {
let code = sqlite3_extended_result_codes(sqliteConnection, 1)
guard code == SQLITE_OK else {
@@ -391,7 +414,7 @@ extension Database {
}
extension Database {
// MARK: - Database Closing
/// This method must be called before database deallocation
@@ -409,18 +432,19 @@ extension Database {
private static func closeConnection(_ sqliteConnection: SQLiteConnection) {
// sqlite3_close_v2 was added in SQLite 3.7.14 http://www.sqlite.org/changes.html#version_3_7_14
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
} else {
closeConnection_v1(sqliteConnection)
}
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
} else {
closeConnection_v1(sqliteConnection)
}
#endif
}
private static func closeConnection_v1(_ sqliteConnection: SQLiteConnection) {
// https://www.sqlite.org/c3ref/close.html
// > If the database connection is associated with unfinalized prepared
@@ -466,7 +490,7 @@ extension Database {
}
extension Database {
// MARK: - Functions
/// Add or redefine an SQL function.
@@ -492,7 +516,7 @@ extension Database {
}
extension Database {
// MARK: - Collations
/// Add or redefine a collation.
@@ -539,7 +563,8 @@ extension Database {
_readOnlyDepth += 1
if _readOnlyDepth == 1 && configuration.readonly == false {
// PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute()
}
}
@@ -548,7 +573,8 @@ extension Database {
_readOnlyDepth -= 1
if _readOnlyDepth == 0 && configuration.readonly == false {
// PRAGMA query_only was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute()
}
}
@@ -583,7 +609,42 @@ extension Database {
}
extension Database {
// MARK: - Authorizer
func withAuthorizer<T>(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T {
SchedulingWatchdog.preconditionValidQueue(self)
let old = self._authorizer
self._authorizer = authorizer
defer { self._authorizer = old }
return try block()
}
}
extension Database {
// MARK: - Recording of the selected region
func recordingSelectedRegion<T>(_ block: () throws -> T) rethrows -> (T, DatabaseRegion) {
SchedulingWatchdog.preconditionValidQueue(self)
let oldFlag = self._isRecordingSelectedRegion
let oldRegion = self._selectedRegion
self._isRecordingSelectedRegion = true
self._selectedRegion = DatabaseRegion()
defer {
self._isRecordingSelectedRegion = oldFlag
if self._isRecordingSelectedRegion {
self._selectedRegion = oldRegion.union(self._selectedRegion)
} else {
self._selectedRegion = oldRegion
}
}
return try (block(), _selectedRegion)
}
}
extension Database {
// MARK: - Transactions & Savepoint
/// Executes a block inside a database transaction.
@@ -640,7 +701,7 @@ extension Database {
}
}
}
if let firstError = firstError {
throw firstError
}
@@ -674,7 +735,7 @@ extension Database {
if !isInsideTransaction && configuration.defaultTransactionKind != .deferred {
return try inTransaction(configuration.defaultTransactionKind, block)
}
// If the savepoint is top-level, we'll use ROLLBACK TRANSACTION in
// order to perform the special error handling of rollbacks (see
// the rollback method).
@@ -849,7 +910,7 @@ extension Database {
}
extension Database {
// MARK: - Memory Management
func releaseMemory() {
@@ -864,12 +925,18 @@ extension Database {
// MARK: - Backup
static func backup(from dbFrom: Database, to dbDest: Database, afterBackupInit: (() -> ())? = nil, afterBackupStep: (() -> ())? = nil) throws {
static func backup(
from dbFrom: Database,
to dbDest: Database,
afterBackupInit: (() -> Void)? = nil,
afterBackupStep: (() -> Void)? = nil)
throws
{
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else {
throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
}
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
throw DatabaseError(resultCode: .SQLITE_ERROR)
throw DatabaseError()
}
afterBackupInit?()
@@ -904,35 +971,36 @@ extension Database {
}
#if SQLITE_HAS_CODEC
extension Database {
// MARK: - Encryption
func change(passphrase: String) throws {
// FIXME: sqlite3_rekey is discouraged.
//
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
//
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
// > favor of attaching a new database with the desired encryption
// > options and using sqlcipher_export() to migrate the contents and
// > schema of the original db into the new one:
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
let data = passphrase.data(using: .utf8)!
#if swift(>=5.0)
let code = data.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
}
#else
let code = data.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0, Int32(data.count))
}
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
extension Database {
// MARK: - Encryption
func change(passphrase: String) throws {
// FIXME: sqlite3_rekey is discouraged.
//
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
//
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
// > favor of attaching a new database with the desired encryption
// > options and using sqlcipher_export() to migrate the contents and
// > schema of the original db into the new one:
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
// swiftlint:disable:previous line_length
let data = passphrase.data(using: .utf8)!
#if swift(>=5.0)
let code = data.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
}
#else
let code = data.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0, Int32(data.count))
}
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
}
}
#endif
extension Database {
@@ -991,7 +1059,7 @@ extension Database {
/// A built-in SQLite collation.
///
/// See https://www.sqlite.org/datatype3.html#collation
public struct CollationName : RawRepresentable, Hashable {
public struct CollationName: RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
@@ -1022,7 +1090,7 @@ extension Database {
/// }
///
/// See https://www.sqlite.org/datatype3.html
public struct ColumnType : RawRepresentable, Hashable {
public struct ColumnType: RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
@@ -1063,7 +1131,7 @@ extension Database {
/// An SQLite conflict resolution.
///
/// See https://www.sqlite.org/lang_conflict.html.
public enum ConflictResolution : String {
public enum ConflictResolution: String {
case rollback = "ROLLBACK"
case abort = "ABORT"
case fail = "FAIL"
@@ -1074,7 +1142,7 @@ extension Database {
/// A foreign key action.
///
/// See https://www.sqlite.org/foreignkeys.html
public enum ForeignKeyAction : String {
public enum ForeignKeyAction: String {
case cascade = "CASCADE"
case restrict = "RESTRICT"
case setNull = "SET NULL"
@@ -1091,7 +1159,7 @@ extension Database {
}
/// An SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html
public enum TransactionKind : String {
public enum TransactionKind: String {
case deferred = "DEFERRED"
case immediate = "IMMEDIATE"
case exclusive = "EXCLUSIVE"
+14 -6
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// A Collation is a string comparison function used by SQLite.
@@ -27,8 +27,16 @@ public final class DatabaseCollation {
self.name = name
self.function = { (length1, buffer1, length2, buffer2) in
// Buffers are not C strings: they do not end with \0.
let string1 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), length: Int(length1), encoding: .utf8, freeWhenDone: false)!
let string2 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), length: Int(length2), encoding: .utf8, freeWhenDone: false)!
let string1 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
length: Int(length1),
encoding: .utf8,
freeWhenDone: false)!
let string2 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
length: Int(length2),
encoding: .utf8,
freeWhenDone: false)!
return function(string1, string2)
}
}
@@ -50,6 +58,6 @@ extension DatabaseCollation: Hashable {
/// :nodoc:
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
// See https://www.sqlite.org/c3ref/create_collation.html
return sqlite3_stricmp(lhs.name, lhs.name) == 0
return sqlite3_stricmp(lhs.name, rhs.name) == 0
}
}
+24 -14
View File
@@ -1,13 +1,13 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
public let rawValue: Int32
public init(rawValue: Int32) {
@@ -48,6 +48,7 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
// Primary Result codes
// https://www.sqlite.org/rescode.html#primary_result_code_list
// swiftlint:disable operator_usage_whitespace
public static let SQLITE_OK = ResultCode(rawValue: 0) // Successful result
public static let SQLITE_ERROR = ResultCode(rawValue: 1) // SQL error or missing database
public static let SQLITE_INTERNAL = ResultCode(rawValue: 2) // Internal logic error in SQLite
@@ -79,10 +80,12 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
public static let SQLITE_WARNING = ResultCode(rawValue: 28) // Warnings from sqlite3_log()
public static let SQLITE_ROW = ResultCode(rawValue: 100) // sqlite3_step() has another row ready
public static let SQLITE_DONE = ResultCode(rawValue: 101) // sqlite3_step() has finished executing
// swiftlint:enable operator_usage_whitespace
// Extended Result Code
// https://www.sqlite.org/rescode.html#extended_result_code_list
// swiftlint:disable operator_usage_whitespace
public static let SQLITE_IOERR_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (1<<8)))
public static let SQLITE_IOERR_SHORT_READ = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (2<<8)))
public static let SQLITE_IOERR_WRITE = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (3<<8)))
@@ -139,21 +142,23 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8)))
public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8)))
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
// swiftlint:enable operator_usage_whitespace
}
// CustomStringConvertible
extension ResultCode {
var errorString: String? {
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
return String(cString: sqlite3_errstr(rawValue))
return String(cString: sqlite3_errstr(rawValue))
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
return String(cString: sqlite3_errstr(rawValue))
} else {
return nil
}
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
return String(cString: sqlite3_errstr(rawValue))
} else {
return nil
}
#endif
}
@@ -168,7 +173,7 @@ extension ResultCode {
}
/// DatabaseError wraps an SQLite error.
public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
/// The SQLite error code (see
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
@@ -207,7 +212,12 @@ public struct DatabaseError : Error, CustomStringConvertible, CustomNSError {
public let sql: String?
/// Creates a Database Error
public init(resultCode: ResultCode = .SQLITE_ERROR, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
public init(
resultCode: ResultCode = .SQLITE_ERROR,
message: String? = nil,
sql: String? = nil,
arguments: StatementArguments? = nil)
{
self.extendedResultCode = resultCode
self.message = message ?? resultCode.errorString
self.sql = sql
@@ -264,7 +274,7 @@ extension DatabaseError {
/// NSError bridging: the user-info dictionary.
/// :nodoc:
public var errorUserInfo: [String : Any] {
public var errorUserInfo: [String: Any] {
return [NSLocalizedDescriptionKey: description]
}
}
+25 -9
View File
@@ -1,9 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// An SQL function or aggregate.
@@ -44,7 +44,12 @@ public final class DatabaseFunction: Hashable {
/// as Int, String, NSDate, etc. The array is guaranteed to have
/// exactly *argumentCount* elements, provided *argumentCount* is
/// not nil.
public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) {
public init(
_ name: String,
argumentCount: Int32? = nil,
pure: Bool = false,
function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?)
{
self.identity = Identity(name: name, nArg: argumentCount ?? -1)
self.pure = pure
self.kind = .function{ (argc, argv) in
@@ -94,10 +99,15 @@ public final class DatabaseFunction: Hashable {
/// an array of DatabaseValue arguments. The array is guaranteed to
/// have exactly *argumentCount* elements, provided *argumentCount* is
/// not nil.
public init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) {
public init<Aggregate: DatabaseAggregate>(
_ name: String,
argumentCount: Int32? = nil,
pure: Bool = false,
aggregate: Aggregate.Type)
{
self.identity = Identity(name: name, nArg: argumentCount ?? -1)
self.pure = pure
self.kind = .aggregate { return Aggregate() }
self.kind = .aggregate { Aggregate() }
}
/// Calls sqlite3_create_function_v2
@@ -197,7 +207,9 @@ public final class DatabaseFunction: Hashable {
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
guard case .function = self else { return nil }
return { (sqliteContext, argc, argv) in
let definition = Unmanaged<FunctionDefinition>.fromOpaque(sqlite3_user_data(sqliteContext)).takeUnretainedValue()
let definition = Unmanaged<FunctionDefinition>
.fromOpaque(sqlite3_user_data(sqliteContext))
.takeUnretainedValue()
do {
try DatabaseFunction.report(
result: definition.compute(argc, argv),
@@ -262,11 +274,15 @@ public final class DatabaseFunction: Hashable {
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
// The current aggregate buffer
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride)
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(
start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!,
count: stride)
if aggregateContextBufferP.contains(where: { $0 != 0 }) { // TODO: This testt looks weird. Review.
// Buffer contains non-null pointer: load aggregate context
let aggregateContextP = aggregateContextBufferP.baseAddress!.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
let aggregateContextP = aggregateContextBufferP
.baseAddress!
.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
return aggregateContextP.pointee
} else {
// Buffer contains null pointer: create aggregate context...
+46 -30
View File
@@ -1,14 +1,14 @@
import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
#if os(iOS)
import UIKit
import UIKit
#endif
/// A DatabasePool grants concurrent accesses to an SQLite database.
@@ -79,7 +79,10 @@ public final class DatabasePool: DatabaseWriter {
// opens a pool to an existing non-WAL database, and
// attempts to read from it.
// See https://github.com/groue/GRDB.swift/issues/102
try db.execute(sql: "CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); DROP TABLE grdb_issue_102;")
try db.execute(sql: """
CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY);
DROP TABLE grdb_issue_102;
""")
}
}
}
@@ -87,8 +90,13 @@ public final class DatabasePool: DatabaseWriter {
// Readers
readerConfig = configuration
readerConfig.readonly = true
readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections.
readerConfig.allowsUnsafeTransactions = false // Because there's no guarantee that one can get the same reader in order to close its opened transaction.
// Readers use deferred transactions by default.
// Other transaction kinds are forbidden by SQLite in read-only connections.
readerConfig.defaultTransactionKind = .deferred
// Readers can't allow dangling transactions because there's no
// guarantee that one can get the same reader later in order to close
// an opened transaction.
readerConfig.allowsUnsafeTransactions = false
var readerCount = 0
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
readerCount += 1 // protected by pool's ReadWriteBox (undocumented behavior and protection)
@@ -134,9 +142,9 @@ public final class DatabasePool: DatabaseWriter {
}
extension DatabasePool {
// MARK: - WAL Checkpoints
/// Runs a WAL checkpoint
///
/// See https://www.sqlite.org/wal.html and
@@ -151,16 +159,16 @@ extension DatabasePool {
// when kind is not .Passive.
let code = sqlite3_wal_checkpoint_v2(db.sqliteConnection, nil, kind.rawValue, nil, nil)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: db.lastErrorMessage, sql: nil)
throw DatabaseError(resultCode: code, message: db.lastErrorMessage)
}
}
}
}
extension DatabasePool {
// MARK: - Memory management
/// Free as much memory as possible.
///
/// This method blocks the current thread until all database accesses are completed.
@@ -195,7 +203,8 @@ extension DatabasePool {
object: nil)
}
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
@objc
private func applicationDidEnterBackground(_ notification: NSNotification) {
guard let application = application else {
return
}
@@ -213,7 +222,8 @@ extension DatabasePool {
}
}
@objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
@objc
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
DispatchQueue.global().async {
self.releaseMemory()
}
@@ -222,24 +232,24 @@ extension DatabasePool {
}
#if SQLITE_HAS_CODEC
extension DatabasePool {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try readerPool.clear(andThen: {
try writer.sync { try $0.change(passphrase: passphrase) }
readerConfig.passphrase = passphrase
})
}
extension DatabasePool {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try readerPool.clear(andThen: {
try writer.sync { try $0.change(passphrase: passphrase) }
readerConfig.passphrase = passphrase
})
}
}
#endif
extension DatabasePool : DatabaseReader {
extension DatabasePool: DatabaseReader {
// MARK: - Reading from Database
/// Synchronously executes a read-only block in a protected dispatch queue,
/// and returns its result. The block is wrapped in a deferred transaction.
///
@@ -493,7 +503,7 @@ extension DatabasePool : DatabaseReader {
asyncConcurrentRead(block)
}
#endif
#if compiler(>=5.0)
/// Asynchronously executes a read-only block in a protected dispatch queue.
///
@@ -649,7 +659,11 @@ extension DatabasePool : DatabaseReader {
/// - updates: The updates to the database.
/// - throws: The error thrown by the updates, or by the
/// wrapping transaction.
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) throws {
public func writeInTransaction(
_ kind: Database.TransactionKind? = nil,
_ updates: (Database) throws -> Database.TransactionCompletion)
throws
{
try writer.sync { db in
try db.inTransaction(kind) {
try updates(db)
@@ -811,7 +825,9 @@ extension DatabasePool {
// Sanity check
if writer.onValidQueue {
writer.execute { db in
GRDBPrecondition(!db.isInsideTransaction, "makeSnapshot() must not be called from inside a transaction.")
GRDBPrecondition(
!db.isInsideTransaction,
"makeSnapshot() must not be called from inside a transaction.")
}
}
+21 -15
View File
@@ -71,9 +71,9 @@ public final class DatabaseQueue: DatabaseWriter {
}
extension DatabaseQueue {
// MARK: - Memory management
/// Free as much memory as possible.
///
/// This method blocks the current thread until all database accesses are completed.
@@ -106,7 +106,8 @@ extension DatabaseQueue {
object: nil)
}
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
@objc
private func applicationDidEnterBackground(_ notification: NSNotification) {
guard let application = application else {
return
}
@@ -124,7 +125,8 @@ extension DatabaseQueue {
}
}
@objc private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
@objc
private func applicationDidReceiveMemoryWarning(_ notification: NSNotification) {
DispatchQueue.global().async {
self.releaseMemory()
}
@@ -133,15 +135,15 @@ extension DatabaseQueue {
}
#if SQLITE_HAS_CODEC
extension DatabaseQueue {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try writer.sync { try $0.change(passphrase: passphrase) }
}
extension DatabaseQueue {
// MARK: - Encryption
/// Changes the passphrase of an encrypted database
public func change(passphrase: String) throws {
try writer.sync { try $0.change(passphrase: passphrase) }
}
}
#endif
extension DatabaseQueue {
@@ -202,7 +204,7 @@ extension DatabaseQueue {
}
}
#endif
/// Synchronously executes a block in a protected dispatch queue, and
/// returns its result.
///
@@ -302,7 +304,11 @@ extension DatabaseQueue {
/// - updates: The updates to the database.
/// - throws: The error thrown by the updates, or by the
/// wrapping transaction.
public func inTransaction(_ kind: Database.TransactionKind? = nil, _ updates: (Database) throws -> Database.TransactionCompletion) throws {
public func inTransaction(
_ kind: Database.TransactionKind? = nil,
_ updates: (Database) throws -> Database.TransactionCompletion)
throws
{
try writer.sync { db in
try db.inTransaction(kind) {
try updates(db)
@@ -323,7 +329,7 @@ extension DatabaseQueue {
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try writer.sync(updates)
}
/// Synchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
+11 -7
View File
@@ -1,9 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// The protocol for all types that can fetch values from a database.
@@ -21,7 +21,7 @@
/// connection to the database. Should you have to cope with external
/// connections, protect yourself with transactions, and be ready to setup a
/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html).
public protocol DatabaseReader : class {
public protocol DatabaseReader: AnyObject {
/// The database configuration
var configuration: Configuration { get }
@@ -220,10 +220,14 @@ extension DatabaseReader {
try backup(to: writer, afterBackupInit: nil, afterBackupStep: nil)
}
func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws {
func backup(to writer: DatabaseWriter, afterBackupInit: (() -> Void)?, afterBackupStep: (() -> Void)?) throws {
try read { dbFrom in
try writer.writeWithoutTransaction { dbDest in
try Database.backup(from: dbFrom, to: dbDest, afterBackupInit: afterBackupInit, afterBackupStep: afterBackupStep)
try Database.backup(
from: dbFrom,
to: dbDest,
afterBackupInit: afterBackupInit,
afterBackupStep: afterBackupStep)
}
}
}
@@ -233,7 +237,7 @@ extension DatabaseReader {
///
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
/// underlying database reader.
public final class AnyDatabaseReader : DatabaseReader {
public final class AnyDatabaseReader: DatabaseReader {
private let base: DatabaseReader
/// Creates a database reader that wraps a base database reader.
+32 -17
View File
@@ -31,6 +31,7 @@
/// let region = try request.databaseRegion(db)
public struct DatabaseRegion: CustomStringConvertible, Equatable {
private let tableRegions: [String: TableRegion]?
private init(tableRegions: [String: TableRegion]?) {
self.tableRegions = tableRegions
}
@@ -125,9 +126,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
switch (tableRegion, otherTableRegion) {
case (nil, nil):
preconditionFailure()
case (nil, let tableRegion?), (let tableRegion?, nil):
case let (nil, tableRegion?), let (tableRegion?, nil):
tableRegionUnion = tableRegion
case (let tableRegion?, let otherTableRegion?):
case let (tableRegion?, otherTableRegion?):
tableRegionUnion = tableRegion.union(otherTableRegion)
}
tableRegionsUnion[table] = tableRegionUnion
@@ -141,10 +142,23 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
self = union(other)
}
func ignoring(_ tables: Set<String>) -> DatabaseRegion {
guard tables.isEmpty == false else { return self }
/// Returns a region suitable for database observation by removing views.
///
/// We can do it because modifications only happen in actual tables. And we
/// want to do it because we have a fast path for regions that span a
/// single table.
func ignoringViews(_ db: Database) throws -> DatabaseRegion {
guard let tableRegions = tableRegions else { return .fullDatabase }
let filteredRegions = tableRegions.filter { tables.contains($0.key) == false }
let viewNames = try db.schema().names(ofType: .view)
guard viewNames.isEmpty == false else { return self }
let filteredRegions = tableRegions.filter { viewNames.contains($0.key) == false }
return DatabaseRegion(tableRegions: filteredRegions)
}
/// Returns a region which doesn't contain any SQLite internal table.
func ignoringInternalSQLiteTables() -> DatabaseRegion {
guard let tableRegions = tableRegions else { return .fullDatabase }
let filteredRegions = tableRegions.filter { !$0.key.starts(with: "sqlite_") }
return DatabaseRegion(tableRegions: filteredRegions)
}
}
@@ -184,7 +198,10 @@ extension DatabaseRegion {
// Slow path when several tables are observed.
guard let tableRegion = tableRegions[event.tableName] else {
// Shouldn't happen if the precondition is met.
fatalError("precondition failure: event was not filtered out in observes(eventsOfKind:) by region.isModified(byEventsOfKind:)")
fatalError("""
precondition failure: event was not filtered out in observes(eventsOfKind:) \
by region.isModified(byEventsOfKind:)
""")
}
return tableRegion.contains(rowID: event.rowID)
}
@@ -198,16 +215,14 @@ extension DatabaseRegion {
switch (lhs.tableRegions, rhs.tableRegions) {
case (nil, nil):
return true
case (let ltableRegions?, let rtableRegions?):
case let (ltableRegions?, rtableRegions?):
let ltableNames = Set(ltableRegions.keys)
let rtableNames = Set(rtableRegions.keys)
guard ltableNames == rtableNames else {
return false
}
for tableName in ltableNames {
if ltableRegions[tableName]! != rtableRegions[tableName]! {
return false
}
for tableName in ltableNames where ltableRegions[tableName]! != rtableRegions[tableName]! {
return false
}
return true
default:
@@ -257,17 +272,17 @@ private struct TableRegion: Equatable {
func intersection(_ other: TableRegion) -> TableRegion {
let columnsIntersection: Set<String>?
switch (self.columns, other.columns) {
case (nil, let columns), (let columns, nil):
case let (nil, columns), let (columns, nil):
columnsIntersection = columns
case (let columns?, let other?):
case let (columns?, other?):
columnsIntersection = columns.intersection(other)
}
let rowIdsIntersection: Set<Int64>?
switch (self.rowIds, other.rowIds) {
case (nil, let rowIds), (let rowIds, nil):
case let (nil, rowIds), let (rowIds, nil):
rowIdsIntersection = rowIds
case (let rowIds?, let other?):
case let (rowIds?, other?):
rowIdsIntersection = rowIds.intersection(other)
}
@@ -279,7 +294,7 @@ private struct TableRegion: Equatable {
switch (self.columns, other.columns) {
case (nil, _), (_, nil):
columnsUnion = nil
case (let columns?, let other?):
case let (columns?, other?):
columnsUnion = columns.union(other)
}
@@ -287,7 +302,7 @@ private struct TableRegion: Equatable {
switch (self.rowIds, other.rowIds) {
case (nil, _), (_, nil):
rowIdsUnion = nil
case (let rowIds?, let other?):
case let (rowIds?, other?):
rowIdsUnion = rowIds.union(other)
}
+13 -18
View File
@@ -13,25 +13,14 @@ public struct DatabaseRegionObservation {
/// `.observerLifetime`: the observation lasts until the
/// observer returned by the `start(in:onChange:)` method
/// is deallocated.
public var extent = Database.TransactionObservationExtent.observerLifetime
public var extent: Database.TransactionObservationExtent
/// A closure that is evaluated when the observation starts, and returns
/// the observed database region.
var observedRegion: (Database) throws -> DatabaseRegion
}
// Not public because we foster DatabaseRegionConvertible.
init(tracking region: @escaping (Database) throws -> DatabaseRegion) {
self.observedRegion = { db in
// Remove views from the observed region.
//
// We can do it because we are only interested in modifications in
// actual tables. And we want to do it because we have a fast path
// for simple regions that span a single table.
let views = try db.schema().names(ofType: .view)
return try region(db).ignoring(views)
}
}
extension DatabaseRegionObservation {
/// Creates a DatabaseRegionObservation which observes *regions*, and
/// notifies whenever one of the observed regions is modified by a
/// database transaction.
@@ -75,7 +64,9 @@ public struct DatabaseRegionObservation {
///
/// - parameter regions: A list of observed regions.
public init(tracking regions: [DatabaseRegionConvertible]) {
self.init(tracking: DatabaseRegion.union(regions))
self.init(
extent: .observerLifetime,
observedRegion: DatabaseRegion.union(regions))
}
}
@@ -87,11 +78,15 @@ extension DatabaseRegionObservation {
/// - parameter onChange: A closure that is provided a database connection
/// with write access each time the observed region has been modified.
/// - returns: a TransactionObserver
public func start(in dbWriter: DatabaseWriter, onChange: @escaping (Database) -> Void) throws -> TransactionObserver {
public func start(
in dbWriter: DatabaseWriter,
onChange: @escaping (Database) -> Void)
throws -> TransactionObserver
{
// Use unsafeReentrantWrite so that observation can start from any
// dispatch queue.
return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in
let region = try observedRegion(db)
let region = try observedRegion(db).ignoringViews(db)
let observer = DatabaseRegionObserver(region: region, onChange: onChange)
db.add(transactionObserver: observer, extent: extent)
return observer
@@ -123,7 +118,7 @@ private class DatabaseRegionObserver: TransactionObserver {
func databaseDidCommit(_ db: Database) {
guard isChanged else { return }
isChanged = false
onChange(db)
}
+1 -1
View File
@@ -6,7 +6,7 @@ import Dispatch
/// See DatabasePool.makeSnapshot()
///
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
public class DatabaseSnapshot : DatabaseReader {
public class DatabaseSnapshot: DatabaseReader {
private var serializedDatabase: SerializedDatabase
/// The database configuration
+25 -23
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
// MARK: - DatabaseValue
@@ -20,7 +20,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
public static let null = DatabaseValue(storage: .null)
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
public enum Storage : Equatable {
public enum Storage: Equatable {
/// The NULL storage class.
case null
@@ -60,10 +60,10 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
public static func == (_ lhs: Storage, _ rhs: Storage) -> Bool {
switch (lhs, rhs) {
case (.null, .null): return true
case (.int64(let lhs), .int64(let rhs)): return lhs == rhs
case (.double(let lhs), .double(let rhs)): return lhs == rhs
case (.string(let lhs), .string(let rhs)): return lhs == rhs
case (.blob(let lhs), .blob(let rhs)): return lhs == rhs
case let (.int64(lhs), .int64(rhs)): return lhs == rhs
case let (.double(lhs), .double(rhs)): return lhs == rhs
case let (.string(lhs), .string(rhs)): return lhs == rhs
case let (.blob(lhs), .blob(rhs)): return lhs == rhs
default: return false
}
}
@@ -120,7 +120,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
fatalError("Unexpected SQLite value type: \(type)")
}
}
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
@@ -187,17 +187,17 @@ extension DatabaseValue {
switch (lhs.storage, rhs.storage) {
case (.null, .null):
return true
case (.int64(let lhs), .int64(let rhs)):
case let (.int64(lhs), .int64(rhs)):
return lhs == rhs
case (.double(let lhs), .double(let rhs)):
case let (.double(lhs), .double(rhs)):
return lhs == rhs
case (.int64(let lhs), .double(let rhs)):
case let (.int64(lhs), .double(rhs)):
return Int64(exactly: rhs) == lhs
case (.double(let lhs), .int64(let rhs)):
case let (.double(lhs), .int64(rhs)):
return rhs == Int64(exactly: lhs)
case (.string(let lhs), .string(let rhs)):
case let (.string(lhs), .string(rhs)):
return lhs == rhs
case (.blob(let lhs), .blob(let rhs)):
case let (.blob(lhs), .blob(rhs)):
return lhs == rhs
default:
return false
@@ -266,8 +266,10 @@ extension DatabaseValue {
case .blob:
// We can't assume all blobs are true, and return false:
//
// SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1', then into integer 1, which is negated into 0)
// SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0', then into integer 0, which is negated into 1)
// SELECT NOT X'31' -- 0 (because X'31' is turned into the string '1',
// then into integer 1, which is negated into 0)
// SELECT NOT X'30' -- 1 (because X'30' is turned into the string '0',
// then into integer 0, which is negated into 1)
return SQLExpressionNot(self)
}
}
@@ -309,17 +311,17 @@ extension DatabaseValue {
/// easier testing.
func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
switch (lhs.storage, rhs.storage) {
case (.int64(let lhs), .int64(let rhs)):
case let (.int64(lhs), .int64(rhs)):
return lhs < rhs
case (.double(let lhs), .double(let rhs)):
case let (.double(lhs), .double(rhs)):
return lhs < rhs
case (.int64(let lhs), .double(let rhs)):
case let (.int64(lhs), .double(rhs)):
return Double(lhs) < rhs
case (.double(let lhs), .int64(let rhs)):
case let (.double(lhs), .int64(rhs)):
return lhs < Double(rhs)
case (.string(let lhs), .string(let rhs)):
case let (.string(lhs), .string(rhs)):
return lhs.utf8.lexicographicallyPrecedes(rhs.utf8)
case (.blob(let lhs), .blob(let rhs)):
case let (.blob(lhs), .blob(rhs)):
return lhs.lexicographicallyPrecedes(rhs, by: <)
case (.blob, _):
return false
+72 -14
View File
@@ -1,9 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
// MARK: - Conversion Context and Errors
@@ -14,6 +14,7 @@ struct ValueConversionContext {
case columnIndex(Int)
case columnName(String)
}
var row: Row?
var sql: String?
var arguments: StatementArguments?
@@ -89,7 +90,12 @@ extension ValueConversionContext {
/// The canonical conversion error message
///
/// - parameter dbValue: nil means "missing column"
func conversionErrorMessage<T>(to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?) -> String {
func conversionErrorMessage<T>(
to: T.Type,
from dbValue: DatabaseValue?,
conversionContext: ValueConversionContext?)
-> String
{
var message: String
var extras: [String] = []
@@ -128,12 +134,33 @@ func conversionErrorMessage<T>(to: T.Type, from dbValue: DatabaseValue?, convers
/// The canonical conversion fatal error
///
/// - parameter dbValue: nil means "missing column", for consistency with (row["missing"] as DatabaseValue? == nil)
func fatalConversionError<T>(to: T.Type, from dbValue: DatabaseValue?, conversionContext: ValueConversionContext?, file: StaticString = #file, line: UInt = #line) -> Never {
fatalError(conversionErrorMessage(to: T.self, from: dbValue, conversionContext: conversionContext), file: file, line: line)
func fatalConversionError<T>(
to: T.Type,
from dbValue: DatabaseValue?,
conversionContext: ValueConversionContext?,
file: StaticString = #file,
line: UInt = #line)
-> Never
{
fatalError(
conversionErrorMessage(
to: T.self,
from: dbValue,
conversionContext: conversionContext),
file: file,
line: line)
}
@usableFromInline
func fatalConversionError<T>(to: T.Type, from dbValue: DatabaseValue?, in row: Row, atColumn columnName: String, file: StaticString = #file, line: UInt = #line) -> Never {
func fatalConversionError<T>(
to: T.Type,
from dbValue: DatabaseValue?,
in row: Row,
atColumn columnName: String,
file: StaticString = #file,
line: UInt = #line)
-> Never
{
fatalConversionError(
to: T.self,
from: dbValue,
@@ -141,7 +168,14 @@ func fatalConversionError<T>(to: T.Type, from dbValue: DatabaseValue?, in row: R
}
@usableFromInline
func fatalConversionError<T>(to: T.Type, sqliteStatement: SQLiteStatement, index: Int32, file: StaticString = #file, line: UInt = #line) -> Never {
func fatalConversionError<T>(
to: T.Type,
sqliteStatement: SQLiteStatement,
index: Int32,
file: StaticString = #file,
line: UInt = #line)
-> Never
{
let row = Row(sqliteStatement: sqliteStatement)
fatalConversionError(
to: T.self,
@@ -150,7 +184,15 @@ func fatalConversionError<T>(to: T.Type, sqliteStatement: SQLiteStatement, index
}
@usableFromInline
func fatalConversionError<T>(to: T.Type, from dbValue: DatabaseValue?, sqliteStatement: SQLiteStatement, index: Int32, file: StaticString = #file, line: UInt = #line) -> Never {
func fatalConversionError<T>(
to: T.Type,
from dbValue: DatabaseValue?,
sqliteStatement: SQLiteStatement,
index: Int32,
file: StaticString = #file,
line: UInt = #line)
-> Never
{
let row = Row(sqliteStatement: sqliteStatement)
fatalConversionError(
to: T.self,
@@ -172,7 +214,11 @@ extension DatabaseValueConvertible {
}
}
static func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self {
static func decode(
from dbValue: DatabaseValue,
conversionContext: @autoclosure () -> ValueConversionContext?)
-> Self
{
if let value = fromDatabaseValue(dbValue) {
return value
} else {
@@ -198,8 +244,12 @@ extension DatabaseValueConvertible {
fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index)
}
}
static func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self? {
static func decodeIfPresent(
from dbValue: DatabaseValue,
conversionContext: @autoclosure () -> ValueConversionContext?)
-> Self?
{
// Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
if let value = fromDatabaseValue(dbValue) {
return value
@@ -258,12 +308,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// Support for @inlinable decoding
extension Row {
@usableFromInline
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ type: Value.Type, atUncheckedIndex index: Int) -> Value {
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
-> Value
{
return impl.fastDecode(type, atUncheckedIndex: index)
}
@usableFromInline
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ type: Value.Type, atUncheckedIndex index: Int) -> Value? {
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
-> Value?
{
return impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
}
}
+82 -20
View File
@@ -1,9 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
// MARK: - DatabaseValueConvertible
@@ -24,7 +24,7 @@
/// try String.fetchOne(statement, arguments:...) // String?
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public protocol DatabaseValueConvertible : SQLExpressible {
public protocol DatabaseValueConvertible: SQLExpressible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
@@ -49,7 +49,7 @@ extension DatabaseValueConvertible {
/// print(url)
/// }
/// }
public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
@usableFromInline let _statement: SelectStatement
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline let _columnIndex: Int32
@@ -65,6 +65,9 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor
_columnIndex = 0
}
_statement.reset(withArguments: arguments)
// Assume cursor is created for iteration
statement.database.selectStatementWillExecute(statement)
}
deinit {
@@ -102,12 +105,12 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor
/// print(url)
/// }
/// }
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
@usableFromInline let _statement: SelectStatement
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline let _columnIndex: Int32
@usableFromInline var _done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
_statement = statement
_sqliteStatement = statement.sqliteStatement
@@ -118,6 +121,9 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>
_columnIndex = 0
}
_statement.reset(withArguments: arguments)
// Assume cursor is created for iteration
statement.database.selectStatementWillExecute(statement)
}
deinit {
@@ -182,7 +188,12 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
public static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> DatabaseValueCursor<Self>
{
return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
@@ -197,7 +208,12 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
public static func fetchAll(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
@@ -215,7 +231,12 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
public static func fetchOne(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{
// fetchOne returns nil if there is no row, or if there is a row with a null value
let cursor = try NullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
return try cursor.next() ?? nil
@@ -223,7 +244,7 @@ extension DatabaseValueConvertible {
}
extension DatabaseValueConvertible {
// MARK: Fetching From SQL
/// Returns a cursor over values fetched from an SQL query.
@@ -245,7 +266,13 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> DatabaseValueCursor<Self>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -260,7 +287,13 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] {
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -278,7 +311,13 @@ extension DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? {
public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> Self?
{
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -430,7 +469,12 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
public static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> NullableDatabaseValueCursor<Wrapped>
{
return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
@@ -445,7 +489,12 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
public static func fetchAll(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
}
@@ -473,7 +522,13 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> NullableDatabaseValueCursor<Wrapped>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -488,7 +543,13 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] {
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -515,7 +576,9 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - request: A FetchRequest.
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor<Wrapped> {
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
throws -> NullableDatabaseValueCursor<Wrapped>
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchCursor(request.statement, adapter: request.adapter)
}
@@ -572,4 +635,3 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
}
}
+107 -61
View File
@@ -15,10 +15,10 @@ import Dispatch
/// connection to the database. Should you have to cope with external
/// connections, protect yourself with transactions, and be ready to setup a
/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html).
public protocol DatabaseWriter : DatabaseReader {
public protocol DatabaseWriter: DatabaseReader {
// MARK: - Writing in Database
/// Synchronously executes database updates in a protected dispatch queue,
/// wrapped inside a transaction, and returns the result.
///
@@ -76,16 +76,18 @@ public protocol DatabaseWriter : DatabaseReader {
/// - parameter completion: A closure that is called with the eventual
/// transaction error.
/// - throws: The error thrown by the updates, or by the wrapping transaction.
func asyncWrite<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void)
func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
#endif
/// Asynchronously executes database updates in a protected dispatch queue,
/// outside of any transaction.
///
/// Eventual concurrent reads may see partial updates unless you wrap them
/// in a transaction.
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
/// Synchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
@@ -98,7 +100,7 @@ public protocol DatabaseWriter : DatabaseReader {
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T
// MARK: - Reading from Database
/// Concurrently executes a read-only block in a protected dispatch queue.
@@ -175,7 +177,7 @@ public protocol DatabaseWriter : DatabaseReader {
}
extension DatabaseWriter {
/// Synchronously executes database updates in a protected dispatch queue,
/// wrapped inside a transaction, and returns the result.
///
@@ -228,7 +230,10 @@ extension DatabaseWriter {
/// - parameter completion: A closure that is called with the eventual
/// transaction error.
/// - throws: The error thrown by the updates, or by the wrapping transaction.
public func asyncWrite<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void) {
public func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
{
asyncWriteWithoutTransaction { db in
do {
var result: T?
@@ -255,7 +260,10 @@ extension DatabaseWriter {
/// - parameter extent: The duration of the observation. The default is
/// the observer lifetime (observation lasts until observer
/// is deallocated).
public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) {
public func add(
transactionObserver: TransactionObserver,
extent: Database.TransactionObservationExtent = .observerLifetime)
{
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
}
@@ -273,7 +281,8 @@ extension DatabaseWriter {
/// execution of this method.
public func erase() throws {
#if SQLITE_HAS_CODEC
// SQLCipher does not support the backup API: https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
// SQLCipher does not support the backup API:
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
// So we'll drop all database objects one after the other.
try writeWithoutTransaction { db in
// Prevent foreign keys from messing with drop table statements
@@ -285,7 +294,8 @@ extension DatabaseWriter {
// Remove all database objects, one after the other
do {
try db.inTransaction {
while let row = try Row.fetchOne(db, sql: "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") {
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
while let row = try Row.fetchOne(db, sql: sql) {
let type: String = row["type"]
let name: String = row["name"]
try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
@@ -333,6 +343,7 @@ extension DatabaseWriter {
let requiresWriteAccess = observation.requiresWriteAccess
let observer = ValueObserver<Reducer>(
requiresWriteAccess: requiresWriteAccess,
observesSelectedRegion: observation.observesSelectedRegion,
writer: self,
reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"),
onError: onError,
@@ -353,18 +364,23 @@ extension DatabaseWriter {
do {
try unsafeReentrantWrite { db in
let region = try observation.observedRegion(db)
var reducer = try observation.makeReducer(db)
observer.notificationQueue = DispatchQueue.main
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
observer.reducer = try observation.makeReducer(db)
// Fetch initial value
if let value = try reducer.value(reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)) {
// Initial value & selected region
let fetchedValue: Reducer.Fetched
if observation.observesSelectedRegion {
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
} else {
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
if let value = observer.reducer.value(fetchedValue) {
startValue = value
}
// Start observing the database
observer.region = region
observer.reducer = reducer
observer.notificationQueue = DispatchQueue.main
db.add(transactionObserver: observer, extent: .observerLifetime)
}
} catch {
@@ -375,20 +391,25 @@ extension DatabaseWriter {
// has the default scheduling .mainQueue
asyncWriteWithoutTransaction { db in
do {
let region = try observation.observedRegion(db)
var reducer = try observation.makeReducer(db)
observer.notificationQueue = DispatchQueue.main
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
observer.reducer = try observation.makeReducer(db)
// Fetch initial value
if let value = try reducer.value(reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)) {
// Initial value & selected region
let fetchedValue: Reducer.Fetched
if observation.observesSelectedRegion {
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
} else {
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
if let value = observer.reducer.value(fetchedValue) {
DispatchQueue.main.async {
onChange(value)
}
}
// Start observing the database
observer.region = region
observer.reducer = reducer
observer.notificationQueue = DispatchQueue.main
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
DispatchQueue.main.async {
@@ -402,22 +423,31 @@ extension DatabaseWriter {
// Use case: observation must not block the target queue
asyncWriteWithoutTransaction { db in
do {
let region = try observation.observedRegion(db)
var reducer = try observation.makeReducer(db)
observer.notificationQueue = queue
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
observer.reducer = try observation.makeReducer(db)
// Fetch initial value
if startImmediately,
let value = try reducer.value(reducer.fetch(db, requiringWriteAccess: requiresWriteAccess))
{
queue.async {
onChange(value)
// Initial value & selected region
if startImmediately {
let fetchedValue: Reducer.Fetched
if observation.observesSelectedRegion {
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
} else {
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
if let value = observer.reducer.value(fetchedValue) {
queue.async {
onChange(value)
}
}
} else if observation.observesSelectedRegion {
(_, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
}
// Start observing the database
observer.region = region
observer.reducer = reducer
observer.notificationQueue = queue
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
queue.async {
@@ -448,20 +478,29 @@ extension DatabaseWriter {
do {
try unsafeReentrantWrite { db in
let region = try observation.observedRegion(db)
var reducer = try observation.makeReducer(db)
observer.notificationQueue = nil
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
observer.reducer = try observation.makeReducer(db)
// Fetch initial value
if startImmediately,
let value = try reducer.value(reducer.fetch(db, requiringWriteAccess: requiresWriteAccess))
{
startValue = value
// Initial value & selected region
if startImmediately {
let fetchedValue: Reducer.Fetched
if observation.observesSelectedRegion {
(fetchedValue, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
} else {
fetchedValue = try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
if let value = observer.reducer.value(fetchedValue) {
startValue = value
}
} else if observation.observesSelectedRegion {
(_, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
}
// Start observing the database
observer.region = region
observer.reducer = reducer
observer.notificationQueue = nil
db.add(transactionObserver: observer, extent: .observerLifetime)
}
} catch {
@@ -474,13 +513,17 @@ extension DatabaseWriter {
// queue on which the onChange and onError callbacks are called.
asyncWriteWithoutTransaction { db in
do {
let region = try observation.observedRegion(db)
let reducer = try observation.makeReducer(db)
// Start observing the database
observer.region = region
observer.reducer = reducer
observer.notificationQueue = nil
observer.baseRegion = try observation.baseRegion(db).ignoringViews(db)
observer.reducer = try observation.makeReducer(db)
// Selected region
if observation.observesSelectedRegion {
(_, observer.selectedRegion) = try db.recordingSelectedRegion {
try observer.reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
}
}
db.add(transactionObserver: observer, extent: .observerLifetime)
} catch {
onError(error)
@@ -545,7 +588,7 @@ public class DatabaseFuture<Value> {
///
/// Instances of AnyDatabaseWriter forward their methods to an arbitrary
/// underlying database writer.
public final class AnyDatabaseWriter : DatabaseWriter {
public final class AnyDatabaseWriter: DatabaseWriter {
private let base: DatabaseWriter
/// Creates a database writer that wraps a base database writer.
@@ -608,7 +651,10 @@ public final class AnyDatabaseWriter : DatabaseWriter {
#if compiler(>=5.0)
/// :nodoc:
public func asyncWrite<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void) {
public func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
{
base.asyncWrite(updates, completion: completion)
}
#endif
@@ -617,12 +663,12 @@ public final class AnyDatabaseWriter : DatabaseWriter {
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
base.asyncWriteWithoutTransaction(updates)
}
/// :nodoc:
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
return try base.unsafeReentrantWrite(updates)
}
// MARK: - Functions
/// :nodoc:
+5 -5
View File
@@ -23,7 +23,7 @@ public struct PreparedRequest {
{
self.init(statement: statement, adapter: adapter, supplementaryFetch: nil)
}
init(
statement: SelectStatement,
adapter: RowAdapter?,
@@ -62,7 +62,7 @@ public protocol FetchRequest: DatabaseRegionConvertible {
/// prepared statement.
/// - returns: A prepared statement and an eventual row adapter.
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
/// Returns a PreparedRequest that is ready to be executed.
///
/// - parameter db: A database connection.
@@ -86,7 +86,7 @@ public protocol FetchRequest: DatabaseRegionConvertible {
}
extension FetchRequest {
/// Returns an adapted request.
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
return AdaptedFetchRequest(self, adapter)
@@ -134,7 +134,7 @@ extension FetchRequest {
// MARK: - AdaptedFetchRequest
/// An adapted request.
public struct AdaptedFetchRequest<Base: FetchRequest> : FetchRequest {
public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
public typealias RowDecoder = Base.RowDecoder
private let base: Base
@@ -175,7 +175,7 @@ public struct AdaptedFetchRequest<Base: FetchRequest> : FetchRequest {
///
/// An AnyFetchRequest forwards its operations to an underlying request,
/// hiding its specifics.
public struct AnyFetchRequest<T> : FetchRequest {
public struct AnyFetchRequest<T>: FetchRequest {
public typealias RowDecoder = T
private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest
+105 -40
View File
@@ -1,14 +1,17 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// A database row.
public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible {
public final class Row: Equatable, Hashable, RandomAccessCollection,
ExpressibleByDictionaryLiteral, CustomStringConvertible,
CustomDebugStringConvertible
{
// It is not a violation of the Demeter law when another type uses this
// property, which is exposed for optimizations.
let impl: RowImpl
@@ -45,7 +48,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl
/// let bookRows = row.prefetchedRows["books"]
/// print(bookRows[0])
/// // Prints [id:42 title:"Moby-Dick"]
public internal(set) var prefetchedRows: PrefetchedRowsView = PrefetchedRowsView()
public internal(set) var prefetchedRows = PrefetchedRowsView()
// MARK: - Building rows
@@ -126,8 +129,13 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl
/// The row is implemented on top of StatementCopyRowImpl, which *copies*
/// the values from the SQLite statement so that further iteration of the
/// statement does not modify the row.
convenience init(copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, statementRef: Unmanaged<SelectStatement>) {
self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: statementRef.takeUnretainedValue().columnNames))
convenience init(
copiedFromSQLiteStatement sqliteStatement: SQLiteStatement,
statementRef: Unmanaged<SelectStatement>)
{
self.init(impl: StatementCopyRowImpl(
sqliteStatement: sqliteStatement,
columnNames: statementRef.takeUnretainedValue().columnNames))
}
init(impl: RowImpl) {
@@ -139,7 +147,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl
}
extension Row {
// MARK: - Columns
/// The names of columns in the row.
@@ -416,7 +424,12 @@ extension Row {
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible, Column: ColumnExpression>(_ column: Column) -> Value? {
public subscript<Value, Column>(_ column: Column)
-> Value?
where
Value: DatabaseValueConvertible & StatementColumnConvertible,
Column: ColumnExpression
{
return self[column.name]
}
@@ -448,7 +461,12 @@ extension Row {
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible, Column: ColumnExpression>(_ column: Column) -> Value {
public subscript<Value, Column>(_ column: Column)
-> Value
where
Value: DatabaseValueConvertible & StatementColumnConvertible,
Column: ColumnExpression
{
return self[column.name]
}
@@ -565,7 +583,7 @@ extension Row {
}
return Record(row: scopedRow)
}
/// Returns the eventual record associated with the given scope.
///
/// For example:
@@ -761,7 +779,7 @@ extension Row {
/// try dbQueue.read { db in
/// let rows: RowCursor = try Row.fetchCursor(db, sql: "SELECT * FROM player")
/// }
public final class RowCursor : Cursor {
public final class RowCursor: Cursor {
public let statement: SelectStatement
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline let _row: Row // Reused for performance
@@ -772,6 +790,9 @@ public final class RowCursor : Cursor {
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
self._sqliteStatement = statement.sqliteStatement
statement.reset(withArguments: arguments)
// Assume cursor is created for iteration
statement.database.selectStatementWillExecute(statement)
}
deinit {
@@ -833,7 +854,12 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor {
public static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> RowCursor
{
return try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
}
@@ -848,7 +874,12 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] {
public static func fetchAll(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Row]
{
// The cursor reuses a single mutable row. Return immutable copies.
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter).map { $0.copy() })
}
@@ -864,7 +895,12 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? {
public static func fetchOne(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Row?
{
let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter)
// Keep cursor alive until we can copy the fetched row
return try withExtendedLifetime(cursor) {
@@ -905,7 +941,13 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor {
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> RowCursor
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -924,7 +966,13 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row] {
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> [Row]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -943,7 +991,13 @@ extension Row {
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row? {
public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> Row?
{
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -1079,7 +1133,7 @@ extension FetchRequest where RowDecoder == Row {
return try Row.fetchOne(db, self)
}
}
// ExpressibleByDictionaryLiteral
extension Row {
@@ -1198,7 +1252,7 @@ extension Row {
if level == 0 && self == self.unadapted && prefetchedRows.prefetches.isEmpty {
return description
}
let prefix = repeatElement(" ", count: level + 1).joined(separator: "")
let prefix = repeatElement(" ", count: level + 1).joined()
var str = ""
if level == 0 {
str = "▿ " + description
@@ -1234,7 +1288,7 @@ extension Row {
// MARK: - RowIndex
/// Indexes to (ColumnName, DatabaseValue) pairs in a database row.
public struct RowIndex : Comparable, Strideable {
public struct RowIndex: Comparable, Strideable {
let index: Int
init(_ index: Int) { self.index = index }
}
@@ -1386,7 +1440,7 @@ extension Row {
}
return names
}
/// Returns the row associated with the given scope.
///
/// For example:
@@ -1461,7 +1515,7 @@ extension Row {
public var isEmpty: Bool {
return prefetches.isEmpty
}
/// The keys for available prefetched rows
///
/// For example:
@@ -1483,7 +1537,7 @@ extension Row {
}
return result
}
/// Returns the prefetched rows associated with the given key.
///
/// For example:
@@ -1538,13 +1592,20 @@ extension OrderedDictionary where Key == String, Value == Row.Prefetch {
protocol RowImpl {
var count: Int { get }
var isFetched: Bool { get }
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView
func columnName(atUncheckedIndex index: Int) -> String
func hasNull(atUncheckedIndex index:Int) -> Bool
func hasNull(atUncheckedIndex index: Int) -> Bool
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ type: Value.Type, atUncheckedIndex index: Int) -> Value
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ type: Value.Type, atUncheckedIndex index: Int) -> Value?
func dataNoCopy(atUncheckedIndex index:Int) -> Data?
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
-> Value
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
-> Value?
func dataNoCopy(atUncheckedIndex index: Int) -> Data?
/// Returns the index of the leftmost column that matches *name* (case-insensitive)
func index(ofColumn name: String) -> Int?
@@ -1558,7 +1619,7 @@ protocol RowImpl {
extension RowImpl {
func copiedRow(_ row: Row) -> Row {
// unless customized, assume unsafe and unadapted row
return Row(impl: ArrayRowImpl(columns: row.map { $0 }))
return Row(impl: ArrayRowImpl(columns: Array(row)))
}
func unscopedRow(_ row: Row) -> Row {
@@ -1576,7 +1637,7 @@ extension RowImpl {
return Row.ScopesView()
}
func hasNull(atUncheckedIndex index:Int) -> Bool {
func hasNull(atUncheckedIndex index: Int) -> Bool {
// unless customized, use slow check (see StatementRowImpl and AdaptedRowImpl for customization)
return databaseValue(atUncheckedIndex: index).isNull
}
@@ -1601,7 +1662,7 @@ extension RowImpl {
conversionContext: ValueConversionContext(Row(impl: self)).atColumn(index))
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
return Data.decodeIfPresent(
from: databaseValue(atUncheckedIndex: index),
@@ -1611,7 +1672,7 @@ extension RowImpl {
// TODO: merge with StatementCopyRowImpl eventually?
/// See Row.init(dictionary:)
private struct ArrayRowImpl : RowImpl {
private struct ArrayRowImpl: RowImpl {
let columns: [(String, DatabaseValue)]
init(columns: [(String, DatabaseValue)]) {
@@ -1647,13 +1708,16 @@ private struct ArrayRowImpl : RowImpl {
// TODO: merge with ArrayRowImpl eventually?
/// See Row.init(copiedFromStatementRef:sqliteStatement:)
private struct StatementCopyRowImpl : RowImpl {
private struct StatementCopyRowImpl: RowImpl {
let dbValues: ContiguousArray<DatabaseValue>
let columnNames: [String]
init(sqliteStatement: SQLiteStatement, columnNames: [String]) {
let sqliteStatement = sqliteStatement
self.dbValues = ContiguousArray((0..<sqlite3_column_count(sqliteStatement)).map { DatabaseValue(sqliteStatement: sqliteStatement, index: $0) } as [DatabaseValue])
self.dbValues = ContiguousArray(
(0..<sqlite3_column_count(sqliteStatement))
.map { DatabaseValue(sqliteStatement: sqliteStatement, index: $0) }
as [DatabaseValue])
self.columnNames = columnNames
}
@@ -1685,7 +1749,7 @@ private struct StatementCopyRowImpl : RowImpl {
/// See Row.init(statement:)
private struct StatementRowImpl : RowImpl {
private struct StatementRowImpl: RowImpl {
let statementRef: Unmanaged<SelectStatement>
let sqliteStatement: SQLiteStatement
let lowercaseColumnIndexes: [String: Int]
@@ -1694,7 +1758,8 @@ private struct StatementRowImpl : RowImpl {
self.statementRef = statementRef
self.sqliteStatement = sqliteStatement
// Optimize row[columnName]
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement)).map { String(cString: sqlite3_column_name(sqliteStatement, Int32($0))).lowercased() }
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement))
.map { String(cString: sqlite3_column_name(sqliteStatement, Int32($0))).lowercased() }
self.lowercaseColumnIndexes = Dictionary(
lowercaseColumnNames
.enumerated()
@@ -1710,12 +1775,12 @@ private struct StatementRowImpl : RowImpl {
return true
}
func hasNull(atUncheckedIndex index:Int) -> Bool {
func hasNull(atUncheckedIndex index: Int) -> Bool {
// Avoid extracting values, because this modifies the SQLite statement.
return sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
return nil
}
@@ -1761,7 +1826,7 @@ private struct StatementRowImpl : RowImpl {
}
// This one is not optimized at all, since it is only used in fatal conversion errors, so far
private struct SQLiteStatementRowImpl : RowImpl {
private struct SQLiteStatementRowImpl: RowImpl {
let sqliteStatement: SQLiteStatement
var count: Int { return Int(sqlite3_column_count(sqliteStatement)) }
var isFetched: Bool { return true }
@@ -1784,7 +1849,7 @@ private struct SQLiteStatementRowImpl : RowImpl {
}
/// See Row.init()
private struct EmptyRowImpl : RowImpl {
private struct EmptyRowImpl: RowImpl {
var count: Int {
return 0
}
+20 -15
View File
@@ -100,7 +100,7 @@ public struct LayoutedColumnMapping {
/// LayoutedColumnMapping adopts LayoutedRowAdapter
///
/// :nodoc:
extension LayoutedColumnMapping : LayoutedRowAdapter {
extension LayoutedColumnMapping: LayoutedRowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns self.
@@ -117,7 +117,7 @@ extension LayoutedColumnMapping : LayoutedRowAdapter {
}
/// :nodoc:
extension LayoutedColumnMapping : RowLayout {
extension LayoutedColumnMapping: RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns the index of the leftmost column named `name`, in a
@@ -171,7 +171,7 @@ public protocol RowLayout {
func layoutIndex(ofColumn name: String) -> Int?
}
extension SelectStatement : RowLayout {
extension SelectStatement: RowLayout {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var layoutColumns: [(Int, String)] {
@@ -270,7 +270,7 @@ public struct EmptyRowAdapter: RowAdapter {
///
/// // [foo:"bar"]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public struct ColumnMapping : RowAdapter {
public struct ColumnMapping: RowAdapter {
/// A dictionary from mapped column names to column names in a base row.
let mapping: [String: String]
@@ -287,7 +287,12 @@ public struct ColumnMapping : RowAdapter {
.map { (mappedColumn, baseColumn) -> (Int, String) in
guard let index = layout.layoutIndex(ofColumn: baseColumn) else {
let columnNames = layout.layoutColumns.map { $0.1 }
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(columnNames.joined(separator: ", ")).")
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: """
Mapping references missing column \(baseColumn). \
Valid column names are: \(columnNames.joined(separator: ", ")).
""")
}
let baseIndex = layout.layoutColumns[index].0
return (baseIndex, mappedColumn)
@@ -304,7 +309,7 @@ public struct ColumnMapping : RowAdapter {
///
/// // [baz:3]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public struct SuffixRowAdapter : RowAdapter {
public struct SuffixRowAdapter: RowAdapter {
/// The suffix index
let index: Int
@@ -331,7 +336,7 @@ public struct SuffixRowAdapter : RowAdapter {
///
/// // [bar:2 baz:3]
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public struct RangeRowAdapter : RowAdapter {
public struct RangeRowAdapter: RowAdapter {
/// The range
let range: CountableRange<Int>
@@ -376,7 +381,7 @@ public struct RangeRowAdapter : RowAdapter {
/// if let barRow = row.scopes["bar"] {
/// barRow["value"] // "bar"
/// }
public struct ScopeAdapter : RowAdapter {
public struct ScopeAdapter: RowAdapter {
/// The base adapter
let base: RowAdapter
@@ -439,15 +444,15 @@ public struct ScopeAdapter : RowAdapter {
}
/// The LayoutedRowAdapter for ScopeAdapter
struct LayoutedScopeAdapter : LayoutedRowAdapter {
struct LayoutedScopeAdapter: LayoutedRowAdapter {
let mapping: LayoutedColumnMapping
let scopes: [String: LayoutedRowAdapter]
}
struct ChainedAdapter : RowAdapter {
struct ChainedAdapter: RowAdapter {
let first: RowAdapter
let second: RowAdapter
func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
return try second.layoutedAdapter(from: first.layoutedAdapter(from: layout).mapping)
}
@@ -458,7 +463,7 @@ extension Row {
convenience init(base: Row, adapter: LayoutedRowAdapter) {
self.init(impl: AdaptedRowImpl(base: base, adapter: adapter))
}
/// Returns self if adapter is nil
func adapted(with adapter: RowAdapter?, layout: RowLayout) throws -> Row {
guard let adapter = adapter else {
@@ -468,7 +473,7 @@ extension Row {
}
}
struct AdaptedRowImpl : RowImpl {
struct AdaptedRowImpl: RowImpl {
let base: Row
let adapter: LayoutedRowAdapter
let mapping: LayoutedColumnMapping
@@ -517,7 +522,7 @@ struct AdaptedRowImpl : RowImpl {
return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex)
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex)
}
@@ -533,7 +538,7 @@ struct AdaptedRowImpl : RowImpl {
func copiedRow(_ row: Row) -> Row {
return Row(base: base.copy(), adapter: adapter)
}
func unscopedRow(_ row: Row) -> Row {
assert(adapter.mapping.scopes.isEmpty)
return Row(base: base, adapter: adapter.mapping)
+4 -4
View File
@@ -7,23 +7,23 @@ public struct SQLInterpolation: StringInterpolationProtocol {
get { return context.arguments! }
set { context.arguments = newValue }
}
public init(literalCapacity: Int, interpolationCount: Int) {
sql = ""
sql.reserveCapacity(literalCapacity + interpolationCount)
}
/// "SELECT * FROM player"
public mutating func appendLiteral(_ sql: String) {
self.sql += sql
}
/// "SELECT * FROM \(sql: "player")"
public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) {
self.sql += sql
self.arguments += arguments
}
/// "SELECT * FROM player WHERE \(literal: condition)"
public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) {
sql += sqlLiteral.sql
+5 -4
View File
@@ -1,4 +1,5 @@
/// SQLLiteral is a type which support [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
/// SQLLiteral is a type which support [SQL
/// Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
///
/// For example:
///
@@ -9,8 +10,8 @@
/// try db.execute(literal: query)
/// }
public struct SQLLiteral {
private(set) public var sql: String
private(set) public var arguments: StatementArguments
public private(set) var sql: String
public private(set) var arguments: StatementArguments
/// Creates an SQLLiteral from a plain SQL string, and eventual arguments.
///
@@ -63,7 +64,7 @@ extension SQLLiteral {
public mutating func append(literal sqlLiteral: SQLLiteral) {
self += sqlLiteral
}
/// Appends a plain SQL string to the receiver, and eventual arguments.
///
/// let name = "O'Brien"
+21 -7
View File
@@ -1,5 +1,5 @@
/// A FetchRequest built from raw SQL.
public struct SQLRequest<T> : FetchRequest {
public struct SQLRequest<T>: FetchRequest {
/// There are two statement caches: one "public" for statements generated by
/// the user, and one "internal" for the statements generated by GRDB. Those
/// are separated so that GRDB has no opportunity to inadvertently modify
@@ -30,10 +30,10 @@ public struct SQLRequest<T> : FetchRequest {
/// The request adapter
public var adapter: RowAdapter?
private var sqlLiteral: SQLLiteral
private let cache: Cache?
/// Creates a request from an SQL string, optional arguments, and
/// optional row adapter.
///
@@ -51,8 +51,16 @@ public struct SQLRequest<T> : FetchRequest {
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: A SQLRequest
public init(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(literal: SQLLiteral(sql: sql, arguments: arguments), adapter: adapter, fromCache: cached ? .public : nil)
public init(
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil,
cached: Bool = false)
{
self.init(
literal: SQLLiteral(sql: sql, arguments: arguments),
adapter: adapter,
fromCache: cached ? .public : nil)
}
/// Creates a request from an SQLLiteral, and optional row adapter.
@@ -80,7 +88,7 @@ public struct SQLRequest<T> : FetchRequest {
public init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates an SQL request from any other fetch request.
///
/// - parameters:
@@ -89,7 +97,13 @@ public struct SQLRequest<T> : FetchRequest {
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: An SQLRequest
public init<Request: FetchRequest>(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder {
public init<Request>(
_ db: Database,
request: Request,
cached: Bool = false)
throws
where Request: FetchRequest, Request.RowDecoder == RowDecoder
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
self.init(
literal: SQLLiteral(sql: request.statement.sql, arguments: request.statement.arguments),
+6 -1
View File
@@ -43,7 +43,12 @@ final class SchedulingWatchdog {
return try body()
}
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
static func preconditionValidQueue(
_ db: Database,
_ message: @autoclosure() -> String = "Database was not used on the correct thread.",
file: StaticString = #file,
line: UInt = #line)
{
GRDBPrecondition(current?.allows(db) ?? false, message(), file: file, line: line)
}
+24 -4
View File
@@ -16,7 +16,14 @@ final class SerializedDatabase {
/// The dispatch queue
private let queue: DispatchQueue
init(path: String, configuration: Configuration = Configuration(), schemaCache: DatabaseSchemaCache, defaultLabel: String, purpose: String? = nil) throws {
init(
path: String,
configuration: Configuration = Configuration(),
schemaCache: DatabaseSchemaCache,
defaultLabel: String,
purpose: String? = nil)
throws
{
// According to https://www.sqlite.org/threadsafe.html
//
// > SQLite support three different threading modes:
@@ -193,12 +200,25 @@ final class SerializedDatabase {
}
/// Fatal error if current dispatch queue is not valid.
func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
func preconditionValidQueue(
_ message: @autoclosure() -> String = "Database was not used on the correct thread.",
file: StaticString = #file,
line: UInt = #line)
{
SchedulingWatchdog.preconditionValidQueue(db, message(), file: file, line: line)
}
/// Fatal error if a transaction has been left opened.
private func preconditionNoUnsafeTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message(), file: file, line: line)
private func preconditionNoUnsafeTransactionLeft(
_ db: Database,
_ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access",
file: StaticString = #file,
line: UInt = #line)
{
GRDBPrecondition(
configuration.allowsUnsafeTransactions || !db.isInsideTransaction,
message(),
file: file,
line: line)
}
}
+97 -91
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// A raw SQLite statement, suitable for the SQLite C API.
@@ -43,6 +43,7 @@ public class Statement {
/// statement in the C string.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - parameter authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
@@ -56,18 +57,25 @@ public class Statement {
var sqliteStatement: SQLiteStatement? = nil
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd)
let code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
&sqliteStatement, statementEnd)
#else
let code: Int32
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd)
code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
&sqliteStatement, statementEnd)
} else {
code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
}
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: String(cString: statementStart))
throw DatabaseError(
resultCode: code,
message: database.lastErrorMessage,
sql: String(cString: statementStart))
}
guard let statement = sqliteStatement else {
@@ -102,7 +110,7 @@ public class Statement {
// Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
fileprivate lazy var sqliteArgumentNames: [String?] = {
return (0..<self.sqliteArgumentCount).map {
(0..<self.sqliteArgumentCount).map {
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, Int32($0 + 1)) else {
return nil
}
@@ -203,7 +211,7 @@ public class Statement {
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
}
}
fileprivate func prepare(withArguments arguments: StatementArguments?) {
// Force arguments validity: it is a programmer error to provide
// arguments that do not match the statement.
@@ -217,45 +225,41 @@ public class Statement {
// MARK: - Statement Preparation
/// A common protocol for UpdateStatement and SelectStatement, only used as
/// support for SelectStatement.prepare(...) and UpdateStatement.prepare(...).
protocol StatementProtocol { }
extension Statement: StatementProtocol { }
extension StatementProtocol where Self: Statement {
extension Statement {
// Static method instead of an initializer because initializer can't run
// inside `sqlCodeUnits.withUnsafeBufferPointer`.
static func prepare(sql: String, prepFlags: Int32, in database: Database) throws -> Self {
static func prepare(_ db: Database, sql: String, prepFlags: Int32) throws -> Self {
let authorizer = StatementCompilationAuthorizer()
database.authorizer = authorizer
defer { database.authorizer = nil }
return try sql.utf8CString.withUnsafeBufferPointer { buffer in
let statementStart = buffer.baseAddress!
var statementEnd: UnsafePointer<Int8>? = nil
guard let statement = try self.init(
database: database,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: authorizer) else
{
throw DatabaseError(
resultCode: .SQLITE_ERROR,
message: "empty statement",
sql: sql,
arguments: nil)
return try db.withAuthorizer(authorizer) {
try sql.utf8CString.withUnsafeBufferPointer { buffer in
let statementStart = buffer.baseAddress!
var statementEnd: UnsafePointer<Int8>? = nil
guard let statement = try self.init(
database: db,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: authorizer) else
{
throw DatabaseError(
resultCode: .SQLITE_ERROR,
message: "empty statement",
sql: sql)
}
let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators)
guard remainingSQL.isEmpty else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: """
Multiple statements found. To execute multiple statements, \
use Database.execute(sql:) instead.
""",
sql: sql)
}
return statement
}
let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators)
guard remainingSQL.isEmpty else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "Multiple statements found. To execute multiple statements, use Database.execute(sql:) instead.",
sql: sql,
arguments: nil)
}
return statement
}
}
}
@@ -271,9 +275,13 @@ extension StatementProtocol where Self: Statement {
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
/// }
public final class SelectStatement : Statement {
public final class SelectStatement: Statement {
// Database region is computed during statement compilation, and maybe
// optimized when statement is compiled for a QueryInterfaceRequest, in
// order to perform focused database observation. See
// SQLQueryGenerator.optimizedDatabaseRegion(_:_:)
/// The database region that the statement looks into.
public private(set) var databaseRegion = DatabaseRegion()
public internal(set) var databaseRegion = DatabaseRegion()
/// Creates a prepared statement. Returns nil if the compiled string is
/// blank or empty.
@@ -285,7 +293,7 @@ public final class SelectStatement : Statement {
/// statement in the C string.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - authorizer: A StatementCompilationAuthorizer
/// - parameter authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
@@ -301,8 +309,12 @@ public final class SelectStatement : Statement {
prepFlags: prepFlags,
authorizer: authorizer)
GRDBPrecondition(authorizer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
GRDBPrecondition(authorizer.transactionEffect == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
GRDBPrecondition(
authorizer.invalidatesDatabaseSchemaCache == false,
"Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
GRDBPrecondition(
authorizer.transactionEffect == nil,
"Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
self.databaseRegion = authorizer.databaseRegion
}
@@ -320,7 +332,7 @@ public final class SelectStatement : Statement {
/// Cache for index(ofColumn:). Keys are lowercase.
private lazy var columnIndexes: [String: Int] = {
return Dictionary(
Dictionary(
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}()
@@ -353,7 +365,6 @@ public final class SelectStatement : Statement {
message: database.lastErrorMessage,
sql: sql,
arguments: arguments)
}
}
@@ -377,6 +388,9 @@ final class StatementCursor: Cursor {
_statement = statement
_sqliteStatement = statement.sqliteStatement
_statement.reset(withArguments: arguments)
// Assume cursor is created for iteration
statement.database.selectStatementWillExecute(statement)
}
deinit {
@@ -418,7 +432,7 @@ final class StatementCursor: Cursor {
/// try statement.execute(arguments: ["Barbara"])
/// return .commit
/// }
public final class UpdateStatement : Statement {
public final class UpdateStatement: Statement {
enum TransactionEffect {
case beginTransaction
case commitTransaction
@@ -445,7 +459,7 @@ public final class UpdateStatement : Statement {
/// statement in the C string.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - authorizer: A StatementCompilationAuthorizer
/// - parameter authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
@@ -473,38 +487,11 @@ public final class UpdateStatement : Statement {
SchedulingWatchdog.preconditionValidQueue(database)
prepare(withArguments: arguments)
try reset()
database.updateStatementWillExecute(self)
while true {
switch sqlite3_step(sqliteStatement) {
case SQLITE_ROW:
// The statement did return a row, and the user ignores the
// content of this row:
//
// try db.execute(sql: "SELECT ...")
//
// That's OK: maybe the selected rows perform side effects.
// For example:
//
// try db.execute(sql: "SELECT sqlcipher_export(...)")
//
// Or maybe the user doesn't know that the executed statement
// return rows (https://github.com/groue/GRDB.swift/issues/15);
//
// try db.execute(sql: "PRAGMA journal_mode=WAL")
//
// It is thus important that we consume *all* rows.
continue
case SQLITE_DONE:
try database.updateStatementDidExecute(self)
return
case let code:
try database.updateStatementDidFail(self)
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
}
}
// Statement does not know how to execute itself, because it does not
// know how to handle its errors, or if truncate optimisation should be
// prevented or not. Database knows.
try database.executeUpdateStatement(self)
}
}
@@ -589,7 +576,9 @@ public final class UpdateStatement : Statement {
/// .filter(sql: "team = :team", arguments: ["team": "Blue"])
/// .filter(sql: "score > ?", arguments: [1000])
/// .fetchAll(db)
public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {
public struct StatementArguments: CustomStringConvertible, Equatable,
ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral
{
private(set) var values: [DatabaseValue] = []
private(set) var namedValues: [String: DatabaseValue] = [:]
@@ -667,7 +656,9 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
///
/// - parameter sequence: A sequence of (key, value) pairs
/// - returns: A StatementArguments.
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element == (String, DatabaseValueConvertible?) {
public init<Sequence>(_ sequence: Sequence)
where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?)
{
namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) })
}
@@ -843,33 +834,48 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
/// append(contentsOf:) method.
public static func += (lhs: inout StatementArguments, rhs: StatementArguments) {
let replacedValues = lhs.append(contentsOf: rhs)
GRDBPrecondition(replacedValues.isEmpty, "already defined statement argument: \(replacedValues.keys.joined(separator: ", "))")
GRDBPrecondition(
replacedValues.isEmpty,
"already defined statement argument: \(replacedValues.keys.joined(separator: ", "))")
}
// MARK: Not Public
mutating func extractBindings(forStatement statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] {
mutating func extractBindings(
forStatement statement: Statement,
allowingRemainingValues: Bool)
throws -> [DatabaseValue]
{
let initialValuesCount = values.count
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
if let argumentName = argumentName {
if let dbValue = namedValues[argumentName] {
return dbValue
} else if values.isEmpty {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "missing statement argument: \(argumentName)", sql: statement.sql, arguments: nil)
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "missing statement argument: \(argumentName)",
sql: statement.sql)
} else {
return values.removeFirst()
}
} else {
if values.isEmpty {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil)
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "wrong number of statement arguments: \(initialValuesCount)",
sql: statement.sql)
} else {
return values.removeFirst()
}
}
}
if !allowingRemainingValues && !values.isEmpty {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)", sql: statement.sql, arguments: nil)
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "wrong number of statement arguments: \(initialValuesCount)",
sql: statement.sql)
}
return bindings
}
@@ -907,7 +913,7 @@ extension StatementArguments {
public var description: String {
let valuesDescriptions = values.map { $0.description }
let namedValuesDescriptions = namedValues.map { (key, value) -> String in
return "\(String(reflecting: key)): \(value)"
"\(String(reflecting: key)): \(value)"
}
return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]"
}
+23 -16
View File
@@ -1,16 +1,16 @@
#if os(Linux)
import Glibc
import Glibc
#endif
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// A protocol around sqlite3_set_authorizer
protocol StatementAuthorizer : class {
protocol StatementAuthorizer: AnyObject {
func authorize(
_ actionCode: Int32,
_ cString1: UnsafePointer<Int8>?,
@@ -21,7 +21,7 @@ protocol StatementAuthorizer : class {
}
/// A class that gathers information about one statement during its compilation.
final class StatementCompilationAuthorizer : StatementAuthorizer {
final class StatementCompilationAuthorizer: StatementAuthorizer {
/// What this statements reads
var databaseRegion = DatabaseRegion()
@@ -47,7 +47,11 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
_ cString4: UnsafePointer<Int8>?)
-> Int32
{
// print("StatementCompilationAuthorizer: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
// print("""
// StatementCompilationAuthorizer: \
// \(actionCode) \
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) })
// """)
switch actionCode {
case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE,
@@ -67,8 +71,8 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
return SQLITE_OK
case SQLITE_READ:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let tableName = cString1.map(String.init) else { return SQLITE_OK }
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
if columnName.isEmpty {
// SELECT COUNT(*) FROM table
databaseRegion.formUnion(DatabaseRegion(table: tableName))
@@ -79,7 +83,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
return SQLITE_OK
case SQLITE_INSERT:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let tableName = cString1.map(String.init) else { return SQLITE_OK }
databaseEventKinds.append(.insert(tableName: tableName))
return SQLITE_OK
@@ -100,8 +104,8 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
return SQLITE_IGNORE
case SQLITE_UPDATE:
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let tableName = cString1.map(String.init) else { return SQLITE_OK }
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
insertUpdateEventKind(tableName: tableName, columnName: columnName)
return SQLITE_OK
@@ -118,7 +122,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
case SQLITE_SAVEPOINT:
guard let cString1 = cString1 else { return SQLITE_OK }
guard let name = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
guard let name = cString2.map(String.init) else { return SQLITE_OK }
if strcmp(cString1, "BEGIN") == 0 {
transactionEffect = .beginSavepoint(name)
} else if strcmp(cString1, "RELEASE") == 0 {
@@ -168,7 +172,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
//
/// Warning: to perform well, this authorizer must be used during statement
/// execution, not during statement compilation.
final class TruncateOptimizationBlocker : StatementAuthorizer {
final class TruncateOptimizationBlocker: StatementAuthorizer {
func authorize(
_ actionCode: Int32,
_ cString1: UnsafePointer<Int8>?,
@@ -177,8 +181,11 @@ final class TruncateOptimizationBlocker : StatementAuthorizer {
_ cString4: UnsafePointer<Int8>?)
-> Int32
{
// print("TruncateOptimizationBlocker: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
// print("""
// TruncateOptimizationBlocker: \
// \(actionCode) \
// \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) })
// """)
return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK
}
}
+96 -21
View File
@@ -1,9 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// The StatementColumnConvertible protocol grants access to the low-level C
@@ -77,6 +77,9 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
_columnIndex = 0
}
_statement.reset(withArguments: arguments)
// Assume cursor is created for iteration
statement.database.selectStatementWillExecute(statement)
}
deinit {
@@ -109,17 +112,20 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
/// For example:
///
/// try dbQueue.read { db in
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, sql: "SELECT email FROM player")
/// let emails: FastNullableDatabaseValueCursor<String> =
/// try Optional<String>.fetchCursor(db, sql: "SELECT email FROM player")
/// while let email = emails.next() { // String?
/// print(email ?? "<NULL>")
/// }
/// }
public final class FastNullableDatabaseValueCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
public final class FastNullableDatabaseValueCursor<Value>: Cursor
where Value: DatabaseValueConvertible & StatementColumnConvertible
{
@usableFromInline let _statement: SelectStatement
@usableFromInline let _columnIndex: Int32
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline var _done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
_statement = statement
_sqliteStatement = statement.sqliteStatement
@@ -130,6 +136,9 @@ public final class FastNullableDatabaseValueCursor<Value: DatabaseValueConvertib
_columnIndex = 0
}
_statement.reset(withArguments: arguments)
// Assume cursor is created for iteration
statement.database.selectStatementWillExecute(statement)
}
deinit {
@@ -187,7 +196,12 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> {
public static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastDatabaseValueCursor<Self>
{
return try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
@@ -202,7 +216,12 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
public static func fetchAll(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
@@ -217,15 +236,23 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
public static func fetchOne(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{
// fetchOne returns nil if there is no row, or if there is a row with a null value
let cursor = try FastNullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
let cursor = try FastNullableDatabaseValueCursor<Self>(
statement: statement,
arguments: arguments,
adapter: adapter)
return try cursor.next() ?? nil
}
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// MARK: Fetching From SQL
/// Returns a cursor over values fetched from an SQL query.
@@ -247,7 +274,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> {
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> FastDatabaseValueCursor<Self>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -262,7 +295,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] {
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> [Self]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -277,7 +316,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? {
public static func fetchOne(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> Self?
{
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -304,7 +349,9 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - request: A FetchRequest.
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> FastDatabaseValueCursor<Self> {
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
throws -> FastDatabaseValueCursor<Self>
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchCursor(request.statement, adapter: request.adapter)
}
@@ -426,7 +473,12 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> {
public static func fetchCursor(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastNullableDatabaseValueCursor<Wrapped>
{
return try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
}
@@ -441,7 +493,12 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
public static func fetchAll(
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
}
@@ -469,7 +526,13 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> {
public static func fetchCursor(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> FastNullableDatabaseValueCursor<Wrapped>
{
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
@@ -484,7 +547,13 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] {
public static func fetchAll(
_ db: Database,
sql: String,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -511,7 +580,9 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - request: A FetchRequest.
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> FastNullableDatabaseValueCursor<Wrapped> {
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
throws -> FastNullableDatabaseValueCursor<Wrapped>
{
let request = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchCursor(request.statement, adapter: request.adapter)
}
@@ -532,7 +603,11 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
}
}
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
extension FetchRequest
where
RowDecoder: _OptionalProtocol,
RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible
{
// MARK: Fetching Optional values
+2 -2
View File
@@ -2,8 +2,8 @@
import CoreGraphics
/// CGFloat adopts DatabaseValueConvertible
extension CGFloat : DatabaseValueConvertible {
extension CGFloat: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return Double(self).databaseValue
+4 -4
View File
@@ -1,14 +1,14 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// Data is convertible to and from DatabaseValue.
extension Data : DatabaseValueConvertible, StatementColumnConvertible {
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
@@ -1,17 +1,17 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// DatabaseDateComponents reads and stores DateComponents in the database.
public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumnConvertible {
public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnConvertible {
/// The available formats for reading and storing date components.
public enum Format : String {
public enum Format: String {
/// The format "yyyy-MM-dd".
case YMD = "yyyy-MM-dd"
@@ -81,8 +81,10 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
}
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
let optionalComponents = cString.withMemoryRebound(to: Int8.self, capacity: length + 1 /* trailing \0 */) { cString in
SQLiteDateParser().components(cString: cString, length: length)
let optionalComponents = cString.withMemoryRebound(
to: Int8.self,
capacity: length + 1 /* trailing \0 */) { cString in
SQLiteDateParser().components(cString: cString, length: length)
}
guard let components = optionalComponents else {
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
@@ -122,7 +124,9 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn
let minute = dateComponents.minute ?? 0
let second = dateComponents.second ?? 0
let nanosecond = dateComponents.nanosecond ?? 0
timeString = String(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0)))
timeString = String(
format: "%02d:%02d:%02d.%03d",
hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0)))
default:
timeString = nil
}
@@ -26,14 +26,22 @@ extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.Refere
}
}
extension DatabaseValueConvertible where Self: Decodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
extension DatabaseValueConvertible
where
Self: Decodable & ReferenceConvertible,
Self.ReferenceType: DatabaseValueConvertible
{
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
// Preserve custom database decoding
return ReferenceType.fromDatabaseValue(databaseValue).flatMap { cast($0) }
}
}
extension DatabaseValueConvertible where Self: Encodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
extension DatabaseValueConvertible
where
Self: Encodable & ReferenceConvertible,
Self.ReferenceType: DatabaseValueConvertible
{
public var databaseValue: DatabaseValue {
// Preserve custom database encoding
return (self as! ReferenceType).databaseValue
+7 -7
View File
@@ -1,16 +1,16 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
#if !os(Linux)
/// NSDate is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension NSDate : DatabaseValueConvertible {
extension NSDate: DatabaseValueConvertible {
/// Returns a database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
public var databaseValue: DatabaseValue {
@@ -38,7 +38,7 @@ extension NSDate : DatabaseValueConvertible {
/// Date is stored in the database using the format
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
extension Date : DatabaseValueConvertible {
extension Date: DatabaseValueConvertible {
/// Returns a database value that contains the date encoded as
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
public var databaseValue: DatabaseValue {
@@ -149,7 +149,7 @@ private let storageDateFormatter: DateFormatter = {
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter
}()
}()
// The NSCalendar for stored dates.
private let UTCCalendar: Calendar = {
@@ -157,4 +157,4 @@ private let UTCCalendar: Calendar = {
calendar.locale = Locale(identifier: "en_US_POSIX")
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
return calendar
}()
}()
+1 -1
View File
@@ -2,7 +2,7 @@
import Foundation
/// NSData is convertible to and from DatabaseValue.
extension NSData : DatabaseValueConvertible {
extension NSData: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
+1 -1
View File
@@ -1,7 +1,7 @@
import Foundation
/// NSNull adopts DatabaseValueConvertible
extension NSNull : DatabaseValueConvertible {
extension NSNull: DatabaseValueConvertible {
/// Returns DatabaseValue.null.
public var databaseValue: DatabaseValue {
+14 -4
View File
@@ -1,10 +1,16 @@
#if !os(Linux)
import Foundation
private let integerRoundingBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
private let integerRoundingBehavior = NSDecimalNumberHandler(
roundingMode: .plain,
scale: 0,
raiseOnExactness: false,
raiseOnOverflow: false,
raiseOnUnderflow: false,
raiseOnDivideByZero: false)
/// NSNumber adopts DatabaseValueConvertible
extension NSNumber : DatabaseValueConvertible {
extension NSNumber: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
@@ -34,13 +40,17 @@ extension NSNumber : DatabaseValueConvertible {
return Int64(intValue).databaseValue
case "L":
let uint = uintValue
GRDBPrecondition(UInt64(uint) <= UInt64(Int64.max), "could not convert \(uint) to an Int64 that can be stored in the database")
GRDBPrecondition(
UInt64(uint) <= UInt64(Int64.max),
"could not convert \(uint) to an Int64 that can be stored in the database")
return Int64(uint).databaseValue
case "q":
return Int64(int64Value).databaseValue
case "Q":
let uint64 = uint64Value
GRDBPrecondition(uint64 <= UInt64(Int64.max), "could not convert \(uint64) to an Int64 that can be stored in the database")
GRDBPrecondition(
uint64 <= UInt64(Int64.max),
"could not convert \(uint64) to an Int64 that can be stored in the database")
return Int64(uint64).databaseValue
case "f":
return Double(floatValue).databaseValue
+1 -1
View File
@@ -2,7 +2,7 @@
import Foundation
/// NSString adopts DatabaseValueConvertible
extension NSString : DatabaseValueConvertible {
extension NSString: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
@@ -58,6 +58,7 @@ class SQLiteDateParser {
withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in
withUnsafeMutablePointer(to: &parserComponents.second) { secondP in
parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in
// swiftlint:disable:next line_length
withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in
vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%9s", pointer)
}
+2 -2
View File
@@ -2,7 +2,7 @@ import Foundation
#if !os(Linux)
/// NSURL stores its absoluteString in the database.
extension NSURL : DatabaseValueConvertible {
extension NSURL: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
/// (the URL's absoluteString).
@@ -21,4 +21,4 @@ extension NSURL : DatabaseValueConvertible {
#endif
/// URL stores its absoluteString in the database.
extension URL : DatabaseValueConvertible { }
extension URL: DatabaseValueConvertible { }
+3 -3
View File
@@ -1,10 +1,10 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
#if !os(Linux)
@@ -13,7 +13,8 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode(_ type: Bool.Type) throws -> Bool {
if let result = Bool.fromDatabaseValue(dbValue) {
@@ -131,9 +132,10 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
if let type = T.self as? DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows custom database decoding, such as decoding Date from
@@ -159,7 +161,7 @@ private struct DatabaseValueDecoder: Decoder {
// Decoder
let codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey : Any] { return [:] }
var userInfo: [CodingUserInfoKey: Any] { return [:] }
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
throw DecodingError.typeMismatch(
@@ -1,4 +1,4 @@
private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
let encode: (DatabaseValue) -> Void
var codingPath: [CodingKey] { return [] }
@@ -34,7 +34,7 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)` call.
mutating func encode<T>(_ value: T) throws where T : Encodable {
mutating func encode<T>(_ value: T) throws where T: Encodable {
if let dbValueConvertible = value as? DatabaseValueConvertible {
// Prefer DatabaseValueConvertible encoding over Decodable.
// This allows us to encode Date as String, for example.
@@ -45,7 +45,7 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
}
}
private struct DatabaseValueEncoder : Encoder {
private struct DatabaseValueEncoder: Encoder {
let encode: (DatabaseValue) -> Void
/// The path of coding keys taken to get to this point in encoding.
@@ -53,7 +53,7 @@ private struct DatabaseValueEncoder : Encoder {
var codingPath: [CodingKey] { return [] }
/// Any contextual information set by the user for encoding.
var userInfo: [CodingUserInfoKey : Any] = [:]
var userInfo: [CodingUserInfoKey: Any] = [:]
init(encode: @escaping (DatabaseValue) -> Void) {
self.encode = encode
@@ -64,7 +64,8 @@ private struct DatabaseValueEncoder : Encoder {
/// - parameter type: The key type to use for the container.
/// - returns: A new keyed encoding container.
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
/// - precondition: May not be called after a value has been encoded through
/// a previous `self.singleValueContainer()` call.
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
fatalError("keyed encoding is not supported")
}
@@ -73,7 +74,8 @@ private struct DatabaseValueEncoder : Encoder {
///
/// - returns: A new empty unkeyed container.
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
/// - precondition: May not be called after a value has been encoded through
/// a previous `self.singleValueContainer()` call.
func unkeyedContainer() -> UnkeyedEncodingContainer {
fatalError("unkeyed encoding is not supported")
}
@@ -83,7 +85,8 @@ private struct DatabaseValueEncoder : Encoder {
/// - returns: A new empty single value container.
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
/// - precondition: May not be called after a value has been encoded through
/// a previous `self.singleValueContainer()` call.
func singleValueContainer() -> SingleValueEncodingContainer {
return DatabaseValueEncodingContainer(encode: encode)
}
@@ -1,9 +1,9 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
// MARK: - Value Types
@@ -500,11 +500,12 @@ extension DatabaseFunction {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.capitalized)
/// let names = try String.fetchAll(dbQueue, request) // [String]
public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.capitalized
public static let capitalize =
DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.capitalized
}
/// An SQL function that returns the Swift built-in lowercased
@@ -519,11 +520,12 @@ extension DatabaseFunction {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.lowercased())
/// let names = try String.fetchAll(dbQueue, request) // [String]
public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.lowercased()
public static let lowercase =
DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.lowercased()
}
/// An SQL function that returns the Swift built-in uppercased
@@ -538,11 +540,12 @@ extension DatabaseFunction {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.uppercased())
/// let names = try String.fetchAll(dbQueue, request) // [String]
public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.uppercased()
public static let uppercase =
DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.uppercased()
}
}
@@ -560,11 +563,12 @@ extension DatabaseFunction {
/// let request = Player.select(nameColumn.localizedCapitalized)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedCapitalized
public static let localizedCapitalize =
DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedCapitalized
}
/// An SQL function that returns the Swift built-in
@@ -580,11 +584,12 @@ extension DatabaseFunction {
/// let request = Player.select(nameColumn.localizedLowercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedLowercase
public static let localizedLowercase =
DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedLowercase
}
/// An SQL function that returns the Swift built-in
@@ -600,11 +605,12 @@ extension DatabaseFunction {
/// let request = Player.select(nameColumn.localizedUppercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedUppercase
public static let localizedUppercase =
DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
}
return string.localizedUppercase
}
}
@@ -637,8 +643,9 @@ extension DatabaseCollation {
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let unicodeCompare = DatabaseCollation("swiftCompare") { (lhs, rhs) in
return (lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending)
public static let unicodeCompare =
DatabaseCollation("swiftCompare") { (lhs, rhs) in
(lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending)
}
/// A collation, or SQL string comparison function, that compares strings
@@ -655,8 +662,9 @@ extension DatabaseCollation {
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let caseInsensitiveCompare = DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in
return lhs.caseInsensitiveCompare(rhs)
public static let caseInsensitiveCompare =
DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in
lhs.caseInsensitiveCompare(rhs)
}
/// A collation, or SQL string comparison function, that compares strings
@@ -673,8 +681,9 @@ extension DatabaseCollation {
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let localizedCaseInsensitiveCompare = DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in
return lhs.localizedCaseInsensitiveCompare(rhs)
public static let localizedCaseInsensitiveCompare =
DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in
return lhs.localizedCaseInsensitiveCompare(rhs)
}
/// A collation, or SQL string comparison function, that compares strings
@@ -691,8 +700,9 @@ extension DatabaseCollation {
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let localizedCompare = DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in
return lhs.localizedCompare(rhs)
public static let localizedCompare =
DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in
lhs.localizedCompare(rhs)
}
/// A collation, or SQL string comparison function, that compares strings
@@ -709,7 +719,8 @@ extension DatabaseCollation {
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let localizedStandardCompare = DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in
return lhs.localizedStandardCompare(rhs)
public static let localizedStandardCompare =
DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in
lhs.localizedStandardCompare(rhs)
}
}
+353 -293
View File
@@ -1,13 +1,13 @@
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
extension Database {
// MARK: - Database Observation
/// Add a transaction observer, so that it gets notified of
@@ -17,7 +17,10 @@ extension Database {
/// - parameter extent: The duration of the observation. The default is
/// the observer lifetime (observation lasts until observer
/// is deallocated).
public func add(transactionObserver: TransactionObserver, extent: TransactionObservationExtent = .observerLifetime) {
public func add(
transactionObserver: TransactionObserver,
extent: TransactionObservationExtent = .observerLifetime)
{
SchedulingWatchdog.preconditionValidQueue(self)
observationBroker.add(transactionObserver: transactionObserver, extent: extent)
}
@@ -42,11 +45,11 @@ extension Database {
///
/// If the transaction is committed, the closure is executed in a protected
/// dispatch queue, serialized will all database updates.
public func afterNextTransactionCommit(_ closure: @escaping (Database) -> ()) {
class CommitHandler : TransactionObserver {
let closure: (Database) -> ()
public func afterNextTransactionCommit(_ closure: @escaping (Database) -> Void) {
class CommitHandler: TransactionObserver {
let closure: (Database) -> Void
init(_ closure: @escaping (Database) -> ()) {
init(_ closure: @escaping (Database) -> Void) {
self.closure = closure
}
@@ -195,7 +198,7 @@ class DatabaseObservationBroker {
}
func disableUntilNextTransaction(transactionObserver: TransactionObserver) {
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver)}) {
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) {
observation.isDisabled = true
statementObservations.removeFirst { $0.0 === observation }
}
@@ -203,7 +206,10 @@ class DatabaseObservationBroker {
// MARK: - Statement execution
func updateStatementWillExecute(_ statement: UpdateStatement) {
/// Setups observation of changes that are about to be performed by the
/// statement, and returns the authorizer that should be used during
/// statement execution.
func updateStatementWillExecute(_ statement: UpdateStatement) -> StatementAuthorizer? {
// As statement executes, it may trigger database changes that will
// be notified to transaction observers. As a consequence, observers
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
@@ -282,18 +288,17 @@ class DatabaseObservationBroker {
}
if observesRowDeletion {
database.authorizer = TruncateOptimizationBlocker()
return TruncateOptimizationBlocker()
} else {
database.authorizer = nil
return nil
}
}
func updateStatementDidFail(_ statement: UpdateStatement) throws {
// Undo updateStatementWillExecute
statementObservations = []
database.authorizer = nil
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Reset transactionState before databaseDidRollback eventually
// executes other statements.
let transactionState = self.transactionState
@@ -316,9 +321,8 @@ class DatabaseObservationBroker {
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
// Undo updateStatementWillExecute
statementObservations = []
database.authorizer = nil
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Has statement any effect on transaction/savepoints?
if let transactionEffect = statement.transactionEffect {
switch transactionEffect {
@@ -379,7 +383,7 @@ class DatabaseObservationBroker {
}
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
#if SQLITE_ENABLE_PREUPDATE_HOOK
// Called from sqlite3_preupdate_hook
private func databaseWillChange(with event: DatabasePreUpdateEvent) {
if savepointStack.isEmpty {
@@ -392,7 +396,7 @@ class DatabaseObservationBroker {
savepointStack.eventsBuffer.append((event: event.copy(), statementObservations: statementObservations))
}
}
#endif
#endif
// Called from sqlite3_update_hook
private func databaseDidChange(with event: DatabaseEvent) {
@@ -597,17 +601,23 @@ class DatabaseObservationBroker {
private func installUpdateHook() {
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
sqlite3_update_hook(database.sqliteConnection, { (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
broker.databaseDidChange(with: DatabaseEvent(
kind: DatabaseEvent.Kind(rawValue: updateKind)!,
rowID: rowID,
databaseNameCString: databaseNameCString,
tableNameCString: tableNameCString))
}, brokerPointer)
sqlite3_update_hook(
database.sqliteConnection,
{ (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
broker.databaseDidChange(with: DatabaseEvent(
kind: DatabaseEvent.Kind(rawValue: updateKind)!,
rowID: rowID,
databaseNameCString: databaseNameCString,
tableNameCString: tableNameCString))
},
brokerPointer)
#if SQLITE_ENABLE_PREUPDATE_HOOK
sqlite3_preupdate_hook(database.sqliteConnection, { (brokerPointer, databaseConnection, updateKind, databaseNameCString, tableNameCString, initialRowID, finalRowID) in
sqlite3_preupdate_hook(
database.sqliteConnection,
// swiftlint:disable:next line_length
{ (brokerPointer, databaseConnection, updateKind, databaseNameCString, tableNameCString, initialRowID, finalRowID) in
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
broker.databaseWillChange(with: DatabasePreUpdateEvent(
connection: databaseConnection!,
@@ -616,14 +626,15 @@ class DatabaseObservationBroker {
finalRowID: finalRowID,
databaseNameCString: databaseNameCString,
tableNameCString: tableNameCString))
}, brokerPointer)
},
brokerPointer)
#endif
}
private func uninstallUpdateHook() {
sqlite3_update_hook(database.sqliteConnection, nil, nil)
#if SQLITE_ENABLE_PREUPDATE_HOOK
sqlite3_preupdate_hook(database.sqliteConnection, nil, nil)
sqlite3_preupdate_hook(database.sqliteConnection, nil, nil)
#endif
}
@@ -642,7 +653,7 @@ class DatabaseObservationBroker {
/// or rollbacked on a database.
///
/// Adopting types must be a class.
public protocol TransactionObserver : class {
public protocol TransactionObserver: AnyObject {
/// Filters database changes that should be notified the the
/// databaseDidChange(with:) method.
@@ -713,7 +724,8 @@ public protocol TransactionObserver : class {
///
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
/// does not have this enabled, so you'll need to compile your own
/// copy using GRDBCustomSQLite. See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md
/// copy using GRDBCustomSQLite.
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md
///
/// The databaseDidChangeWithEvent callback is always available,
/// and may provide most/all of what you need.
@@ -726,13 +738,13 @@ extension TransactionObserver {
/// Default implementation does nothing
public func databaseWillCommit() throws {
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
/// Default implementation does nothing
public func databaseWillChange(with event: DatabasePreUpdateEvent) {
}
#endif
/// After this method has been called, the `databaseDidChange(with:)`
/// method won't be called until the next transaction.
///
@@ -756,7 +768,10 @@ extension TransactionObserver {
/// - precondition: This method must be called from `databaseDidChange(with:)`.
public func stopObservingDatabaseChangesUntilNextTransaction() {
guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else {
fatalError("stopObservingDatabaseChangesUntilNextTransaction must be called from the databaseDidChange method")
fatalError("""
stopObservingDatabaseChangesUntilNextTransaction must be called \
from the databaseDidChange method
""")
}
broker.disableUntilNextTransaction(transactionObserver: self)
}
@@ -801,23 +816,23 @@ final class TransactionObservation {
if isDisabled { return false }
return observer?.observes(eventsOfKind: eventKind) ?? false
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
func databaseWillChange(with event: DatabasePreUpdateEvent) {
if isDisabled { return }
observer?.databaseWillChange(with: event)
}
#endif
func databaseDidChange(with event: DatabaseEvent) {
if isDisabled { return }
observer?.databaseDidChange(with: event)
}
func databaseWillCommit() throws {
try observer?.databaseWillCommit()
}
func databaseDidCommit(_ db: Database) {
switch extent {
case .observerLifetime, .databaseLifetime:
@@ -867,11 +882,11 @@ public enum DatabaseEventKind {
var modifiedRegion: DatabaseRegion {
switch self {
case .delete(let tableName):
case let .delete(tableName):
return DatabaseRegion(table: tableName)
case .insert(let tableName):
case let .insert(tableName):
return DatabaseRegion(table: tableName)
case .update(let tableName, let updatedColumnNames):
case let .update(tableName, updatedColumnNames):
return DatabaseRegion(table: tableName, columns: updatedColumnNames)
}
}
@@ -881,9 +896,9 @@ extension DatabaseEventKind {
/// The impacted database table
public var tableName: String {
switch self {
case .insert(tableName: let tableName): return tableName
case .delete(tableName: let tableName): return tableName
case .update(tableName: let tableName, columnNames: _): return tableName
case let .insert(tableName: tableName): return tableName
case let .delete(tableName: tableName): return tableName
case let .update(tableName: tableName, columnNames: _): return tableName
}
}
}
@@ -915,7 +930,7 @@ public struct DatabaseEvent {
/// The database name
public var databaseName: String { return impl.databaseName }
/// The table name
public var tableName: String { return impl.tableName }
@@ -941,11 +956,16 @@ public struct DatabaseEvent {
}
init(kind: Kind, rowID: Int64, databaseNameCString: UnsafePointer<Int8>?, tableNameCString: UnsafePointer<Int8>?) {
self.init(kind: kind, rowID: rowID, impl: MetalDatabaseEventImpl(databaseNameCString: databaseNameCString, tableNameCString: tableNameCString))
self.init(
kind: kind,
rowID: rowID,
impl: MetalDatabaseEventImpl(
databaseNameCString: databaseNameCString,
tableNameCString: tableNameCString))
}
}
extension DatabaseEvent : DatabaseEventProtocol {
extension DatabaseEvent: DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseDidChange(with: self)
}
@@ -970,19 +990,25 @@ private protocol DatabaseEventImpl {
/// Optimization: MetalDatabaseEventImpl does not create Swift strings from raw
/// SQLite char* until actually asked for databaseName or tableName.
private struct MetalDatabaseEventImpl : DatabaseEventImpl {
private struct MetalDatabaseEventImpl: DatabaseEventImpl {
let databaseNameCString: UnsafePointer<Int8>?
let tableNameCString: UnsafePointer<Int8>?
var databaseName: String { return String(cString: databaseNameCString!) }
var tableName: String { return String(cString: tableNameCString!) }
func copy(_ event: DatabaseEvent) -> DatabaseEvent {
return DatabaseEvent(kind: event.kind, rowID: event.rowID, impl: CopiedDatabaseEventImpl(databaseName: databaseName, tableName: tableName))
return DatabaseEvent(
kind: event.kind,
rowID: event.rowID,
impl: CopiedDatabaseEventImpl(
databaseName: databaseName,
tableName: tableName))
}
}
/// Impl for DatabaseEvent that contains copies of event strings.
private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
let databaseName: String
let tableName: String
func copy(_ event: DatabaseEvent) -> DatabaseEvent {
@@ -992,258 +1018,293 @@ private struct CopiedDatabaseEventImpl : DatabaseEventImpl {
#if SQLITE_ENABLE_PREUPDATE_HOOK
public struct DatabasePreUpdateEvent {
public struct DatabasePreUpdateEvent {
/// An event kind
public enum Kind: Int32 {
/// SQLITE_INSERT
case insert = 18
/// An event kind
public enum Kind: Int32 {
/// SQLITE_INSERT
case insert = 18
/// SQLITE_DELETE
case delete = 9
/// SQLITE_UPDATE
case update = 23
}
/// SQLITE_DELETE
case delete = 9
/// The event kind
public let kind: Kind
/// The database name
public var databaseName: String { return impl.databaseName }
/// The table name
public var tableName: String { return impl.tableName }
/// The number of columns in the row that is being inserted, updated, or deleted.
public var count: Int { return Int(impl.columnsCount) }
/// The triggering depth of the row update
/// Returns:
/// 0 if the preupdate callback was invoked as a result of a direct insert,
// update, or delete operation;
/// 1 for inserts, updates, or deletes invoked by top-level triggers;
/// 2 for changes resulting from triggers called by top-level triggers;
/// ... and so forth
public var depth: CInt { return impl.depth }
/// The initial rowID of the row being changed for .Update and .Delete changes,
/// and nil for .Insert changes.
public let initialRowID: Int64?
/// The final rowID of the row being changed for .Update and .Insert changes,
/// and nil for .Delete changes.
public let finalRowID: Int64?
/// The initial database values in the row.
///
/// Values appear in the same order as the columns in the table.
///
/// The result is nil if the event is an .Insert event.
public var initialDatabaseValues: [DatabaseValue]? {
guard (kind == .update || kind == .delete) else { return nil }
return impl.initialDatabaseValues
}
/// Returns the initial `DatabaseValue` at given index.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// The result is nil if the event is an .Insert event.
public func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
guard (kind == .update || kind == .delete) else { return nil }
return impl.initialDatabaseValue(atIndex: index)
}
/// The final database values in the row.
///
/// Values appear in the same order as the columns in the table.
///
/// The result is nil if the event is a .Delete event.
public var finalDatabaseValues: [DatabaseValue]? {
guard (kind == .update || kind == .insert) else { return nil }
return impl.finalDatabaseValues
}
/// Returns the final `DatabaseValue` at given index.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// The result is nil if the event is a .Delete event.
public func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
guard (kind == .update || kind == .insert) else { return nil }
return impl.finalDatabaseValue(atIndex: index)
}
/// Returns an event that can be stored:
///
/// class MyObserver: TransactionObserver {
/// var events: [DatabasePreUpdateEvent]
/// func databaseWillChange(with event: DatabasePreUpdateEvent) {
/// events.append(event.copy())
/// }
/// }
public func copy() -> DatabasePreUpdateEvent {
return impl.copy(self)
}
fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) {
self.kind = kind
self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil
self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil
self.impl = impl
}
init(connection: SQLiteConnection, kind: Kind, initialRowID: Int64, finalRowID: Int64, databaseNameCString: UnsafePointer<Int8>?, tableNameCString: UnsafePointer<Int8>?) {
self.init(kind: kind,
initialRowID: (kind == .update || kind == .delete ) ? finalRowID : nil,
finalRowID: (kind == .update || kind == .insert ) ? finalRowID : nil,
impl: MetalDatabasePreUpdateEventImpl(connection: connection, kind: kind, databaseNameCString: databaseNameCString, tableNameCString: tableNameCString))
}
private let impl: DatabasePreUpdateEventImpl
/// SQLITE_UPDATE
case update = 23
}
extension DatabasePreUpdateEvent : DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseWillChange(with: self)
}
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool {
switch (kind, databaseEventKind) {
case (.insert, .insert(let tableName)): return self.tableName == tableName
case (.delete, .delete(let tableName)): return self.tableName == tableName
case (.update, .update(let tableName, _)): return self.tableName == tableName
default:
return false
}
}
/// The event kind
public let kind: Kind
/// The database name
public var databaseName: String { return impl.databaseName }
/// The table name
public var tableName: String { return impl.tableName }
/// The number of columns in the row that is being inserted, updated, or deleted.
public var count: Int { return Int(impl.columnsCount) }
/// The triggering depth of the row update
/// Returns:
/// 0 if the preupdate callback was invoked as a result of a direct insert,
// update, or delete operation;
/// 1 for inserts, updates, or deletes invoked by top-level triggers;
/// 2 for changes resulting from triggers called by top-level triggers;
/// ... and so forth
public var depth: CInt { return impl.depth }
/// The initial rowID of the row being changed for .Update and .Delete changes,
/// and nil for .Insert changes.
public let initialRowID: Int64?
/// The final rowID of the row being changed for .Update and .Insert changes,
/// and nil for .Delete changes.
public let finalRowID: Int64?
/// The initial database values in the row.
///
/// Values appear in the same order as the columns in the table.
///
/// The result is nil if the event is an .Insert event.
public var initialDatabaseValues: [DatabaseValue]? {
guard kind == .update || kind == .delete else { return nil }
return impl.initialDatabaseValues
}
/// Protocol for internal implementation of DatabaseEvent
private protocol DatabasePreUpdateEventImpl {
var databaseName: String { get }
var tableName: String { get }
var columnsCount: CInt { get }
var depth: CInt { get }
var initialDatabaseValues: [DatabaseValue]? { get }
var finalDatabaseValues: [DatabaseValue]? { get }
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue?
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue?
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent
/// Returns the initial `DatabaseValue` at given index.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// The result is nil if the event is an .Insert event.
public func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
guard kind == .update || kind == .delete else { return nil }
return impl.initialDatabaseValue(atIndex: index)
}
/// Optimization: MetalDatabasePreUpdateEventImpl does not create Swift strings from raw
/// SQLite char* until actually asked for databaseName or tableName,
/// nor does it request other data via the sqlite3_preupdate_* APIs
/// until asked.
private struct MetalDatabasePreUpdateEventImpl : DatabasePreUpdateEventImpl {
let connection: SQLiteConnection
let kind: DatabasePreUpdateEvent.Kind
let databaseNameCString: UnsafePointer<Int8>?
let tableNameCString: UnsafePointer<Int8>?
var databaseName: String { return String(cString: databaseNameCString!) }
var tableName: String { return String(cString: tableNameCString!) }
var columnsCount: CInt { return sqlite3_preupdate_count(connection) }
var depth: CInt { return sqlite3_preupdate_depth(connection) }
var initialDatabaseValues: [DatabaseValue]? {
guard (kind == .update || kind == .delete) else { return nil }
return preupdate_getValues_old(connection)
}
var finalDatabaseValues: [DatabaseValue]? {
guard (kind == .update || kind == .insert) else { return nil }
return preupdate_getValues_new(connection)
}
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? {
let columnCount = columnsCount
precondition(index >= 0 && index < Int(columnCount), "row index out of range")
return getValue(connection, column: CInt(index), sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
return sqlite3_preupdate_old(connection, column, &value)
})
}
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? {
let columnCount = columnsCount
precondition(index >= 0 && index < Int(columnCount), "row index out of range")
return getValue(connection, column: CInt(index), sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
return sqlite3_preupdate_new(connection, column, &value)
})
}
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent {
return DatabasePreUpdateEvent(kind: event.kind, initialRowID: event.initialRowID, finalRowID: event.finalRowID, impl: CopiedDatabasePreUpdateEventImpl(
databaseName: databaseName,
tableName: tableName,
columnsCount: columnsCount,
depth: depth,
initialDatabaseValues: initialDatabaseValues,
finalDatabaseValues: finalDatabaseValues))
}
private func preupdate_getValues(_ connection: SQLiteConnection, sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt ) -> [DatabaseValue]? {
let columnCount = sqlite3_preupdate_count(connection)
guard columnCount > 0 else { return nil }
var columnValues = [DatabaseValue]()
for i in 0..<columnCount {
let value = getValue(connection, column: i, sqlite_func: sqlite_func)!
columnValues.append(value)
}
return columnValues
}
private func getValue(_ connection: SQLiteConnection, column: CInt, sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt ) -> DatabaseValue? {
var value : SQLiteValue? = nil
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
if let value = value {
return DatabaseValue(sqliteValue: value)
}
return nil
}
private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? {
return preupdate_getValues(connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
return sqlite3_preupdate_old(connection, column, &value)
})
}
private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? {
return preupdate_getValues(connection, sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
return sqlite3_preupdate_new(connection, column, &value)
})
}
/// The final database values in the row.
///
/// Values appear in the same order as the columns in the table.
///
/// The result is nil if the event is a .Delete event.
public var finalDatabaseValues: [DatabaseValue]? {
guard kind == .update || kind == .insert else { return nil }
return impl.finalDatabaseValues
}
/// Impl for DatabasePreUpdateEvent that contains copies of all event data.
private struct CopiedDatabasePreUpdateEventImpl : DatabasePreUpdateEventImpl {
let databaseName: String
let tableName: String
let columnsCount: CInt
let depth: CInt
let initialDatabaseValues: [DatabaseValue]?
let finalDatabaseValues: [DatabaseValue]?
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { return initialDatabaseValues?[index] }
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { return finalDatabaseValues?[index] }
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent {
return event
/// Returns the final `DatabaseValue` at given index.
///
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
///
/// The result is nil if the event is a .Delete event.
public func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? {
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
guard kind == .update || kind == .insert else { return nil }
return impl.finalDatabaseValue(atIndex: index)
}
/// Returns an event that can be stored:
///
/// class MyObserver: TransactionObserver {
/// var events: [DatabasePreUpdateEvent]
/// func databaseWillChange(with event: DatabasePreUpdateEvent) {
/// events.append(event.copy())
/// }
/// }
public func copy() -> DatabasePreUpdateEvent {
return impl.copy(self)
}
fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) {
self.kind = kind
self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil
self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil
self.impl = impl
}
init(
connection: SQLiteConnection,
kind: Kind,
initialRowID: Int64,
finalRowID: Int64,
databaseNameCString: UnsafePointer<Int8>?,
tableNameCString: UnsafePointer<Int8>?)
{
self.init(
kind: kind,
initialRowID: (kind == .update || kind == .delete ) ? finalRowID : nil,
finalRowID: (kind == .update || kind == .insert ) ? finalRowID : nil,
impl: MetalDatabasePreUpdateEventImpl(
connection: connection,
kind: kind,
databaseNameCString: databaseNameCString,
tableNameCString: tableNameCString))
}
private let impl: DatabasePreUpdateEventImpl
}
extension DatabasePreUpdateEvent: DatabaseEventProtocol {
func send(to observer: TransactionObservation) {
observer.databaseWillChange(with: self)
}
func matchesKind(_ databaseEventKind: DatabaseEventKind) -> Bool {
switch (kind, databaseEventKind) {
case (.insert, .insert(let tableName)): return self.tableName == tableName
case (.delete, .delete(let tableName)): return self.tableName == tableName
case (.update, .update(let tableName, _)): return self.tableName == tableName
default:
return false
}
}
}
/// Protocol for internal implementation of DatabaseEvent
private protocol DatabasePreUpdateEventImpl {
var databaseName: String { get }
var tableName: String { get }
var columnsCount: CInt { get }
var depth: CInt { get }
var initialDatabaseValues: [DatabaseValue]? { get }
var finalDatabaseValues: [DatabaseValue]? { get }
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue?
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue?
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent
}
/// Optimization: MetalDatabasePreUpdateEventImpl does not create Swift strings from raw
/// SQLite char* until actually asked for databaseName or tableName,
/// nor does it request other data via the sqlite3_preupdate_* APIs
/// until asked.
private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
let connection: SQLiteConnection
let kind: DatabasePreUpdateEvent.Kind
let databaseNameCString: UnsafePointer<Int8>?
let tableNameCString: UnsafePointer<Int8>?
var databaseName: String { return String(cString: databaseNameCString!) }
var tableName: String { return String(cString: tableNameCString!) }
var columnsCount: CInt { return sqlite3_preupdate_count(connection) }
var depth: CInt { return sqlite3_preupdate_depth(connection) }
var initialDatabaseValues: [DatabaseValue]? {
guard kind == .update || kind == .delete else { return nil }
return preupdate_getValues_old(connection)
}
var finalDatabaseValues: [DatabaseValue]? {
guard kind == .update || kind == .insert else { return nil }
return preupdate_getValues_new(connection)
}
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? {
let columnCount = columnsCount
precondition(index >= 0 && index < Int(columnCount), "row index out of range")
return getValue(
connection,
column: CInt(index),
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
sqlite3_preupdate_old(connection, column, &value)
})
}
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? {
let columnCount = columnsCount
precondition(index >= 0 && index < Int(columnCount), "row index out of range")
return getValue(
connection,
column: CInt(index),
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
sqlite3_preupdate_new(connection, column, &value)
})
}
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent {
return DatabasePreUpdateEvent(
kind: event.kind,
initialRowID: event.initialRowID,
finalRowID: event.finalRowID,
impl: CopiedDatabasePreUpdateEventImpl(
databaseName: databaseName,
tableName: tableName,
columnsCount: columnsCount,
depth: depth,
initialDatabaseValues: initialDatabaseValues,
finalDatabaseValues: finalDatabaseValues))
}
private func preupdate_getValues(
_ connection: SQLiteConnection,
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
-> [DatabaseValue]?
{
let columnCount = sqlite3_preupdate_count(connection)
guard columnCount > 0 else { return nil }
var columnValues = [DatabaseValue]()
for i in 0..<columnCount {
let value = getValue(connection, column: i, sqlite_func: sqlite_func)!
columnValues.append(value)
}
return columnValues
}
private func getValue(
_ connection: SQLiteConnection,
column: CInt,
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
-> DatabaseValue?
{
var value: SQLiteValue? = nil
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
if let value = value {
return DatabaseValue(sqliteValue: value)
}
return nil
}
private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? {
return preupdate_getValues(
connection,
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
sqlite3_preupdate_old(connection, column, &value)
})
}
private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? {
return preupdate_getValues(
connection,
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
sqlite3_preupdate_new(connection, column, &value)
})
}
}
/// Impl for DatabasePreUpdateEvent that contains copies of all event data.
private struct CopiedDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
let databaseName: String
let tableName: String
let columnsCount: CInt
let depth: CInt
let initialDatabaseValues: [DatabaseValue]?
let finalDatabaseValues: [DatabaseValue]?
func initialDatabaseValue(atIndex index: Int) -> DatabaseValue? { return initialDatabaseValues?[index] }
func finalDatabaseValue(atIndex index: Int) -> DatabaseValue? { return finalDatabaseValues?[index] }
func copy(_ event: DatabasePreUpdateEvent) -> DatabasePreUpdateEvent {
return event
}
}
#endif
@@ -1330,4 +1391,3 @@ class SavepointStack {
}
}
}
+5 -2
View File
@@ -4,7 +4,7 @@
/// try db.create(virtualTable: "document", using: FTS3()) { t in
/// t.column("content")
/// }
public struct FTS3 : VirtualTableModule {
public struct FTS3: VirtualTableModule {
/// Options for Latin script characters. Matches the raw "remove_diacritics"
/// tokenizer argument.
///
@@ -55,7 +55,10 @@ public struct FTS3 : VirtualTableModule {
if tokenizer.arguments.isEmpty {
arguments.append("tokenize=\(tokenizer.name)")
} else {
arguments.append("tokenize=\(tokenizer.name) " + tokenizer.arguments.map { "\"\($0)\"" as String }.joined(separator: " "))
arguments.append(
"tokenize=\(tokenizer.name) " + tokenizer.arguments
.map { "\"\($0)\"" as String }
.joined(separator: " "))
}
}
return arguments
+2 -2
View File
@@ -24,7 +24,7 @@ public struct FTS3Pattern {
}
} catch let error as DatabaseError {
// Remove private SQL & arguments from the thrown error
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil)
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message)
}
// Pattern is valid
@@ -115,7 +115,7 @@ public struct FTS3Pattern {
#endif
}
extension FTS3Pattern : DatabaseValueConvertible {
extension FTS3Pattern: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return rawPattern.databaseValue
+34 -11
View File
@@ -48,7 +48,12 @@ public struct FTS3TokenizerDescriptor {
/// these characters as token characters.
///
/// See https://www.sqlite.org/fts3.html#tokenizer
public static func unicode61(diacritics: FTS3.Diacritics = .removeLegacy, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
public static func unicode61(
diacritics: FTS3.Diacritics = .removeLegacy,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{
return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters)
}
#else
@@ -68,14 +73,25 @@ public struct FTS3TokenizerDescriptor {
///
/// See https://www.sqlite.org/fts3.html#tokenizer
@available(OSX 10.10, *)
public static func unicode61(diacritics: FTS3.Diacritics = .removeLegacy, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
public static func unicode61(
diacritics: FTS3.Diacritics = .removeLegacy,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters)
}
#endif
private static func _unicode61(diacritics: FTS3.Diacritics, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
private static func _unicode61(
diacritics: FTS3.Diacritics,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{
var arguments: [String] = []
switch diacritics {
case .removeLegacy:
@@ -88,12 +104,16 @@ public struct FTS3TokenizerDescriptor {
#endif
}
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
arguments.append("separators=" + separators.sorted().map { String($0) }.joined(separator: ""))
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
arguments.append("separators=" + separators.sorted().map { String($0) }.joined())
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined(separator: ""))
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined())
}
return FTS3TokenizerDescriptor("unicode61", arguments: arguments)
}
@@ -108,13 +128,14 @@ public struct FTS3TokenizerDescriptor {
return _tokenize(string)
}
#endif
/// Returns an array of tokens found in the string argument.
///
/// FTS3TokenizerDescriptor.simple.tokenize("foo bar") // ["foo", "bar"]
private func _tokenize(_ string: String) -> [String] {
// fts3tokenize was introduced in SQLite 3.7.17 https://www.sqlite.org/changes.html#version_3_7_17
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
return DatabaseQueue().inDatabase { db in
var tokenizerChunks: [String] = []
tokenizerChunks.append(name)
@@ -124,7 +145,9 @@ public struct FTS3TokenizerDescriptor {
let tokenizerSQL = tokenizerChunks.joined(separator: ", ")
// Assume fts3tokenize virtual table in an in-memory database always succeeds
try! db.execute(sql: "CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))")
return try! String.fetchAll(db, sql: "SELECT token FROM tokens WHERE input = ? ORDER BY position", arguments: [string])
return try! String.fetchAll(db, sql: """
SELECT token FROM tokens WHERE input = ? ORDER BY position
""", arguments: [string])
}
}
}
+9 -4
View File
@@ -6,7 +6,7 @@
/// }
///
/// See https://www.sqlite.org/fts3.html
public struct FTS4 : VirtualTableModule {
public struct FTS4: VirtualTableModule {
/// Creates a FTS4 module suitable for the Database
/// `create(virtualTable:using:)` method.
@@ -53,7 +53,10 @@ public struct FTS4 : VirtualTableModule {
if tokenizer.arguments.isEmpty {
arguments.append("tokenize=\(tokenizer.name)")
} else {
arguments.append("tokenize=\(tokenizer.name) " + tokenizer.arguments.map { "\"\($0)\"" as String }.joined(separator: " "))
arguments.append(
"tokenize=\(tokenizer.name) " + tokenizer.arguments
.map { "\"\($0)\"" as String }
.joined(separator: " "))
}
}
@@ -273,7 +276,8 @@ public final class FTS4ColumnDefinition {
@discardableResult
public func notIndexed() -> Self {
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
self.isIndexed = false
return self
}
@@ -292,7 +296,8 @@ public final class FTS4ColumnDefinition {
@discardableResult
public func notIndexed() -> Self {
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
self.isIndexed = false
return self
}
+32 -18
View File
@@ -1,10 +1,11 @@
#if SQLITE_ENABLE_FTS5
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// FTS5 lets you define "fts5" virtual tables.
@@ -15,7 +16,7 @@
/// }
///
/// See https://www.sqlite.org/fts5.html
public struct FTS5 : VirtualTableModule {
public struct FTS5: VirtualTableModule {
/// Options for Latin script characters. Matches the raw "remove_diacritics"
/// tokenizer argument.
///
@@ -34,7 +35,7 @@ public struct FTS5 : VirtualTableModule {
case remove
#endif
}
/// Creates a FTS5 module suitable for the Database
/// `create(virtualTable:using:)` method.
///
@@ -75,30 +76,41 @@ public struct FTS5 : VirtualTableModule {
}
if let tokenizer = definition.tokenizer {
arguments.append("tokenize=\(tokenizer.components.joined(separator: " ").sqlExpression.quotedSQL(wrappedInParenthesis: false))")
let tokenizerSQL = tokenizer
.components
.joined(separator: " ")
.sqlExpression
.quotedSQL()
arguments.append("tokenize=\(tokenizerSQL)")
}
switch definition.contentMode {
case .raw(let content, let contentRowID):
case let .raw(content, contentRowID):
if let content = content {
let quotedContent = content.sqlExpression.quotedSQL(wrappedInParenthesis: false)
let quotedContent = content.sqlExpression.quotedSQL()
arguments.append("content=\(quotedContent)")
}
if let contentRowID = contentRowID {
let quotedContentRowID = contentRowID.sqlExpression.quotedSQL(wrappedInParenthesis: false)
let quotedContentRowID = contentRowID.sqlExpression.quotedSQL()
arguments.append("content_rowid=\(quotedContentRowID)")
}
case .synchronized(let contentTable):
arguments.append("content=\(contentTable.sqlExpression.quotedSQL(wrappedInParenthesis: false))")
case let .synchronized(contentTable):
arguments.append("content=\(contentTable.sqlExpression.quotedSQL())")
if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn {
let quotedRowID = rowIDColumn.sqlExpression.quotedSQL(wrappedInParenthesis: false)
let quotedRowID = rowIDColumn.sqlExpression.quotedSQL()
arguments.append("content_rowid=\(quotedRowID)")
}
}
if let prefixes = definition.prefixes {
arguments.append("prefix=\(prefixes.sorted().map { "\($0)" }.joined(separator: " ").sqlExpression.quotedSQL(wrappedInParenthesis: false))")
let prefix = prefixes
.sorted()
.map { "\($0)" }
.joined(separator: " ")
.sqlExpression
.quotedSQL()
arguments.append("prefix=\(prefix)")
}
if let columnSize = definition.columnSize {
@@ -141,14 +153,14 @@ public struct FTS5 : VirtualTableModule {
try db.execute(sql: """
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
END;
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
""")
@@ -190,7 +202,7 @@ public struct FTS5 : VirtualTableModule {
}
#if swift(>=5.0)
return data.withUnsafeBytes {
$0.bindMemory(to: UnsafePointer<fts5_api>.self).first!
$0.bindMemory(to: UnsafePointer<fts5_api>.self).first!
}
#else
return data.withUnsafeBytes {
@@ -203,7 +215,9 @@ public struct FTS5 : VirtualTableModule {
// https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4
private static func api_v2(
_ db: Database,
// swiftlint:disable:next line_length
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, Int32, UInt32, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> Int32,
// swiftlint:disable:next line_length
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32)
-> UnsafePointer<fts5_api>
{
+40 -11
View File
@@ -1,14 +1,14 @@
#if SQLITE_ENABLE_FTS5
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// The protocol for custom FTS5 tokenizers.
public protocol FTS5CustomTokenizer : FTS5Tokenizer {
public protocol FTS5CustomTokenizer: FTS5Tokenizer {
/// The name of the tokenizer; should uniquely identify your custom
/// tokenizer.
static var name: String { get }
@@ -41,7 +41,6 @@ extension FTS5CustomTokenizer {
public static func tokenizerDescriptor(arguments: [String] = []) -> FTS5TokenizerDescriptor {
return FTS5TokenizerDescriptor(components: [name] + arguments)
}
}
extension Database {
@@ -52,7 +51,10 @@ extension Database {
let db: Database
let constructor: (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> Int32
init(db: Database, constructor: @escaping (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> Int32) {
init(
db: Database,
constructor: @escaping (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> Int32)
{
self.db = db
self.constructor = constructor
}
@@ -101,7 +103,13 @@ extension Database {
Unmanaged<AnyObject>.fromOpaque(constructorPointer).release()
}
func xCreateTokenizer(constructorPointer: UnsafeMutableRawPointer?, azArg: UnsafeMutablePointer<UnsafePointer<Int8>?>?, nArg: Int32, tokenizerHandle: UnsafeMutablePointer<OpaquePointer?>?) -> Int32 {
func xCreateTokenizer(
constructorPointer: UnsafeMutableRawPointer?,
azArg: UnsafeMutablePointer<UnsafePointer<Int8>?>?,
nArg: Int32,
tokenizerHandle: UnsafeMutablePointer<OpaquePointer?>?)
-> Int32
{
guard let constructorPointer = constructorPointer else {
return SQLITE_ERROR
}
@@ -122,20 +130,41 @@ extension Database {
Unmanaged<AnyObject>.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).release()
}
func xTokenize(tokenizerPointer: OpaquePointer?, context: UnsafeMutableRawPointer?, flags: Int32, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer<Int8>?, Int32, Int32, Int32) -> Int32)?) -> Int32 {
func xTokenize(
tokenizerPointer: OpaquePointer?,
context: UnsafeMutableRawPointer?,
flags: Int32,
pText: UnsafePointer<Int8>?,
nText: Int32,
// swiftlint:disable:next line_length
tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer<Int8>?, Int32, Int32, Int32) -> Int32)?)
-> Int32
{
guard let tokenizerPointer = tokenizerPointer else {
return SQLITE_ERROR
}
let object = Unmanaged<AnyObject>.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).takeUnretainedValue()
let object = Unmanaged<AnyObject>
.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer))
.takeUnretainedValue()
guard let tokenizer = object as? FTS5Tokenizer else {
return SQLITE_ERROR
}
return tokenizer.tokenize(context: context, tokenization: FTS5Tokenization(rawValue: flags), pText: pText, nText: nText, tokenCallback: tokenCallback!)
return tokenizer.tokenize(
context: context,
tokenization: FTS5Tokenization(rawValue: flags),
pText: pText,
nText: nText,
tokenCallback: tokenCallback!)
}
var xTokenizer = fts5_tokenizer(xCreate: xCreateTokenizer, xDelete: xDeleteTokenizer, xTokenize: xTokenize)
let code = withUnsafeMutablePointer(to: &xTokenizer) { xTokenizerPointer in
api.pointee.xCreateTokenizer(UnsafeMutablePointer(mutating: api), Tokenizer.name, constructorPointer, xTokenizerPointer, deleteConstructor)
api.pointee.xCreateTokenizer(
UnsafeMutablePointer(mutating: api),
Tokenizer.name,
constructorPointer,
xTokenizerPointer,
deleteConstructor)
}
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
+34 -6
View File
@@ -13,7 +13,14 @@ public struct FTS5Pattern {
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingAnyTokenIn string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard
let tokens = try? DatabaseQueue().inDatabase({ db in
try db
.makeTokenizer(.ascii())
.nonSynonymTokens(in: string, for: .query) })
else {
return nil
}
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " OR "))
}
@@ -26,7 +33,14 @@ public struct FTS5Pattern {
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingAllTokensIn string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard
let tokens = try? DatabaseQueue().inDatabase({ db in
try db
.makeTokenizer(.ascii())
.nonSynonymTokens(in: string, for: .query) })
else {
return nil
}
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " "))
}
@@ -39,7 +53,14 @@ public struct FTS5Pattern {
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingPhrase string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard
let tokens = try? DatabaseQueue().inDatabase({ db in
try db
.makeTokenizer(.ascii())
.nonSynonymTokens(in: string, for: .query) })
else {
return nil
}
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
@@ -52,7 +73,14 @@ public struct FTS5Pattern {
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingPrefixPhrase string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard
let tokens = try? DatabaseQueue().inDatabase({ db in
try db
.makeTokenizer(.ascii())
.nonSynonymTokens(in: string, for: .query) })
else {
return nil
}
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"")
}
@@ -80,7 +108,7 @@ public struct FTS5Pattern {
}
} catch let error as DatabaseError {
// Remove private SQL & arguments from the thrown error
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil)
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message)
}
// Pattern is valid
@@ -104,7 +132,7 @@ extension Database {
}
}
extension FTS5Pattern : DatabaseValueConvertible {
extension FTS5Pattern: DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return rawPattern.databaseValue
+73 -25
View File
@@ -1,21 +1,29 @@
#if SQLITE_ENABLE_FTS5
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// A low-level SQLite function that lets FTS5Tokenizer notify tokens.
///
/// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:)
public typealias FTS5TokenCallback = @convention(c) (_ context: UnsafeMutableRawPointer?, _ flags: Int32, _ pToken: UnsafePointer<Int8>?, _ nToken: Int32, _ iStart: Int32, _ iEnd: Int32) -> Int32
public typealias FTS5TokenCallback = @convention(c) (
_ context: UnsafeMutableRawPointer?,
_ flags: Int32,
_ pToken: UnsafePointer<Int8>?,
_ nToken: Int32,
_ iStart: Int32,
_ iEnd: Int32)
-> Int32
/// The reason why FTS5 is requesting tokenization.
///
/// See https://www.sqlite.org/fts5.html#custom_tokenizers
public struct FTS5Tokenization : OptionSet {
public struct FTS5Tokenization: OptionSet {
public let rawValue: Int32
public init(rawValue: Int32) {
@@ -36,7 +44,7 @@ public struct FTS5Tokenization : OptionSet {
}
/// The protocol for FTS5 tokenizers
public protocol FTS5Tokenizer : class {
public protocol FTS5Tokenizer: AnyObject {
/// Tokenizes the text described by `pText` and `nText`, and
/// notifies found tokens to the `tokenCallback` function.
///
@@ -51,7 +59,13 @@ public protocol FTS5Tokenizer : class {
/// - nText: The number of bytes in the tokenized text.
/// - tokenCallback: The function to call for each found token.
/// It matches the `xToken` callback at https://www.sqlite.org/fts5.html#custom_tokenizers
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32
func tokenize(
context: UnsafeMutableRawPointer?,
tokenization: FTS5Tokenization,
pText: UnsafePointer<Int8>?,
nText: Int32,
tokenCallback: @escaping FTS5TokenCallback)
-> Int32
}
private class TokenizeContext {
@@ -81,20 +95,34 @@ extension FTS5Tokenizer {
var context = TokenizeContext()
try withUnsafeMutablePointer(to: &context) { contextPointer in
let code = tokenize(context: UnsafeMutableRawPointer(contextPointer), tokenization: tokenization, pText: pText, nText: nText, tokenCallback: { (contextPointer, flags, pToken, nToken, iStart, iEnd) -> Int32 in
guard let contextPointer = contextPointer else { return SQLITE_ERROR }
// Extract token
guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else {
let code = tokenize(
context: UnsafeMutableRawPointer(contextPointer),
tokenization: tokenization,
pText: pText,
nText: nText,
tokenCallback: { (contextPointer, flags, pToken, nToken, _ /* iStart */, _ /* iEnd */) -> Int32 in
guard let contextPointer = contextPointer else {
return SQLITE_ERROR
}
// Extract token
guard
let token = pToken.flatMap({
String(
data: Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: $0),
count: Int(nToken),
deallocator: .none),
encoding: .utf8) })
else {
return SQLITE_OK
}
let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee
context.tokens.append((token, FTS5TokenFlags(rawValue: flags)))
return SQLITE_OK
}
let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee
context.tokens.append((token, FTS5TokenFlags(rawValue: flags)))
return SQLITE_OK
})
if (code != SQLITE_OK) {
if code != SQLITE_OK {
throw DatabaseError(resultCode: code)
}
}
@@ -119,13 +147,13 @@ extension Database {
/// Private type that makes a pre-registered FTS5 tokenizer available
/// through the FTS5Tokenizer protocol.
private final class FTS5RegisteredTokenizer : FTS5Tokenizer {
private final class FTS5RegisteredTokenizer: FTS5Tokenizer {
let xTokenizer: fts5_tokenizer
let tokenizerPointer: OpaquePointer
init(xTokenizer: fts5_tokenizer, contextPointer: UnsafeMutableRawPointer?, arguments: [String]) throws {
guard let xCreate = xTokenizer.xCreate else {
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate")
throw DatabaseError(message: "nil fts5_tokenizer.xCreate")
}
self.xTokenizer = xTokenizer
@@ -135,7 +163,13 @@ extension Database {
if let argument = arguments.first {
// Turn [String] into ContiguousArray<UnsafePointer<Int8>>
// (for an alternative implementation see https://oleb.net/blog/2016/10/swift-array-of-c-strings/)
func convertArguments<Result>(_ array: inout ContiguousArray<UnsafePointer<Int8>>, _ car: String, _ cdr: [String], _ body: (ContiguousArray<UnsafePointer<Int8>>) -> Result) -> Result {
func convertArguments<Result>(
_ array: inout ContiguousArray<UnsafePointer<Int8>>,
_ car: String,
_ cdr: [String],
_ body: (ContiguousArray<UnsafePointer<Int8>>) -> Result)
-> Result
{
return car.withCString { cString in
if let car = cdr.first {
array.append(cString)
@@ -148,7 +182,11 @@ extension Database {
var cStrings = ContiguousArray<UnsafePointer<Int8>>()
code = convertArguments(&cStrings, argument, Array(arguments.suffix(from: 1))) { cStrings in
cStrings.withUnsafeBufferPointer { azArg in
xCreate(contextPointer, UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), Int32(cStrings.count), &tokenizerPointer)
xCreate(
contextPointer,
UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)),
Int32(cStrings.count),
&tokenizerPointer)
}
}
} else {
@@ -172,7 +210,14 @@ extension Database {
}
}
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 {
func tokenize(
context: UnsafeMutableRawPointer?,
tokenization: FTS5Tokenization,
pText: UnsafePointer<Int8>?,
nText: Int32,
tokenCallback: @escaping FTS5TokenCallback)
-> Int32
{
guard let xTokenize = xTokenizer.xTokenize else {
return SQLITE_ERROR
}
@@ -216,7 +261,10 @@ extension Database {
}
let contextPointer = contextHandle.pointee
return try FTS5RegisteredTokenizer(xTokenizer: xTokenizerPointer.pointee, contextPointer: contextPointer, arguments: descriptor.arguments)
return try FTS5RegisteredTokenizer(
xTokenizer: xTokenizerPointer.pointee,
contextPointer: contextPointer,
arguments: descriptor.arguments)
}
}
#endif
+29 -9
View File
@@ -57,11 +57,20 @@ public struct FTS5TokenizerDescriptor {
///
/// See https://www.sqlite.org/fts5.html#ascii_tokenizer
public static func ascii(separators: Set<Character> = []) -> FTS5TokenizerDescriptor {
let components: [String]
if separators.isEmpty {
return FTS5TokenizerDescriptor(components: ["ascii"])
components = ["ascii"]
} else {
return FTS5TokenizerDescriptor(components: ["ascii", "separators", separators.map { String($0) }.joined(separator: "").sqlExpression.quotedSQL(wrappedInParenthesis: false)])
components = [
"ascii",
"separators",
separators
.map { String($0) }
.joined()
.sqlExpression
.quotedSQL()]
}
return FTS5TokenizerDescriptor(components: components)
}
/// The "porter" tokenizer
@@ -98,7 +107,12 @@ public struct FTS5TokenizerDescriptor {
/// consider these characters as token characters.
///
/// See https://www.sqlite.org/fts5.html#unicode61_tokenizer
public static func unicode61(diacritics: FTS5.Diacritics = .removeLegacy, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS5TokenizerDescriptor {
public static func unicode61(
diacritics: FTS5.Diacritics = .removeLegacy,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS5TokenizerDescriptor
{
var components: [String] = ["unicode61"]
switch diacritics {
case .removeLegacy:
@@ -111,26 +125,32 @@ public struct FTS5TokenizerDescriptor {
#endif
}
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
components.append(contentsOf: [
"separators",
separators
.sorted()
.map { String($0) }
.joined(separator: "")
.joined()
.sqlExpression
.quotedSQL(wrappedInParenthesis: false)])
.quotedSQL()
])
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
components.append(contentsOf: [
"tokenchars",
tokenCharacters
.sorted()
.map { String($0) }
.joined(separator: "")
.joined()
.sqlExpression
.quotedSQL(wrappedInParenthesis: false)])
.quotedSQL()
])
}
return FTS5TokenizerDescriptor(components: components)
}
+90 -52
View File
@@ -1,16 +1,17 @@
#if SQLITE_ENABLE_FTS5
import Foundation
#if SWIFT_PACKAGE
import CSQLite
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
import SQLite3
#endif
/// Flags that tell SQLite how to register a token.
///
/// See https://www.sqlite.org/fts5.html#custom_tokenizers
public struct FTS5TokenFlags : OptionSet {
public struct FTS5TokenFlags: OptionSet {
public let rawValue: Int32
public init(rawValue: Int32) {
@@ -24,7 +25,7 @@ public struct FTS5TokenFlags : OptionSet {
/// A function that lets FTS5WrapperTokenizer notify tokens.
///
/// See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:)
public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> ()
public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> Void
/// The protocol for custom FTS5 tokenizers that wrap another tokenizer.
///
@@ -44,11 +45,17 @@ public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5Token
/// wrappedTokenizer = try db.makeTokenizer(.ascii())
/// }
///
/// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
/// func accept(
/// token: String,
/// flags: FTS5TokenFlags,
/// for tokenization: FTS5Tokenization,
/// tokenCallback: FTS5WrapperTokenCallback)
/// throws
/// {
/// try tokenCallback(token, flags)
/// }
/// }
public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer {
/// The wrapped tokenizer
var wrappedTokenizer: FTS5Tokenizer { get }
@@ -57,7 +64,13 @@ public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
///
/// For example:
///
/// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
/// func accept(
/// token: String,
/// flags: FTS5TokenFlags,
/// for tokenization: FTS5Tokenization,
/// tokenCallback: FTS5WrapperTokenCallback)
/// throws
/// {
/// // pass through:
/// try tokenCallback(token, flags)
/// }
@@ -77,7 +90,12 @@ public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
/// - flags: Flags that tell SQLite how to register a token.
/// - tokenization: The reason why FTS5 is requesting tokenization.
/// - tokenCallback: The function to call for each customized token.
func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws
func accept(
token: String,
flags: FTS5TokenFlags,
for tokenization: FTS5Tokenization,
tokenCallback: FTS5WrapperTokenCallback)
throws
}
private struct FTS5WrapperContext {
@@ -89,7 +107,14 @@ private struct FTS5WrapperContext {
extension FTS5WrapperTokenizer {
/// Default implementation
public func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 {
public func tokenize(
context: UnsafeMutableRawPointer?,
tokenization: FTS5Tokenization,
pText: UnsafePointer<Int8>?,
nText: Int32,
tokenCallback: @escaping FTS5TokenCallback)
-> Int32
{
// `tokenCallback` is @convention(c). This requires a little setup
// in order to transfer context.
var customContext = FTS5WrapperContext(
@@ -99,49 +124,62 @@ extension FTS5WrapperTokenizer {
tokenCallback: tokenCallback)
return withUnsafeMutablePointer(to: &customContext) { customContextPointer in
// Invoke wrappedTokenizer
return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in
// Extract token produced by wrapped tokenizer
guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else {
return 0 // SQLITE_OK
}
// Extract context
let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee
let tokenizer = customContext.tokenizer
let context = customContext.context
let tokenization = customContext.tokenization
let tokenCallback = customContext.tokenCallback
// Process token produced by wrapped tokenizer
do {
try tokenizer.accept(
token: token,
flags: FTS5TokenFlags(rawValue: tokenFlags),
for: tokenization,
tokenCallback: { (token, flags) in
// Turn token into bytes
return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in
guard let addr = buffer.baseAddress else {
return
}
let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self)
let nToken = Int32(buffer.count)
// Inject token bytes into SQLite
let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: "token callback failed")
}
}
})
return wrappedTokenizer.tokenize(
context: customContextPointer,
tokenization: tokenization,
pText: pText,
nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in
return SQLITE_OK
} catch let error as DatabaseError {
return error.extendedResultCode.rawValue
} catch {
return SQLITE_ERROR
}
// Extract token produced by wrapped tokenizer
guard
let token = pToken.flatMap({
String(
data: Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: $0),
count: Int(nToken),
deallocator: .none),
encoding: .utf8) })
else {
return SQLITE_OK // 0 // SQLITE_OK
}
// Extract context
let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee
let tokenizer = customContext.tokenizer
let context = customContext.context
let tokenization = customContext.tokenization
let tokenCallback = customContext.tokenCallback
// Process token produced by wrapped tokenizer
do {
try tokenizer.accept(
token: token,
flags: FTS5TokenFlags(rawValue: tokenFlags),
for: tokenization,
tokenCallback: { (token, flags) in
// Turn token into bytes
return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in
guard let addr = buffer.baseAddress else {
return
}
let pToken = UnsafeMutableRawPointer(mutating: addr)
.assumingMemoryBound(to: Int8.self)
let nToken = Int32(buffer.count)
// Inject token bytes into SQLite
let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: "token callback failed")
}
}
})
return SQLITE_OK
} catch let error as DatabaseError {
return error.extendedResultCode.rawValue
} catch {
return SQLITE_ERROR
}
}
}
}
+138 -24
View File
@@ -4,7 +4,10 @@ import Dispatch
extension Cursor {
@available(*, unavailable, renamed: "compactMap")
public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> { preconditionFailure() }
public func flatMap<ElementOfResult>(
_ transform: @escaping (Element) throws -> ElementOfResult?)
-> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
{ preconditionFailure() }
}
extension DatabaseWriter {
@@ -14,17 +17,26 @@ extension DatabaseWriter {
extension ValueObservation {
@available(*, unavailable, message: "Provide the reducer in a (Database) -> Reducer closure")
public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation { preconditionFailure() }
public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer)
-> ValueObservation
{ preconditionFailure() }
@available(*, unavailable, message: "Use removeDuplicates() instead")
public static func tracking<Value>(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (Database) throws -> Value) -> ValueObservation<ValueReducers.RemoveDuplicates<ValueReducers.Fetch<Value>>> where Value: Equatable { preconditionFailure() }
public static func tracking<Value>(
_ regions: DatabaseRegionConvertible...,
fetchDistinct fetch: @escaping (Database) throws -> Value)
-> ValueObservation<ValueReducers.RemoveDuplicates<ValueReducers.Fetch<Value>>>
where Value: Equatable
{ preconditionFailure() }
}
@available(*, unavailable, renamed: "FastDatabaseValueCursor")
public typealias ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastDatabaseValueCursor<Value>
public typealias ColumnCursor<Value> = FastDatabaseValueCursor<Value>
where Value: DatabaseValueConvertible & StatementColumnConvertible
@available(*, unavailable, renamed: "FastNullableDatabaseValueCursor")
public typealias NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastNullableDatabaseValueCursor<Value>
public typealias NullableColumnCursor<Value> = FastNullableDatabaseValueCursor<Value>
where Value: DatabaseValueConvertible & StatementColumnConvertible
extension Database {
@available(*, unavailable, renamed: "execute(sql:arguments:)")
@@ -45,58 +57,141 @@ extension Database {
extension DatabaseValueConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> { preconditionFailure() }
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> DatabaseValueCursor<Self>
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { preconditionFailure() }
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { preconditionFailure() }
public static func fetchOne(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{ preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> { preconditionFailure() }
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> NullableDatabaseValueCursor<Wrapped>
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { preconditionFailure() }
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
{ preconditionFailure() }
}
extension Row {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor { preconditionFailure() }
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> RowCursor
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { preconditionFailure() }
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Row]
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { preconditionFailure() }
public static func fetchOne(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Row?
{ preconditionFailure() }
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> { preconditionFailure() }
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastDatabaseValueCursor<Self>
{ preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> { preconditionFailure() }
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastNullableDatabaseValueCursor<Wrapped>
{ preconditionFailure() }
}
extension FetchableRecord {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> { preconditionFailure() }
public static func fetchCursor(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> RecordCursor<Self>
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { preconditionFailure() }
public static func fetchAll(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
{ preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { preconditionFailure() }
public static func fetchOne(
_ db: Database,
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
{ preconditionFailure() }
}
extension SQLRequest {
@available(*, unavailable, renamed: "init(sql:arguments:adapter:cached:)")
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) { preconditionFailure() }
public init(
_ sql: String,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil,
cached: Bool = false)
{ preconditionFailure() }
}
extension SQLExpressionLiteral {
@@ -111,30 +206,49 @@ extension SQLExpression {
extension FTS3TokenizerDescriptor {
@available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)")
public static func unicode61(removeDiacritics: Bool, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor { preconditionFailure() }
public static func unicode61(
removeDiacritics: Bool,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS3TokenizerDescriptor
{ preconditionFailure() }
}
#if SQLITE_ENABLE_FTS5
extension FTS5TokenizerDescriptor {
@available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)")
public static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS5TokenizerDescriptor { preconditionFailure() }
public static func unicode61(
removeDiacritics: Bool = true,
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
-> FTS5TokenizerDescriptor
{ preconditionFailure() }
}
#endif
extension DatabaseValue {
@available(*, unavailable)
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T: DatabaseValueConvertible { preconditionFailure() }
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil)
-> T
where T: DatabaseValueConvertible
{ preconditionFailure() }
@available(*, unavailable)
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T: DatabaseValueConvertible { preconditionFailure() }
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil)
-> T?
where T: DatabaseValueConvertible
{ preconditionFailure() }
}
extension ValueScheduling {
@available(*, unavailable, renamed: "async(onQueue:startImmediately:)")
public static func onQueue(_ queue: DispatchQueue, startImmediately: Bool) -> ValueScheduling { preconditionFailure() }
public static func onQueue(_ queue: DispatchQueue, startImmediately: Bool)
-> ValueScheduling
{ preconditionFailure() }
}
extension ValueObservation {
// swiftlint:disable:next line_length
@available(*, unavailable, message: "Observation extent is controlled by the lifetime of observers returned by the start() method.")
public var extent: Database.TransactionObservationExtent {
get { preconditionFailure() }
+67 -55
View File
@@ -68,7 +68,7 @@ public struct DatabaseMigrator {
/// for some downloaded data.
public var eraseDatabaseOnSchemaChange = false
private var migrations: [Migration] = []
/// A new migrator.
public init() {
}
@@ -92,58 +92,64 @@ public struct DatabaseMigrator {
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
/// try db.create(table: "new_player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// }
/// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
/// try db.drop(table: "player")
/// try db.rename(table: "new_player", to: "player")
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
///
/// :nodoc:
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
/// try db.create(table: "new_player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// }
/// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
/// try db.drop(table: "player")
/// try db.rename(table: "new_player", to: "player")
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
///
/// :nodoc:
public mutating func registerMigrationWithDeferredForeignKeyCheck(
_ identifier: String,
migrate: @escaping (Database) throws -> Void)
{
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
#else
@available(OSX 10.10, *)
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
/// try db.create(table: "new_player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// }
/// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
/// try db.drop(table: "player")
/// try db.rename(table: "new_player", to: "player")
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigrationWithDeferredForeignKeyCheck(_ identifier: String, migrate: @escaping (Database) throws -> Void) {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
@available(OSX 10.10, *)
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
/// try db.create(table: "new_player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// }
/// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
/// try db.drop(table: "player")
/// try db.rename(table: "new_player", to: "player")
/// }
///
/// While your migration code runs with disabled foreign key checks, those
/// are re-enabled and checked at the end of the migration, regardless of
/// eventual errors.
///
/// - parameters:
/// - identifier: The migration identifier.
/// - block: The migration block that performs SQL statements.
/// - precondition: No migration with the same same as already been registered.
public mutating func registerMigrationWithDeferredForeignKeyCheck(
_ identifier: String,
migrate: @escaping (Database) throws -> Void)
{
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
#endif
/// Iterate migrations in the same order as they were registered. If a
@@ -232,7 +238,9 @@ public struct DatabaseMigrator {
// MARK: - Non public
private mutating func registerMigration(_ migration: Migration) {
GRDBPrecondition(!migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \(String(reflecting: migration.identifier))")
GRDBPrecondition(
!migrations.map({ $0.identifier }).contains(migration.identifier),
"already registered migration: \(String(reflecting: migration.identifier))")
migrations.append(migration)
}
@@ -254,13 +262,17 @@ public struct DatabaseMigrator {
}
// targetIdentifier must refer to a registered migration
GRDBPrecondition(prefixMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))")
GRDBPrecondition(
prefixMigrations.last?.identifier == targetIdentifier,
"undefined migration: \(String(reflecting: targetIdentifier))")
// Subsequent migration must not be applied
let appliedIdentifiers = try self.appliedIdentifiers(db)
if prefixMigrations.count < migrations.count {
let nextIdentifier = migrations[prefixMigrations.count].identifier
GRDBPrecondition(!appliedIdentifiers.contains(nextIdentifier), "database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
GRDBPrecondition(
!appliedIdentifiers.contains(nextIdentifier),
"database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
}
for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) {
+20 -18
View File
@@ -5,26 +5,27 @@ struct Migration {
let migrate: (Database) throws -> Void
#if GRDBCUSTOMSQLITE || GRDBCIPHER
init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = disabledForeignKeyChecks
self.migrate = migrate
}
init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = disabledForeignKeyChecks
self.migrate = migrate
}
#else
init(identifier: String, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = false
self.migrate = migrate
}
init(identifier: String, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = false
self.migrate = migrate
}
@available(OSX 10.10, *)
// PRAGMA foreign_key_check was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = disabledForeignKeyChecks
self.migrate = migrate
}
@available(OSX 10.10, *)
// PRAGMA foreign_key_check was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) {
self.identifier = identifier
self.disabledForeignKeyChecks = disabledForeignKeyChecks
self.migrate = migrate
}
#endif
func run(_ db: Database) throws {
@@ -75,6 +76,7 @@ struct Migration {
return .commit
}
// TODO: we should restore foreign_keys in case of error as well
// > 12. If foreign keys constraints were originally enabled, reenable them now.
try db.execute(sql: "PRAGMA foreign_keys = ON")
}
@@ -1,4 +1,4 @@
extension QueryInterfaceRequest {
extension TableRequest where Self: FilteredRequest {
// MARK: Full Text Search
@@ -11,7 +11,7 @@ extension QueryInterfaceRequest {
///
/// If the search pattern is nil, the request does not match any
/// database row.
public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<T> {
public func matching(_ pattern: FTS3Pattern?) -> Self {
guard let pattern = pattern else {
return none()
}
+39 -39
View File
@@ -1,44 +1,44 @@
#if SQLITE_ENABLE_FTS5
extension QueryInterfaceRequest {
// MARK: Full Text Search
/// Creates a request with a full-text predicate added to the eventual
/// set of already applied predicates.
///
/// // SELECT * FROM book WHERE book MATCH '...'
/// var request = Book.all()
/// request = request.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<T> {
guard let pattern = pattern else {
return none()
}
let alias = TableAlias()
let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue)
return self.aliased(alias).filter(matchExpression)
}
}
extension TableRequest where Self: FilteredRequest {
extension TableRecord {
// MARK: Full Text Search
/// Returns a QueryInterfaceRequest with a matching predicate.
///
/// // SELECT * FROM book WHERE book MATCH '...'
/// var request = Book.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<Self> {
return all().matching(pattern)
// MARK: Full Text Search
/// Creates a request with a full-text predicate added to the eventual
/// set of already applied predicates.
///
/// // SELECT * FROM book WHERE book MATCH '...'
/// var request = Book.all()
/// request = request.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public func matching(_ pattern: FTS5Pattern?) -> Self {
guard let pattern = pattern else {
return none()
}
let alias = TableAlias()
let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue)
return self.aliased(alias).filter(matchExpression)
}
}
extension TableRecord {
// MARK: Full Text Search
/// Returns a QueryInterfaceRequest with a matching predicate.
///
/// // SELECT * FROM book WHERE book MATCH '...'
/// var request = Book.matching(pattern)
///
/// If the search pattern is nil, the request does not match any
/// database row.
public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<Self> {
return all().matching(pattern)
}
}
#endif
@@ -18,7 +18,7 @@ public protocol Association: DerivableRequest {
/// // BelongsToAssociation<Book, Author>
/// static let author = belongsTo(Author.self)
/// }
associatedtype OriginRowDecoder
associatedtype OriginRowDecoder: TableRecord
/// :nodoc:
var sqlAssociation: SQLAssociation { get }
@@ -72,12 +72,12 @@ extension Association {
extension Association {
private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self {
return Self.init(sqlAssociation: sqlAssociation.mapDestinationRelation(transform))
return .init(sqlAssociation: sqlAssociation.mapDestinationRelation(transform))
}
}
extension Association {
/// The association key defines how rows fetched from this association
/// should be consumed.
///
@@ -290,8 +290,8 @@ extension Association {
}
}
// Allow association.filter(key: ...)
extension Association where Self: TableRequest, RowDecoder: TableRecord {
// TableRequest
extension Association {
/// :nodoc:
public var databaseTableName: String { return RowDecoder.databaseTableName }
}
@@ -306,7 +306,7 @@ public protocol AssociationToOne: Association { }
extension AssociationToOne {
public func forKey(_ key: String) -> Self {
let associationKey = SQLAssociationKey.fixedSingular(key)
return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
}
}
@@ -320,11 +320,11 @@ public protocol AssociationToMany: Association { }
extension AssociationToMany {
public func forKey(_ key: String) -> Self {
let associationKey = SQLAssociationKey.fixedPlural(key)
return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
}
}
extension AssociationToMany where OriginRowDecoder: TableRecord {
extension AssociationToMany {
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<OriginRowDecoder> {
return AssociationAggregate { request in
let tableAlias = TableAlias()
@@ -353,7 +353,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord {
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
public var count: AssociationAggregate<OriginRowDecoder> {
return makeAggregate(SQLExpressionCountDistinct(Column.rowID))
.aliased("\(key.singularizedName)Count")
.forKey("\(key.singularizedName)Count")
}
/// Creates an aggregate that is true if there exists no associated records.
@@ -373,7 +373,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord {
/// let teams: [Team] = try Team.having(Team.players.isEmpty() == false)
public var isEmpty: AssociationAggregate<OriginRowDecoder> {
return makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID)))
.aliased("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
.forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
}
/// Creates an aggregate which evaluate to the average value of the given
@@ -397,7 +397,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord {
let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.aliased("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
@@ -424,7 +424,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord {
let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.aliased("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
@@ -451,7 +451,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord {
let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.aliased("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
@@ -478,7 +478,7 @@ extension AssociationToMany where OriginRowDecoder: TableRecord {
let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.aliased("\(name)\(column.name.uppercasingFirstCharacter)Sum")
return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum")
} else {
return aggregate
}
@@ -1,5 +1,9 @@
import Foundation
typealias AssociationAggregatePreparation<RowDecoder> =
(QueryInterfaceRequest<RowDecoder>)
-> (request: QueryInterfaceRequest<RowDecoder>, expression: SQLExpression)
/// An AssociationAggregate is able to compute aggregated values from a
/// population of associated records.
///
@@ -56,12 +60,12 @@ public struct AssociationAggregate<RowDecoder> {
/// - We don't know yet if the aggregated value will be used in the
/// SQL selection, or in the HAVING clause.
/// - It helps implementing aggregate operators such as `&&`, `+`, etc.
let prepare: (QueryInterfaceRequest<RowDecoder>) -> (request: QueryInterfaceRequest<RowDecoder>, expression: SQLExpression)
let prepare: AssociationAggregatePreparation<RowDecoder>
/// The SQL alias for the value of this aggregate. See aliased(_:).
var alias: String?
/// The SQL name for the value of this aggregate. See forKey(_:).
var key: String?
init(_ prepare: @escaping (QueryInterfaceRequest<RowDecoder>) -> (request: QueryInterfaceRequest<RowDecoder>, expression: SQLExpression)) {
init(_ prepare: @escaping AssociationAggregatePreparation<RowDecoder>) {
self.prepare = prepare
}
}
@@ -71,14 +75,28 @@ extension AssociationAggregate {
///
/// For example:
///
/// let aggregate = Author.books.count.aliased("foo")
/// let aggregate = Author.books.count.aliased("numberOfBooks")
/// let request = Author.annotated(with: aggregate)
/// if let row = try Row.fetchOne(db, request) {
/// let bookCount: Int = row["foo"]
/// let numberOfBooks: Int = row["numberOfBooks"]
/// }
@available(*, deprecated, renamed: "forKey(_:)")
public func aliased(_ name: String) -> AssociationAggregate<RowDecoder> {
return forKey(name)
}
/// Returns an aggregate that is selected in a column with the given name.
///
/// For example:
///
/// let aggregate = Author.books.count.forKey("numberOfBooks")
/// let request = Author.annotated(with: aggregate)
/// if let row = try Row.fetchOne(db, request) {
/// let numberOfBooks: Int = row["numberOfBooks"]
/// }
public func forKey(_ key: String) -> AssociationAggregate<RowDecoder> {
var aggregate = self
aggregate.alias = name
aggregate.key = key
return aggregate
}
@@ -89,16 +107,36 @@ extension AssociationAggregate {
///
/// struct AuthorInfo: Decodable, FetchableRecord {
/// var author: Author
/// var bookCount: Int
/// var numberOfBooks: Int
///
/// static func fetchAll(_ db: Database) throws -> [AuthorInfo] {
/// let aggregate = Author.books.count.aliased(CodingKeys.bookCount)
/// let aggregate = Author.books.count.aliased(CodingKeys.numberOfBooks)
/// let request = Author.annotated(with: aggregate)
/// return try AuthorInfo.fetchAll(db, request)
/// }
/// }
@available(*, deprecated, renamed: "forKey(_:)")
public func aliased(_ key: CodingKey) -> AssociationAggregate<RowDecoder> {
return aliased(key.stringValue)
return forKey(key)
}
/// Returns an aggregate that is selected in a column named like the given
/// coding key.
///
/// For example:
///
/// struct AuthorInfo: Decodable, FetchableRecord {
/// var author: Author
/// var numberOfBooks: Int
///
/// static func fetchAll(_ db: Database) throws -> [AuthorInfo] {
/// let aggregate = Author.books.count.forKey(CodingKeys.numberOfBooks)
/// let request = Author.annotated(with: aggregate)
/// return try AuthorInfo.fetchAll(db, request)
/// }
/// }
public func forKey(_ key: CodingKey) -> AssociationAggregate<RowDecoder> {
return forKey(key.stringValue)
}
}
@@ -121,7 +159,11 @@ public prefix func ! <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -
/// For example:
///
/// Author.having(Author.books.isEmpty && Author.paintings.isEmpty)
public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func && <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -131,7 +173,11 @@ public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
// TODO: test
/// :nodoc:
public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func && <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression && rhs)
@@ -140,7 +186,11 @@ public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
// TODO: test
/// :nodoc:
public func && <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func && <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs && expression)
@@ -153,7 +203,11 @@ public func && <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDe
/// For example:
///
/// Author.having(!Author.books.isEmpty || !Author.paintings.isEmpty)
public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func || <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -163,7 +217,11 @@ public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
// TODO: test
/// :nodoc:
public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func || <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression || rhs)
@@ -172,7 +230,11 @@ public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
// TODO: test
/// :nodoc:
public func || <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func || <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs || expression)
@@ -186,7 +248,11 @@ public func || <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDe
/// For example:
///
/// Author.having(Author.books.count == Author.paintings.count)
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func == <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -199,7 +265,11 @@ public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
/// For example:
///
/// Author.having(Author.books.count == 3)
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func == <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression == rhs)
@@ -211,7 +281,11 @@ public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
/// For example:
///
/// Author.having(3 == Author.books.count)
public func == <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func == <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs == expression)
@@ -247,7 +321,11 @@ public func == <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) ->
/// For example:
///
/// Author.having(Author.books.count != Author.paintings.count)
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func != <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -260,7 +338,11 @@ public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
/// For example:
///
/// Author.having(Author.books.count != 3)
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func != <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression != rhs)
@@ -272,7 +354,11 @@ public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
/// For example:
///
/// Author.having(3 != Author.books.count)
public func != <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func != <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs != expression)
@@ -308,7 +394,11 @@ public func != <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) ->
/// For example:
///
/// Author.having(Author.books.count === Author.paintings.count)
public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func === <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -321,7 +411,11 @@ public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associa
/// For example:
///
/// Author.having(Author.books.count === 3)
public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func === <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression === rhs)
@@ -333,7 +427,11 @@ public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpr
/// For example:
///
/// Author.having(3 === Author.books.count)
public func === <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func === <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs === expression)
@@ -345,7 +443,11 @@ public func === <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowD
/// For example:
///
/// Author.having(Author.books.count !== Author.paintings.count)
public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func !== <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -358,7 +460,11 @@ public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associa
/// For example:
///
/// Author.having(Author.books.count !== 3)
public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func !== <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression !== rhs)
@@ -370,7 +476,11 @@ public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpr
/// For example:
///
/// Author.having(3 !== Author.books.count)
public func !== <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func !== <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs !== expression)
@@ -384,7 +494,11 @@ public func !== <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowD
/// For example:
///
/// Author.having(Author.books.count <= Author.paintings.count)
public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func <= <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -397,7 +511,11 @@ public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
/// For example:
///
/// Author.having(Author.books.count <= 3)
public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func <= <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression <= rhs)
@@ -409,7 +527,11 @@ public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
/// For example:
///
/// Author.having(3 <= Author.books.count)
public func <= <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func <= <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs <= expression)
@@ -421,7 +543,11 @@ public func <= <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDe
/// For example:
///
/// Author.having(Author.books.count < Author.paintings.count)
public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func < <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -434,7 +560,11 @@ public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
/// For example:
///
/// Author.having(Author.books.count < 3)
public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func < <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression < rhs)
@@ -446,7 +576,11 @@ public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
/// For example:
///
/// Author.having(3 < Author.books.count)
public func < <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func < <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs < expression)
@@ -458,7 +592,11 @@ public func < <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
/// For example:
///
/// Author.having(Author.books.count > Author.paintings.count)
public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func > <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -471,7 +609,11 @@ public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
/// For example:
///
/// Author.having(Author.books.count > 3)
public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func > <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression > rhs)
@@ -483,7 +625,11 @@ public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
/// For example:
///
/// Author.having(3 > Author.books.count)
public func > <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func > <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs > expression)
@@ -495,7 +641,11 @@ public func > <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
/// For example:
///
/// Author.having(Author.books.count >= Author.paintings.count)
public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func >= <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -508,7 +658,11 @@ public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
/// For example:
///
/// Author.having(Author.books.count >= 3)
public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func >= <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression >= rhs)
@@ -520,7 +674,11 @@ public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
/// For example:
///
/// Author.having(3 >= Author.books.count)
public func >= <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func >= <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs >= expression)
@@ -546,7 +704,11 @@ public prefix func - <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -
/// For example:
///
/// Author.annotated(with: Author.books.count + Author.paintings.count)
public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func + <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -559,7 +721,11 @@ public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
/// For example:
///
/// Author.annotated(with: Author.books.count + 1)
public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func + <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression + rhs)
@@ -571,7 +737,11 @@ public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
/// For example:
///
/// Author.annotated(with: 1 + Author.books.count)
public func + <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func + <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs + expression)
@@ -583,7 +753,11 @@ public func + <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
/// For example:
///
/// Author.annotated(with: Author.books.count - Author.paintings.count)
public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func - <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -596,7 +770,11 @@ public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
/// For example:
///
/// Author.annotated(with: Author.books.count - 1)
public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func - <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression - rhs)
@@ -608,7 +786,11 @@ public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
/// For example:
///
/// Author.annotated(with: 1 - Author.books.count)
public func - <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func - <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs - expression)
@@ -620,7 +802,11 @@ public func - <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
/// For example:
///
/// Author.annotated(with: Author.books.count * Author.paintings.count)
public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func * <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -633,7 +819,11 @@ public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
/// For example:
///
/// Author.annotated(with: Author.books.count * 2)
public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func * <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression * rhs)
@@ -645,7 +835,11 @@ public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
/// For example:
///
/// Author.annotated(with: 2 * Author.books.count)
public func * <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func * <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs * expression)
@@ -657,7 +851,11 @@ public func * <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
/// For example:
///
/// Author.annotated(with: Author.books.count / Author.paintings.count)
public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func / <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
let (request, rExpression) = rhs.prepare(lRequest)
@@ -670,7 +868,11 @@ public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
/// For example:
///
/// Author.annotated(with: Author.books.count / 2)
public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func / <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression / rhs)
@@ -682,7 +884,11 @@ public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
/// For example:
///
/// Author.annotated(with: 2 / Author.books.count)
public func / <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
public func / <RowDecoder>(
lhs: SQLExpressible,
rhs: AssociationAggregate<RowDecoder>)
-> AssociationAggregate<RowDecoder>
{
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
return (request: request, expression: lhs / expression)
@@ -694,14 +900,18 @@ public func / <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
/// Returns an aggregate that evaluates the `IFNULL` SQL function.
///
/// Team.annotated(with: Team.players.min(Column("score")) ?? 0)
public func ?? <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
public func ?? <RowDecoder>(
lhs: AssociationAggregate<RowDecoder>,
rhs: SQLExpressible)
-> AssociationAggregate<RowDecoder>
{
var aggregate = AssociationAggregate<RowDecoder> { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression ?? rhs)
}
// Preserve alias
aggregate.alias = lhs.alias
// Preserve key
aggregate.key = lhs.key
return aggregate
}
@@ -58,7 +58,7 @@
/// }
///
/// See ForeignKey for more information.
public struct BelongsToAssociation<Origin, Destination>: AssociationToOne {
public struct BelongsToAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToOne {
/// :nodoc:
public typealias OriginRowDecoder = Origin
@@ -73,6 +73,3 @@ public struct BelongsToAssociation<Origin, Destination>: AssociationToOne {
self.sqlAssociation = sqlAssociation
}
}
// Allow BelongsToAssociation(...).filter(key: ...)
extension BelongsToAssociation: TableRequest where Destination: TableRecord { }
@@ -58,7 +58,7 @@
/// }
///
/// See ForeignKey for more information.
public struct HasManyAssociation<Origin, Destination>: AssociationToMany {
public struct HasManyAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToMany {
/// :nodoc:
public typealias OriginRowDecoder = Origin
@@ -73,6 +73,3 @@ public struct HasManyAssociation<Origin, Destination>: AssociationToMany {
self.sqlAssociation = sqlAssociation
}
}
// Allow HasManyAssociation(...).filter(key: ...)
extension HasManyAssociation: TableRequest where Destination: TableRecord { }
@@ -41,7 +41,7 @@
/// two other associations: the `through:` and `using:` arguments. Those
/// associations can be any other association (BelongsTo, HasMany,
/// HasManyThrough, etc).
public struct HasManyThroughAssociation<Origin, Destination>: AssociationToMany {
public struct HasManyThroughAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToMany {
/// :nodoc:
public typealias OriginRowDecoder = Origin
@@ -56,6 +56,3 @@ public struct HasManyThroughAssociation<Origin, Destination>: AssociationToMany
self.sqlAssociation = sqlAssociation
}
}
// Allow HasManyThroughAssociation(...).filter(key: ...)
extension HasManyThroughAssociation: TableRequest where Destination: TableRecord { }
@@ -60,7 +60,7 @@
/// }
///
/// See ForeignKey for more information.
public struct HasOneAssociation<Origin, Destination>: AssociationToOne {
public struct HasOneAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToOne {
/// :nodoc:
public typealias OriginRowDecoder = Origin
@@ -75,6 +75,3 @@ public struct HasOneAssociation<Origin, Destination>: AssociationToOne {
self.sqlAssociation = sqlAssociation
}
}
// Allow HasOneAssociation(...).filter(key: ...)
extension HasOneAssociation: TableRequest where Destination: TableRecord { }
@@ -21,7 +21,7 @@
/// two other associations: the `through:` and `using:` arguments. Those
/// associations can be any other association to one (BelongsTo, HasOne,
/// HasOneThrough).
public struct HasOneThroughAssociation<Origin, Destination>: AssociationToOne {
public struct HasOneThroughAssociation<Origin: TableRecord, Destination: TableRecord>: AssociationToOne {
/// :nodoc:
public typealias OriginRowDecoder = Origin
@@ -36,6 +36,3 @@ public struct HasOneThroughAssociation<Origin, Destination>: AssociationToOne {
self.sqlAssociation = sqlAssociation
}
}
// Allow HasOneThroughAssociation(...).filter(key: ...)
extension HasOneThroughAssociation: TableRequest where Destination: TableRecord { }
@@ -4,8 +4,8 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
let (request, expression) = aggregate.prepare(self)
if let alias = aggregate.alias {
return request.annotated(with: [expression.aliased(alias)])
if let key = aggregate.key {
return request.annotated(with: [expression.forKey(key)])
} else {
return request.annotated(with: [expression])
}
@@ -20,7 +20,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> QueryInterfaceRequest {
return annotated(with: aggregates)
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
@@ -28,7 +28,7 @@
/// }
///
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct QueryInterfaceRequest<T>: DerivableRequest {
public struct QueryInterfaceRequest<T> {
var query: SQLQuery
init(query: SQLQuery) {
@@ -86,7 +86,7 @@ extension QueryInterfaceRequest: FetchRequest {
/// - parameter db: A database connection.
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
var region = try SQLQueryGenerator(query).databaseRegion(db)
var region = try SQLQueryGenerator(query).makeSelectStatement(db).databaseRegion
// Iterate all prefetched associations
var fifo = query.relation.prefetchedAssociations
@@ -101,11 +101,11 @@ extension QueryInterfaceRequest: FetchRequest {
let prefetchedRelation = association
.mapPivotRelation { $0.qualified(with: pivotAlias) }
.destinationRelation(fromOriginRows: { _ in [] /* no origin row */ })
.annotated(with: pivotColumns.map { pivotAlias[Column($0)].aliased("grdb_\($0)") })
.annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") })
let prefetchedQuery = SQLQuery(relation: prefetchedRelation)
// Union region
try region.formUnion(SQLQueryGenerator(prefetchedQuery).databaseRegion(db))
try region.formUnion(SQLQueryGenerator(prefetchedQuery).makeSelectStatement(db).databaseRegion)
// Append nested prefetched associations (support for
// A.including(all: A.bs.including(all: B.cs))
@@ -143,7 +143,9 @@ extension QueryInterfaceRequest: SelectionRequest {
/// let request = Player.all().select([max(Column("score"))], as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
public func select<RowDecoder>(_ selection: [SQLSelectable], as type: RowDecoder.Type)
-> QueryInterfaceRequest<RowDecoder>
{
return mapQuery { $0.select(selection) }.asRequest(of: RowDecoder.self)
}
@@ -155,7 +157,9 @@ extension QueryInterfaceRequest: SelectionRequest {
/// let request = Player.all().select(max(Column("score")), as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
public func select<RowDecoder>(_ selection: SQLSelectable..., as type: RowDecoder.Type)
-> QueryInterfaceRequest<RowDecoder>
{
return select(selection, as: type)
}
@@ -167,7 +171,12 @@ extension QueryInterfaceRequest: SelectionRequest {
/// let request = Player.all().select(sql: "max(score)", as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
public func select<RowDecoder>(
sql: String,
arguments: StatementArguments = StatementArguments(),
as type: RowDecoder.Type)
-> QueryInterfaceRequest<RowDecoder>
{
return select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type)
}
@@ -198,7 +207,11 @@ extension QueryInterfaceRequest: SelectionRequest {
/// as: String.self)
/// let name: String? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
public func select<RowDecoder>(
literal sqlLiteral: SQLLiteral,
as type: RowDecoder.Type)
-> QueryInterfaceRequest<RowDecoder>
{
return select(SQLSelectionLiteral(literal: sqlLiteral), as: type)
}
@@ -225,7 +238,7 @@ extension QueryInterfaceRequest: SelectionRequest {
extension QueryInterfaceRequest: FilteredRequest {
// MARK: Request Derivation
/// Creates a request with the provided *predicate promise* added to the
/// eventual set of already applied predicates.
///
@@ -235,7 +248,6 @@ extension QueryInterfaceRequest: FilteredRequest {
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
return mapQuery { $0.filter(predicate) }
}
}
extension QueryInterfaceRequest: OrderedRequest {
@@ -298,7 +310,7 @@ extension QueryInterfaceRequest: AggregatingRequest {
}
}
extension QueryInterfaceRequest: JoinableRequest {
extension QueryInterfaceRequest: _JoinableRequest {
/// :nodoc:
public func _including(all association: SQLAssociation) -> QueryInterfaceRequest {
return mapQuery { $0._including(all: association) }
@@ -325,10 +337,12 @@ extension QueryInterfaceRequest: JoinableRequest {
}
}
extension QueryInterfaceRequest: JoinableRequest where T: TableRecord { }
extension QueryInterfaceRequest {
// MARK: Request Derivation
/// Creates a request which returns distinct rows.
///
/// // SELECT DISTINCT * FROM player
@@ -460,6 +474,8 @@ extension QueryInterfaceRequest: TableRequest {
}
}
extension QueryInterfaceRequest: DerivableRequest where T: TableRecord { }
extension QueryInterfaceRequest where T: MutablePersistableRecord {
// MARK: Deleting
@@ -479,7 +495,7 @@ extension QueryInterfaceRequest where T: MutablePersistableRecord {
// MARK: - Eager loading of hasMany associations
/// Append rows from prefetched associations into the argument rows.
fileprivate func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws {
private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws {
guard let firstRow = rows.first else {
// No rows -> no prefetch
return
@@ -517,7 +533,7 @@ fileprivate func prefetch(_ db: Database, associations: [SQLAssociation], in row
let prefetchedRelation = association
.mapPivotRelation { $0.qualified(with: pivotAlias) }
.destinationRelation(fromOriginRows: { _ in rows })
.annotated(with: pivotColumns.map { pivotAlias[Column($0)].aliased("grdb_\($0)") })
.annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") })
prefetchedRows = try QueryInterfaceRequest(relation: prefetchedRelation)
.fetchAll(db)
.grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" })
@@ -176,7 +176,7 @@ extension FilteredRequest {
// NOT TESTED
return filter(SQLExpressionLiteral(literal: sqlLiteral))
}
/// Creates a request that matches nothing.
///
/// // SELECT * FROM player WHERE 0
@@ -230,7 +230,10 @@ extension TableRequest where Self: FilteredRequest {
}
/// Creates a request with the provided primary key *predicate*.
public func filter<Sequence: Swift.Sequence>(keys: Sequence) -> Self where Sequence.Element: DatabaseValueConvertible {
public func filter<Sequence: Swift.Sequence>(keys: Sequence)
-> Self
where Sequence.Element: DatabaseValueConvertible
{
var request = self
let keys = Array(keys)
switch keys.count {
@@ -241,7 +244,7 @@ extension TableRequest where Self: FilteredRequest {
default:
break
}
let databaseTableName = self.databaseTableName
return request.filter { db in
let primaryKey = try db.primaryKey(databaseTableName)
@@ -286,7 +289,10 @@ extension TableRequest where Self: FilteredRequest {
// ("foo", "bar") is not a unique key (primary key or columns of a
// unique index)
guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
fatalError("table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))")
fatalError("""
table \(databaseTableName) has no unique index on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
}
let lowercaseColumns = columns.map { $0.lowercased() }
@@ -365,13 +371,13 @@ extension AggregatingRequest {
// NOT TESTED
return group(SQLExpressionLiteral(literal: sqlLiteral))
}
/// Creates a request with the provided *sql* added to the
/// eventual set of already applied predicates.
public func having(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
return having(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request with the provided *sql* added to the
/// eventual set of already applied predicates.
public func having(literal sqlLiteral: SQLLiteral) -> Self {
@@ -494,6 +500,8 @@ extension OrderedRequest {
}
}
// MARK: - JoinableRequest
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Type-unsafe support for the JoinableRequest protocol.
@@ -542,7 +550,7 @@ public protocol JoinableRequest: _JoinableRequest {
/// // BelongsToAssociation<Book, Author>
/// static let author = belongsTo(Author.self)
/// }
associatedtype RowDecoder
associatedtype RowDecoder: TableRecord
}
extension JoinableRequest {
@@ -587,4 +595,4 @@ extension JoinableRequest {
/// The base protocol for all requests that can be refined.
///
/// :nodoc:
public protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest, JoinableRequest { }
public protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { }
@@ -51,7 +51,7 @@ public struct SQLCollatedExpression {
}
/// :nodoc:
extension SQLCollatedExpression : SQLOrderingTerm {
extension SQLCollatedExpression: SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
+5 -3
View File
@@ -37,15 +37,17 @@ extension SQLCollection {
/// SQLExpressionsArray wraps an array of expressions
///
/// SQLExpressionsArray([1, 2, 3])
struct SQLExpressionsArray : SQLCollection {
struct SQLExpressionsArray: SQLCollection {
let expressions: [SQLExpression]
init<S: Sequence>(_ expressions: S) where S.Iterator.Element : SQLExpressible {
init<S: Sequence>(_ expressions: S) where S.Iterator.Element: SQLExpressible {
self.expressions = expressions.map { $0.sqlExpression }
}
func collectionSQL(_ context: inout SQLGenerationContext) -> String {
return (expressions.map { $0.expressionSQL(&context, wrappedInParenthesis: false) } as [String]).joined(separator: ", ")
return expressions
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
.joined(separator: ", ")
}
func contains(_ value: SQLExpressible) -> SQLExpression {
+1 -1
View File
@@ -31,7 +31,7 @@ public protocol SQLExpressible {
/// On the other side, Int adopts SQLExpressible (via DatabaseValueConvertible).
///
/// :nodoc:
public protocol SQLSpecificExpressible : SQLExpressible {
public protocol SQLSpecificExpressible: SQLExpressible {
// SQLExpressible can be adopted by Swift standard types, and user
// types, through the DatabaseValueConvertible protocol which inherits
// from SQLExpressible.
@@ -14,10 +14,10 @@ extension SQLExpression {
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
///
/// "foo'bar".databaseValue.quotedSQL(wrappedInParenthesis: true) // "'foo''bar'""
func quotedSQL(wrappedInParenthesis: Bool) -> String {
/// "foo'bar".databaseValue.quotedSQL() // "'foo''bar'""
func quotedSQL() -> String {
var context = SQLGenerationContext.literalGenerationContext(withArguments: false)
return expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis)
return expressionSQL(&context, wrappedInParenthesis: false)
}
}
@@ -33,7 +33,7 @@ extension SQLExpression {
///
/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2])
/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])
public struct SQLExpressionLiteral : SQLExpression {
public struct SQLExpressionLiteral: SQLExpression {
private let sqlLiteral: SQLLiteral
public var sql: String { return sqlLiteral.sql }
public var arguments: StatementArguments { return sqlLiteral.arguments }
@@ -93,7 +93,7 @@ public struct SQLExpressionLiteral : SQLExpression {
/// SQLUnaryOperator is a SQLite unary operator.
///
/// :nodoc:
public struct SQLUnaryOperator : Hashable {
public struct SQLUnaryOperator: Hashable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The SQL operator
@@ -121,7 +121,7 @@ public struct SQLUnaryOperator : Hashable {
/// an operand expression.
///
/// :nodoc:
public struct SQLExpressionUnary : SQLExpression {
public struct SQLExpressionUnary: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The unary operator
@@ -167,7 +167,7 @@ public struct SQLExpressionUnary : SQLExpression {
/// SQLBinaryOperator is a SQLite binary operator.
///
/// :nodoc:
public struct SQLBinaryOperator : Hashable {
public struct SQLBinaryOperator: Hashable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The SQL operator
@@ -211,7 +211,7 @@ public struct SQLBinaryOperator : Hashable {
/// SQLExpressionBinary(.multiply, Column("length"), Column("width"))
///
/// :nodoc:
public struct SQLExpressionBinary : SQLExpression {
public struct SQLExpressionBinary: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The left operand
@@ -252,17 +252,17 @@ public struct SQLExpressionBinary : SQLExpression {
\(rhs.expressionSQL(&context, wrappedInParenthesis: true))
"""
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public var negated: SQLExpression {
if let negatedOp = op.negated {
return SQLExpressionBinary(negatedOp, lhs, rhs)
return SQLExpressionBinary(negatedOp, lhs, rhs)
} else {
return SQLExpressionNot(self)
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
@@ -272,7 +272,7 @@ public struct SQLExpressionBinary : SQLExpression {
// MARK: - SQLExpressionAnd
struct SQLExpressionAnd : SQLExpression {
struct SQLExpressionAnd: SQLExpression {
let expressions: [SQLExpression]
init(_ expressions: [SQLExpression]) {
@@ -312,7 +312,7 @@ struct SQLExpressionAnd : SQLExpression {
// MARK: - SQLExpressionOr
struct SQLExpressionOr : SQLExpression {
struct SQLExpressionOr: SQLExpression {
let expressions: [SQLExpression]
init(_ expressions: [SQLExpression]) {
@@ -422,9 +422,9 @@ struct SQLExpressionEqual: SQLExpression {
}
}
switch (lhs, rhs) {
case (let column as ColumnExpression, let dbValue as DatabaseValue):
case let (column as ColumnExpression, dbValue as DatabaseValue):
return matchedRowIds(column: column, dbValue: dbValue)
case (let dbValue as DatabaseValue, let column as ColumnExpression):
case let (dbValue as DatabaseValue, column as ColumnExpression):
return matchedRowIds(column: column, dbValue: dbValue)
default:
return nil
@@ -443,7 +443,7 @@ struct SQLExpressionEqual: SQLExpression {
///
/// // id IN (1,2,3)
/// SQLExpressionContains(Column("id"), SQLExpressionsArray([1,2,3]))
struct SQLExpressionContains : SQLExpression {
struct SQLExpressionContains: SQLExpression {
let expression: SQLExpression
let collection: SQLCollection
let isNegated: Bool
@@ -509,7 +509,7 @@ struct SQLExpressionContains : SQLExpression {
///
/// // id BETWEEN 1 AND 3
/// SQLExpressionBetween(Column("id"), 1.databaseValue, 3.databaseValue)
struct SQLExpressionBetween : SQLExpression {
struct SQLExpressionBetween: SQLExpression {
let expression: SQLExpression
let lowerBound: SQLExpression
let upperBound: SQLExpression
@@ -534,7 +534,7 @@ struct SQLExpressionBetween : SQLExpression {
\(upperBound.expressionSQL(&context, wrappedInParenthesis: true))
"""
}
var negated: SQLExpression {
return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated)
}
@@ -553,7 +553,7 @@ struct SQLExpressionBetween : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// SQLFunctionName is an SQL function name.
public struct SQLFunctionName : Hashable {
public struct SQLFunctionName: Hashable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The SQL function name
@@ -581,7 +581,7 @@ public struct SQLFunctionName : Hashable {
/// SQLExpressionFunction(.abs, [-1.databaseValue])
///
/// :nodoc:
public struct SQLExpressionFunction : SQLExpression {
public struct SQLExpressionFunction: SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The function name
@@ -616,11 +616,13 @@ public struct SQLExpressionFunction : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
return """
\(functionName.sql)(\
\((arguments.map { $0.expressionSQL(&context, wrappedInParenthesis: false) } as [String]).joined(separator: ", "))\
)
"""
var sql = functionName.sql
sql += "("
sql += arguments
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
.joined(separator: ", ")
sql += ")"
return sql
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -636,7 +638,7 @@ public struct SQLExpressionFunction : SQLExpression {
///
/// // COUNT(name)
/// SQLExpressionCount(Column("name"))
struct SQLExpressionCount : SQLExpression {
struct SQLExpressionCount: SQLExpression {
/// The counted value
let counted: SQLSelectable
@@ -659,7 +661,7 @@ struct SQLExpressionCount : SQLExpression {
///
/// // COUNT(DISTINCT name)
/// SQLExpressionCountDistinct(Column("name"))
struct SQLExpressionCountDistinct : SQLExpression {
struct SQLExpressionCountDistinct: SQLExpression {
let counted: SQLExpression
init(_ counted: SQLExpression) {
@@ -680,7 +682,7 @@ struct SQLExpressionCountDistinct : SQLExpression {
/// This one helps generating `COUNT(...) = 0` or `COUNT(...) > 0` while letting
/// the user using the not `!` logical operator, or comparisons with booleans
/// such as `== true` or `== false`.
struct SQLExpressionIsEmpty : SQLExpression {
struct SQLExpressionIsEmpty: SQLExpression {
var countExpression: SQLExpression
var isEmpty: Bool
@@ -739,7 +741,7 @@ struct TableMatchExpression: SQLExpression {
///
/// // email = 'arthur@example.com' COLLATE NOCASE
/// SQLExpressionCollate(Column("email") == "arthur@example.com", "NOCASE")
struct SQLExpressionCollate : SQLExpression {
struct SQLExpressionCollate: SQLExpression {
let expression: SQLExpression
let collationName: Database.CollationName
@@ -752,9 +754,8 @@ struct SQLExpressionCollate : SQLExpression {
if wrappedInParenthesis {
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
}
let sql = expression.expressionSQL(&context, wrappedInParenthesis: false)
return """
\(sql) \
\(expression.expressionSQL(&context, wrappedInParenthesis: false)) \
COLLATE \
\(collationName.rawValue)
"""
+2 -14
View File
@@ -5,20 +5,8 @@
/// SQLExpression is the protocol for types that represent an SQL expression, as
/// described at https://www.sqlite.org/lang_expr.html
///
/// GRDB ships with a variety of types that already adopt this protocol, and
/// allow to represent many SQLite expressions:
///
/// - Column
/// - DatabaseValue
/// - SQLExpressionLiteral
/// - SQLExpressionUnary
/// - SQLExpressionBinary
/// - SQLExpressionExists
/// - SQLExpressionFunction
/// - SQLExpressionCollate
///
/// :nodoc:
public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm {
public protocol SQLExpression: SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
@@ -131,7 +119,7 @@ extension SQLExpression {
// MARK: - SQLExpressionNot
struct SQLExpressionNot : SQLExpression {
struct SQLExpressionNot: SQLExpression {
let expression: SQLExpression
init(_ expression: SQLExpression) {
@@ -67,7 +67,7 @@ struct SQLForeignKeyRequest: Equatable {
// No matching foreign key found: use the destination primary key
if let originColumns = originColumns {
let destinationColumns = try db.primaryKey(destinationTable).columns
if (originColumns.count == destinationColumns.count) {
if originColumns.count == destinationColumns.count {
let mapping = zip(originColumns, destinationColumns).map {
(origin: $0, destination: $1)
}
+2 -2
View File
@@ -158,7 +158,7 @@ extension SQLSpecificExpressible {
public var capitalized: SQLExpression {
return DatabaseFunction.capitalize.apply(sqlExpression)
}
/// Returns an SQL expression that applies the Swift's built-in
/// lowercased String property. It is NULL for non-String arguments.
///
@@ -168,7 +168,7 @@ extension SQLSpecificExpressible {
public var lowercased: SQLExpression {
return DatabaseFunction.lowercase.apply(sqlExpression)
}
/// Returns an SQL expression that applies the Swift's built-in
/// uppercased String property. It is NULL for non-String arguments.
///
+2 -2
View File
@@ -3,14 +3,14 @@
// Outputs "x = y" or "x IS NULL"
private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression {
switch (lhs, rhs) {
case (let lhs, let rhs as DatabaseValue):
case let (lhs, rhs as DatabaseValue):
switch rhs.storage {
case .null:
return SQLExpressionEqual(.is, lhs, rhs)
default:
return SQLExpressionEqual(.equal, lhs, rhs)
}
case (let lhs as DatabaseValue, let rhs):
case let (lhs as DatabaseValue, rhs):
switch lhs.storage {
case .null:
return SQLExpressionEqual(.is, rhs, lhs)
+1 -1
View File
@@ -23,7 +23,7 @@ public protocol SQLOrderingTerm {
// MARK: - SQLOrdering
enum SQLOrdering : SQLOrderingTerm {
enum SQLOrdering: SQLOrderingTerm {
case asc(SQLExpression)
case desc(SQLExpression)
+1 -1
View File
@@ -11,7 +11,7 @@ struct SQLQuery {
// `(a AND b AND c)` instead of `((a AND b) AND c)`.
var havingExpressions: [SQLExpression]
var limit: SQLLimit?
init(
relation: SQLRelation,
isDistinct: Bool = false,
+12 -8
View File
@@ -1,4 +1,5 @@
/// A "relation", as defined by the [relational terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology),
/// A "relation", as defined by the [relational
/// terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology),
/// is "a set of tuples sharing the same attributes; a set of columns and rows."
///
/// SQLRelation is defined with a selection, a source table of query, and an
@@ -200,7 +201,7 @@ extension SQLRelation {
relation.selection.append(contentsOf: selection)
return relation
}
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> SQLRelation {
var relation = self
relation.filtersPromise = relation.filtersPromise.flatMap { filters in
@@ -277,10 +278,10 @@ extension SQLRelation {
/// as HasManyThrough, which have any number of pivot relations between the
/// origin and the destination.
func appendingChild(for association: SQLAssociation, kind: SQLRelation.Child.Kind) -> SQLRelation {
// Preserve association cardinality in intermediate steps of
// including(all:), and force desired cardinality otherwize
let childCardinality = (kind == .allNotPrefetched)
// preserve association cardinality in intermediate steps of including(all:)
? association.destination.cardinality
// force desired cardinality otherwize
: kind.cardinality
let childKey = association.destination.key.name(for: childCardinality)
let child = SQLRelation.Child(
@@ -347,7 +348,10 @@ extension SQLRelation {
if let existingChild = relation.children.removeValue(forKey: key) {
guard let mergedChild = existingChild.merged(with: child) else {
// can't merge
fatalError("The association key \"\(key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.")
fatalError("""
The association key \"\(key)\" is ambiguous. \
Use the Association.forKey(_:) method is order to disambiguate.
""")
}
relation.children.appendValue(mergedChild, forKey: key)
} else {
@@ -387,7 +391,7 @@ enum SQLSource {
func qualified(with alias: TableAlias) -> SQLSource {
switch self {
case .table(let tableName, let sourceAlias):
case let .table(tableName, sourceAlias):
if let sourceAlias = sourceAlias {
alias.becomeProxy(of: sourceAlias)
return self
@@ -395,7 +399,7 @@ enum SQLSource {
alias.setTableName(tableName)
return .table(tableName: tableName, alias: alias)
}
case .query(let query):
case let .query(query):
return .query(query.qualified(with: alias))
}
}
@@ -774,7 +778,7 @@ extension SQLRelation.Child.Kind {
// .including(all: associationToDestinationThroughPivot)
// .including(all: associationToPivot)
fatalError("Not implemented: merging a direct association and an indirect one with including(all:)")
case (.allNotPrefetched, .allNotPrefetched):
// Equivalent to Record.including(all: association)
//
@@ -18,7 +18,7 @@ public struct AllColumns {
public init() { }
}
extension AllColumns : SQLSelectable {
extension AllColumns: SQLSelectable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
@@ -69,7 +69,7 @@ struct QualifiedAllColumns {
}
}
extension QualifiedAllColumns : SQLSelectable {
extension QualifiedAllColumns: SQLSelectable {
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
if let qualifier = context.qualifier(for: alias) {
return qualifier.quotedDatabaseIdentifier + ".*"
@@ -94,10 +94,10 @@ extension QualifiedAllColumns : SQLSelectable {
//
// So let's always return `*`, and fix this later.
// if context.qualifier(for: alias) != nil {
// // SELECT COUNT(t.*) is invalid SQL
// fatalError("Not implemented, or invalid query")
// }
// if context.qualifier(for: alias) != nil {
// // SELECT COUNT(t.*) is invalid SQL
// fatalError("Not implemented, or invalid query")
// }
return "*"
}
@@ -118,7 +118,7 @@ extension QualifiedAllColumns : SQLSelectable {
// MARK: - SQLAliasedExpression
struct SQLAliasedExpression : SQLSelectable {
struct SQLAliasedExpression: SQLSelectable {
let expression: SQLExpression
let name: String
+13 -4
View File
@@ -25,7 +25,7 @@ public protocol SQLSelectable {
// MARK: - SQLSelectionLiteral
struct SQLSelectionLiteral : SQLSelectable {
struct SQLSelectionLiteral: SQLSelectable {
private let sqlLiteral: SQLLiteral
init(literal sqlLiteral: SQLLiteral) {
@@ -42,15 +42,24 @@ struct SQLSelectionLiteral : SQLSelectable {
}
func countedSQL(_ context: inout SQLGenerationContext) -> String {
fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.")
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several SQLExpressionLiteral instead.
""")
}
func count(distinct: Bool) -> SQLCount? {
fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.")
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several SQLExpressionLiteral instead.
""")
}
func columnCount(_ db: Database) throws -> Int {
fatalError("Selection literals don't known how many columns they contain. To resolve this error, select one or several SQLExpressionLiteral instead.")
fatalError("""
Selection literals don't known how many columns they contain. \
To resolve this error, select one or several SQLExpressionLiteral instead.
""")
}
func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable {
@@ -24,18 +24,78 @@ extension SQLSpecificExpressible {
/// :nodoc:
extension SQLSpecificExpressible {
/// Returns a value that can be used as an argument to QueryInterfaceRequest.select()
/// Give the expression the given SQL name.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
/// For example:
///
/// // SELECT (width * height) AS area FROM shape
/// let area = (Column("width") * Column("height")).aliased("area")
/// let request = Shape.select(area)
/// if let row = try Row.fetchOne(db, request) {
/// let area: Int = row["area"]
/// }
@available(*, deprecated, renamed: "forKey(_:)")
public func aliased(_ name: String) -> SQLSelectable {
return SQLAliasedExpression(sqlExpression, name: name)
return forKey(name)
}
/// Returns a value that can be used as an argument to QueryInterfaceRequest.select()
/// Give the expression the given SQL name.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
/// For example:
///
/// // SELECT (width * height) AS area FROM shape
/// let area = (Column("width") * Column("height")).forKey("area")
/// let request = Shape.select(area)
/// if let row = try Row.fetchOne(db, request) {
/// let area: Int = row["area"]
/// }
public func forKey(_ key: String) -> SQLSelectable {
return SQLAliasedExpression(sqlExpression, name: key)
}
/// Give the expression the same SQL name as the coding key.
///
/// For example:
///
/// struct Shape: Decodable, FetchableRecord, TableRecord {
/// let width: Int
/// let height: Int
/// let area: Int
///
/// static let databaseSelection: [SQLSelectable] = [
/// Column(CodingKeys.width),
/// Column(CodingKeys.height),
/// (Column(CodingKeys.width) * Column(CodingKeys.height)).aliased(CodingKeys.area),
/// ]
/// }
///
/// // SELECT width, height, (width * height) AS area FROM shape
/// let shapes: [Shape] = try Shape.fetchAll(db)
@available(*, deprecated, renamed: "forKey(_:)")
public func aliased(_ key: CodingKey) -> SQLSelectable {
return aliased(key.stringValue)
return forKey(key)
}
/// Give the expression the same SQL name as the coding key.
///
/// For example:
///
/// struct Shape: Decodable, FetchableRecord, TableRecord {
/// let width: Int
/// let height: Int
/// let area: Int
///
/// static let databaseSelection: [SQLSelectable] = [
/// Column(CodingKeys.width),
/// Column(CodingKeys.height),
/// (Column(CodingKeys.width) * Column(CodingKeys.height)).forKey(CodingKeys.area),
/// ]
/// }
///
/// // SELECT width, height, (width * height) AS area FROM shape
/// let shapes: [Shape] = try Shape.fetchAll(db)
public func forKey(_ key: CodingKey) -> SQLSelectable {
return forKey(key.stringValue)
}
}
@@ -63,4 +123,3 @@ extension SQLSpecificExpressible {
return SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(collation.name))
}
}
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff. Show more