Merge branch 'GRDB3' into development
No files matched your search
@@ -1 +1 @@
|
||||
4.0
|
||||
4.1
|
||||
@@ -15,198 +15,140 @@ jobs:
|
||||
###########################################
|
||||
## Test GRDB
|
||||
|
||||
# Test GRDBOSX (Xcode 9.2)
|
||||
# Test GRDBOSX (Xcode 9.3)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDBOSX (Xcode 9.2, macOS)
|
||||
- TID=GRDBOSX (Xcode 9.3, macOS)
|
||||
script: make test_framework_GRDBOSX
|
||||
|
||||
# Test GRDBWatchOS (Xcode 9.2)
|
||||
# Test GRDBWatchOS (Xcode 9.3)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDBWatchOS (Xcode 9.2, watchOS)
|
||||
- TID=GRDBWatchOS (Xcode 9.3, watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
# Test GRDBiOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
|
||||
# Test GRDBiOS (Xcode 9.3, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 9.2, iOS <MAX>)
|
||||
- TID=GRDBiOS (Xcode 9.3, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget
|
||||
|
||||
# Test GRDBiOS (Xcode 9.2, iOS <MINIMUM VERSION>))
|
||||
# Test GRDBiOS (Xcode 9.3, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 9.2, iOS <MIN>)
|
||||
- TID=GRDBiOS (Xcode 9.3, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
# Test GRDB [SPM] (Xcode 9.2, macOS)
|
||||
# Test GRDB [SPM] (Xcode 9.3, macOS)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDB [SPM] (Xcode 9.2, macOS)
|
||||
- TID=GRDB [SPM] (Xcode 9.3, macOS)
|
||||
script: make test_SPM
|
||||
|
||||
# Test GRDBOSX (Xcode 9.0)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBOSX (Xcode 9.0, macOS)
|
||||
script: make test_framework_GRDBOSX
|
||||
|
||||
# Test GRDBiOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 9.0, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB (Custom SQLite)
|
||||
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 9.2)
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 9.3)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 9.2, macOS)
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 9.3, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.3, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MAX>)
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.3, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MINIMUM VERSION>))
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.3, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS <MIN>)
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.3, iOS <MIN>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 9.0)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 9.0, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.0, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB (SQLCipher)
|
||||
|
||||
# Test GRDBCipherOSX (Xcode 9.2)
|
||||
# Test GRDBCipherOSX (Xcode 9.3)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDBCipherOSX (Xcode 9.2, macOS)
|
||||
- TID=GRDBCipherOSX (Xcode 9.3, macOS)
|
||||
script: make test_framework_GRDBCipherOSX
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 9.2, iOS <MAXIMUM VERSION>)
|
||||
# Test GRDBCipheriOS (Xcode 9.3, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 9.2, iOS <MAX>)
|
||||
- TID=GRDBCipheriOS (Xcode 9.3, iOS <MAX>)
|
||||
script: make test_framework_GRDBCipheriOS_maxTarget
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 9.2, iOS <MINIMUM VERSION>))
|
||||
# Test GRDBCipheriOS (Xcode 9.3, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 9.2, iOS <MIN>)
|
||||
- TID=GRDBCipheriOS (Xcode 9.3, iOS <MIN>)
|
||||
script: make test_framework_GRDBCipheriOS_minTarget
|
||||
|
||||
# Test GRDBCipherOSX (Xcode 9.0)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCipherOSX (Xcode 9.0, macOS)
|
||||
script: make test_framework_GRDBCipherOSX
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 9.0, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 9.0, iOS <MAX>)
|
||||
script: make test_framework_GRDBCipheriOS_maxTarget
|
||||
|
||||
|
||||
###########################################
|
||||
## Test Installation Methods
|
||||
|
||||
# Manual Install (Xcode 9.2)
|
||||
# Manual Install (Xcode 9.3)
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=Manual Install (Xcode 9.2)
|
||||
- TID=Manual Install (Xcode 9.3)
|
||||
script: make test_install_manual
|
||||
|
||||
# Manual Install (GRDBCipher, Xcode 9.2)
|
||||
# Manual Install (GRDBCipher, Xcode 9.3)
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=Manual Install (GRDBCipher, Xcode 9.2)
|
||||
- TID=Manual Install (GRDBCipher, Xcode 9.3)
|
||||
script: make test_install_GRDBCipher
|
||||
|
||||
# Cocoapods Lint (Xcode 9.2)
|
||||
# Cocoapods Lint (Xcode 9.3)
|
||||
- stage: Test Installation
|
||||
osx_image: xcode9.2
|
||||
osx_image: xcode9.3
|
||||
install:
|
||||
- gem install cocoapods # Since Travis is not always on latest version
|
||||
env:
|
||||
- TID=Cocoapods (Xcode 9.2)
|
||||
- TID=Cocoapods (Xcode 9.3)
|
||||
script: make test_CocoaPodsLint
|
||||
|
||||
# Cocoapods Lint (Xcode 9.0)
|
||||
# SPM Install (Xcode 9.3)
|
||||
- stage: Test Installation
|
||||
osx_image: xcode9
|
||||
install:
|
||||
- gem install cocoapods # Since Travis is not always on latest version
|
||||
osx_image: xcode9.3
|
||||
env:
|
||||
- TID=Cocoapods (Xcode 9.0)
|
||||
script: make test_CocoaPodsLint
|
||||
|
||||
# SPM Install (Xcode 9.2)
|
||||
- stage: Test Installation
|
||||
osx_image: xcode9.2
|
||||
env:
|
||||
- TID=SPM (Xcode 9.2)
|
||||
- TID=SPM (Xcode 9.3)
|
||||
script: make test_install_SPM
|
||||
|
||||
## Carthage Build
|
||||
## Commented out until `make test_CarthageBuild` performs *reliably*.
|
||||
## See https://github.com/groue/GRDB.swift/pull/262
|
||||
# - stage: Test Installation
|
||||
# osx_image: xcode9.2
|
||||
# osx_image: xcode9.3
|
||||
# before_install:
|
||||
# - brew update
|
||||
# - brew outdated carthage || brew upgrade carthage
|
||||
|
||||
@@ -1,9 +1,59 @@
|
||||
Release Notes
|
||||
=============
|
||||
|
||||
## Next Version
|
||||
## 3.0.0
|
||||
|
||||
- Improved parsing of dates and date components ([#334](https://github.com/groue/GRDB.swift/pull/334) by @sobri909)
|
||||
GRDB 3 is a release focused on **modernization**, **safety**, and **associations between record types**.
|
||||
|
||||
It comes with new features, but also a few breaking changes, and a set of updated good practices. The [GRDB 2 Migration Guide](Documentation/GRDB2MigrationGuide.md) will help you upgrading your applications.
|
||||
|
||||
|
||||
### New
|
||||
|
||||
- Associations and Joins ([#319](https://github.com/groue/GRDB.swift/pull/319)).
|
||||
- Enhancements to logical operators ([#336](https://github.com/groue/GRDB.swift/pull/336)).
|
||||
- Foster auto-incremented primary keys ([#337](https://github.com/groue/GRDB.swift/pull/337)).
|
||||
- ColumnExpression Protocol ([#340](https://github.com/groue/GRDB.swift/pull/340)).
|
||||
- Improved parsing of dates and date components ([#334](https://github.com/groue/GRDB.swift/pull/334) by @sobri909).
|
||||
- Common API for requests and associations derivation ([#347](https://github.com/groue/GRDB.swift/pull/347)).
|
||||
- `DatabaseMigrator.appliedMigrations(in:)` returns the set of applied migrations identifiers in a database ([#321](https://github.com/groue/GRDB.swift/pull/321)).
|
||||
- `Database.isSQLiteInternalTable(_:)` returns whether a table name is an internal SQLite table ([#321](https://github.com/groue/GRDB.swift/pull/321)).
|
||||
- `Database.isGRDBInternalTable(_:)` returns whether a table name is an internal GRDB table ([#321](https://github.com/groue/GRDB.swift/pull/321)).
|
||||
- Upgrade custom SQLite builds to [v3.23.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Improve Row descriptions ([#331](https://github.com/groue/GRDB.swift/pull/331)).
|
||||
- Request derivation protocols ([#329](https://github.com/groue/GRDB.swift/pull/329)).
|
||||
- Preliminary Linux support for the main framework ([#354](https://github.com/groue/GRDB.swift/pull/354)).
|
||||
- Automatic table name generation ([#355](https://github.com/groue/GRDB.swift/pull/355)).
|
||||
- Delayed Request Ordering ([#365](https://github.com/groue/GRDB.swift/pull/365)).
|
||||
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- Swift 4.1 is now required.
|
||||
- iOS 8 sunsetting: GRDB 3 is only tested on iOS 9+, due to a limitation in Xcode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported.
|
||||
- The Record protocols have been renamed: `RowConvertible` to `FetchableRecord`, `Persistable` to `PersistableRecord`, and `TableMapping` to `TableRecord` ([#314](https://github.com/groue/GRDB.swift/pull/314)).
|
||||
- Implicit transaction in DatabasePool.write and DatabaseQueue.write ([#332](https://github.com/groue/GRDB.swift/pull/332)).
|
||||
- `Request` and `TypedRequest` protocols have been merged into `FetchRequest` ([#311](https://github.com/groue/GRDB.swift/pull/311), [#328](https://github.com/groue/GRDB.swift/pull/328), [#348](https://github.com/groue/GRDB.swift/pull/348)).
|
||||
- Reversing unordered requests has no effect ([#342](https://github.com/groue/GRDB.swift/pull/342)).
|
||||
- The `IteratorCursor` type has been removed. Use `AnyCursor` instead ([#312](https://github.com/groue/GRDB.swift/pull/312)).
|
||||
- Row scopes collection, breadth-first scope search ([#335](https://github.com/groue/GRDB.swift/pull/335)).
|
||||
- Expressions are no longer PATs ([#330](https://github.com/groue/GRDB.swift/pull/330)).
|
||||
- Deprecated APIs have been removed.
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- [Associations](Documentation/AssociationsBasics.md): Discover the major GRDB 3 feature
|
||||
- [Database Queues](README.md#database-queues): focus on the `read` and `write` methods.
|
||||
- [Database Pools](README.md#database-pools): focus on the `read` and `write` methods.
|
||||
- [Transactions and Savepoints](README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature.
|
||||
- [ScopeAdapter](README.md#scopeadapter): do you use row adapters? If so, have a look.
|
||||
- [TableRecord Protocol](README.md#tablerecord-protocol): updated for the new automatic generation of database table name.
|
||||
- [Examples of Record Definitions](README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass).
|
||||
- [SQL Operators](README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`.
|
||||
- [Custom Requests](README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter.
|
||||
- [Customized Decoding of Database Rows](README.md#customized-decoding-of-database-rows): learn how to escape the ready-made `FetchableRecord` protocol when it does not fit your needs.
|
||||
- [Migrations](README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests).
|
||||
|
||||
|
||||
## 2.10.0
|
||||
|
||||
@@ -21,11 +21,9 @@
|
||||
56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; };
|
||||
56B036111E8D9EBE003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */; };
|
||||
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; };
|
||||
56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Person.swift */; };
|
||||
56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */; };
|
||||
56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */; };
|
||||
56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */; };
|
||||
56B036251E8D9F4C003B6DA4 /* SimplePersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */; };
|
||||
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; };
|
||||
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; };
|
||||
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */; };
|
||||
56B0365E1E8D9FB1003B6DA4 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; };
|
||||
56B0365F1E8D9FB1003B6DA4 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
/* End PBXBuildFile section */
|
||||
@@ -195,11 +193,9 @@
|
||||
56B036101E8D9EBE003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
56B036121E8D9EBE003B6DA4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
|
||||
56B0361A1E8D9F38003B6DA4 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = "<group>"; };
|
||||
56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = "<group>"; };
|
||||
56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = "<group>"; };
|
||||
56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonsViewController.swift; sourceTree = "<group>"; };
|
||||
56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimplePersonsViewController.swift; sourceTree = "<group>"; };
|
||||
56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
|
||||
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = "<group>"; };
|
||||
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = "<group>"; };
|
||||
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../GRDB.xcodeproj; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
@@ -270,8 +266,9 @@
|
||||
children = (
|
||||
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
|
||||
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
|
||||
56B0361A1E8D9F38003B6DA4 /* Person.swift */,
|
||||
56B0361D1E8D9F3D003B6DA4 /* Controllers */,
|
||||
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
|
||||
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */,
|
||||
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */,
|
||||
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
|
||||
56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */,
|
||||
56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */,
|
||||
@@ -280,17 +277,6 @@
|
||||
path = GRDBDemoiOS;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56B0361D1E8D9F3D003B6DA4 /* Controllers */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */,
|
||||
56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */,
|
||||
56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */,
|
||||
56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */,
|
||||
);
|
||||
name = Controllers;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56B036271E8D9F79003B6DA4 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -524,13 +510,11 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */,
|
||||
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */,
|
||||
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
|
||||
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
|
||||
56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */,
|
||||
56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */,
|
||||
56B036251E8D9F4C003B6DA4 /* SimplePersonsViewController.swift in Sources */,
|
||||
56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */,
|
||||
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */,
|
||||
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -770,7 +754,6 @@
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
|
||||
SWIFT_VERSION = 4.0;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
|
||||
@@ -25,14 +25,14 @@ struct AppDatabase {
|
||||
static var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
try db.create(table: "persons") { t in
|
||||
try db.create(table: "player") { t in
|
||||
// An integer primary key auto-generates unique IDs
|
||||
t.column("id", .integer).primaryKey()
|
||||
|
||||
// Sort person names in a localized case insensitive fashion by default
|
||||
// Sort player names in a localized case insensitive fashion by default
|
||||
// See https://github.com/groue/GRDB.swift/#unicode
|
||||
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
|
||||
|
||||
@@ -41,12 +41,13 @@ struct AppDatabase {
|
||||
}
|
||||
|
||||
migrator.registerMigration("fixtures") { db in
|
||||
// Populate the persons table with random data
|
||||
// Populate the players table with random data
|
||||
for _ in 0..<8 {
|
||||
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
|
||||
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
|
||||
try player.insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// // Migrations for future application versions will be inserted here:
|
||||
// migrator.registerMigration(...) { db in
|
||||
// ...
|
||||
@@ -55,3 +56,4 @@ struct AppDatabase {
|
||||
return migrator
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("db.sqlite")
|
||||
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
|
||||
|
||||
|
||||
// Be a nice iOS citizen, and don't consume too much memory
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
dbQueue.setupMemoryManagement(in: application)
|
||||
|
||||
@@ -1,15 +1,5 @@
|
||||
{
|
||||
"images" : [
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "20x20",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "20x20",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"idiom" : "iphone",
|
||||
"size" : "29x29",
|
||||
@@ -42,16 +32,6 @@
|
||||
"filename" : "Icon-60@3x.png",
|
||||
"scale" : "3x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "20x20",
|
||||
"scale" : "1x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "20x20",
|
||||
"scale" : "2x"
|
||||
},
|
||||
{
|
||||
"idiom" : "ipad",
|
||||
"size" : "29x29",
|
||||
|
||||
@@ -1,69 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11129.15" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14109" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
|
||||
<device id="retina4_7" orientation="portrait">
|
||||
<adaptation id="fullscreen"/>
|
||||
</device>
|
||||
<dependencies>
|
||||
<deployment identifier="iOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11103.10"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
|
||||
<capability name="Constraints to layout margins" minToolsVersion="6.0"/>
|
||||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--Hall Of Fame-->
|
||||
<scene sceneID="8jG-C9-QsI">
|
||||
<objects>
|
||||
<tableViewController id="cyv-nk-Plb" customClass="SimplePersonsViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="oON-zg-8kO">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Person" textLabel="XIE-DF-pSO" detailTextLabel="vyz-CH-eMb" style="IBUITableViewCellStyleValue1" id="V5t-oJ-KD9">
|
||||
<frame key="frameInset" minY="92" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="V5t-oJ-KD9" id="Coo-th-ywF">
|
||||
<frame key="frameInset" width="342" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="XIE-DF-pSO">
|
||||
<frame key="frameInset" minX="15" minY="12" width="31.5" height="19.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="vyz-CH-eMb">
|
||||
<frame key="frameInset" minX="298.5" minY="12" width="41.5" height="19.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" red="0.55686274509803924" green="0.55686274509803924" blue="0.57647058823529407" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="iNr-Oe-muq" kind="show" identifier="EditPerson" id="czF-1h-sYn"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</prototypes>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="cyv-nk-Plb" id="uBb-Bn-Lhg"/>
|
||||
<outlet property="delegate" destination="cyv-nk-Plb" id="nLb-Ak-ZXS"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<toolbarItems/>
|
||||
<navigationItem key="navigationItem" title="Hall Of Fame" id="YLU-iz-PGw"/>
|
||||
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
|
||||
<connections>
|
||||
<segue destination="ein-Sr-i8w" kind="presentation" identifier="NewPerson" id="zii-bJ-cOA"/>
|
||||
</connections>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="PrM-ex-2C8" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="630" y="640"/>
|
||||
</scene>
|
||||
<!--Person Edition View Controller-->
|
||||
<!--Player Edition View Controller-->
|
||||
<scene sceneID="Juk-Ad-tZ2">
|
||||
<objects>
|
||||
<tableViewController id="iNr-Oe-muq" customClass="PersonEditionViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableViewController id="iNr-Oe-muq" customClass="PlayerEditionViewController" customModule="GRDBDemo" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="static" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
@@ -72,13 +22,14 @@
|
||||
<tableViewSection id="Nzq-eO-jT3">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="2gb-gB-918">
|
||||
<rect key="frame" x="0.0" y="64" width="375" height="44"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="2gb-gB-918" id="iyM-TJ-JB4">
|
||||
<frame key="frameInset" width="375" height="44"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Name" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
|
||||
<rect key="frame" x="26" y="12" width="333" height="20"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
|
||||
<connections>
|
||||
@@ -94,13 +45,14 @@
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="vp3-Ft-Gth">
|
||||
<rect key="frame" x="0.0" y="108" width="375" height="44"/>
|
||||
<rect key="frame" x="0.0" y="44" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="vp3-Ft-Gth" id="ccO-0O-u72">
|
||||
<frame key="frameInset" width="375" height="44"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Score" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
|
||||
<rect key="frame" x="26" y="12" width="333" height="20"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
|
||||
</textField>
|
||||
@@ -124,12 +76,12 @@
|
||||
<navigationItem key="navigationItem" id="U4g-xG-W8b">
|
||||
<barButtonItem key="leftBarButtonItem" systemItem="cancel" id="VIN-Hi-Twt">
|
||||
<connections>
|
||||
<segue destination="lTz-K0-aRY" kind="unwind" unwindAction="cancelPersonEdition:" id="fOs-ol-qJL"/>
|
||||
<segue destination="lTz-K0-aRY" kind="unwind" unwindAction="cancelEdition:" id="fOs-ol-qJL"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
<barButtonItem key="rightBarButtonItem" systemItem="done" id="2um-u5-BhV">
|
||||
<connections>
|
||||
<segue destination="lTz-K0-aRY" kind="unwind" identifier="" unwindAction="commitPersonEdition:" id="Y1E-dI-wcl"/>
|
||||
<segue destination="lTz-K0-aRY" kind="unwind" identifier="Commit" unwindAction="commitEdition:" id="Y1E-dI-wcl"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
</navigationItem>
|
||||
@@ -146,79 +98,14 @@
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="fNC-Ls-uRw" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
<exit id="lTz-K0-aRY" userLabel="Exit" sceneMemberID="exit"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="1450" y="1435"/>
|
||||
</scene>
|
||||
<!--GRDB Demo-->
|
||||
<scene sceneID="XjB-aQ-v94">
|
||||
<objects>
|
||||
<tableViewController id="9kw-c5-KTk" customClass="DemoViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="static" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="f4Y-o2-7VW">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<sections>
|
||||
<tableViewSection id="dCg-qU-h2X">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" textLabel="clL-nG-zPX" style="IBUITableViewCellStyleDefault" id="kJB-sX-YAb">
|
||||
<rect key="frame" x="0.0" y="64" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="kJB-sX-YAb" id="f5l-ob-3DG">
|
||||
<frame key="frameInset" width="342" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Simple TableView" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="clL-nG-zPX">
|
||||
<frame key="frameInset" minX="15" width="325" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="cyv-nk-Plb" kind="show" id="Bgq-9t-jRc"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" textLabel="I78-c5-0kp" style="IBUITableViewCellStyleDefault" id="q4C-mT-5mi">
|
||||
<rect key="frame" x="0.0" y="108" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="q4C-mT-5mi" id="2Cu-K1-hiz">
|
||||
<frame key="frameInset" width="342" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="FetchedRecordsController" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="I78-c5-0kp">
|
||||
<frame key="frameInset" minX="15" width="325" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="PJp-Eq-ZjA" kind="show" id="1fk-ZR-6XN"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</cells>
|
||||
</tableViewSection>
|
||||
</sections>
|
||||
<connections>
|
||||
<outlet property="dataSource" destination="9kw-c5-KTk" id="IK7-Os-Odc"/>
|
||||
<outlet property="delegate" destination="9kw-c5-KTk" id="U7E-yB-s8d"/>
|
||||
</connections>
|
||||
</tableView>
|
||||
<navigationItem key="navigationItem" title="GRDB Demo" id="z0z-02-Ucy"/>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="OhY-4B-BcJ" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="-190" y="1435"/>
|
||||
<point key="canvasLocation" x="1134" y="2891"/>
|
||||
</scene>
|
||||
<!--Navigation Controller-->
|
||||
<scene sceneID="2KX-IU-Z5Q">
|
||||
<objects>
|
||||
<navigationController id="ein-Sr-i8w" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="zIT-dB-Mfo">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<rect key="frame" x="0.0" y="20" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
@@ -227,49 +114,49 @@
|
||||
</navigationController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="kNr-vk-I5l" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="630" y="1435"/>
|
||||
<point key="canvasLocation" x="1134" y="2071"/>
|
||||
</scene>
|
||||
<!--Navigation Controller-->
|
||||
<scene sceneID="N1X-4j-Re4">
|
||||
<objects>
|
||||
<navigationController id="UAh-8N-CM8" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="U7d-1C-GnL">
|
||||
<rect key="frame" x="0.0" y="0.0" width="320" height="44"/>
|
||||
<rect key="frame" x="0.0" y="20" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
<segue destination="9kw-c5-KTk" kind="relationship" relationship="rootViewController" id="qDW-qI-Hyg"/>
|
||||
<segue destination="PJp-Eq-ZjA" kind="relationship" relationship="rootViewController" id="klT-ZP-gtX"/>
|
||||
</connections>
|
||||
</navigationController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="sVt-e9-ghQ" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="-1006" y="1435"/>
|
||||
<point key="canvasLocation" x="-459" y="2071"/>
|
||||
</scene>
|
||||
<!--Hall Of Fame-->
|
||||
<scene sceneID="9su-ms-vdJ">
|
||||
<objects>
|
||||
<tableViewController id="PJp-Eq-ZjA" customClass="PersonsViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableViewController id="PJp-Eq-ZjA" customClass="PlayersViewController" customModule="GRDBDemo" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" id="tX0-ON-WSI">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Person" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
|
||||
<frame key="frameInset" minY="92" width="375" height="44"/>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Player" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
|
||||
<rect key="frame" x="0.0" y="28" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bFj-Hd-fwd" id="kDf-TZ-xhb">
|
||||
<frame key="frameInset" width="342" height="43.5"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="341" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="G8y-VE-YRu">
|
||||
<frame key="frameInset" minX="15" minY="12" width="31.5" height="19.5"/>
|
||||
<rect key="frame" x="16" y="12" width="31.5" height="19.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" white="0.0" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
|
||||
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" id="NNc-J4-xiE">
|
||||
<frame key="frameInset" minX="298.5" minY="12" width="41.5" height="19.5"/>
|
||||
<rect key="frame" x="298.5" y="12" width="41.5" height="19.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" type="system" pointSize="16"/>
|
||||
<color key="textColor" red="0.5568627451" green="0.5568627451" blue="0.57647058819999997" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
@@ -278,7 +165,7 @@
|
||||
</subviews>
|
||||
</tableViewCellContentView>
|
||||
<connections>
|
||||
<segue destination="iNr-Oe-muq" kind="show" identifier="EditPerson" id="Lgu-Yd-HSy"/>
|
||||
<segue destination="iNr-Oe-muq" kind="show" identifier="Edit" id="Lgu-Yd-HSy"/>
|
||||
</connections>
|
||||
</tableViewCell>
|
||||
</prototypes>
|
||||
@@ -291,20 +178,23 @@
|
||||
<barButtonItem title="Item" id="hMF-Rv-dAe"/>
|
||||
</toolbarItems>
|
||||
<navigationItem key="navigationItem" title="Hall Of Fame" id="QIv-M6-kT1">
|
||||
<barButtonItem key="rightBarButtonItem" systemItem="add" id="2bK-Fl-55Q"/>
|
||||
<barButtonItem key="leftBarButtonItem" systemItem="add" id="2bK-Fl-55Q">
|
||||
<connections>
|
||||
<segue destination="ein-Sr-i8w" kind="presentation" identifier="New" id="ehP-ZN-Nt4"/>
|
||||
</connections>
|
||||
</barButtonItem>
|
||||
</navigationItem>
|
||||
<simulatedToolbarMetrics key="simulatedBottomBarMetrics"/>
|
||||
<connections>
|
||||
<segue destination="ein-Sr-i8w" kind="presentation" identifier="NewPerson" id="7PC-xN-zD4"/>
|
||||
<outlet property="newPlayerButtonItem" destination="2bK-Fl-55Q" id="O9m-8s-oRL"/>
|
||||
</connections>
|
||||
</tableViewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="af5-Qo-AkD" userLabel="First Responder" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
<point key="canvasLocation" x="630" y="2254"/>
|
||||
<point key="canvasLocation" x="348" y="2071"/>
|
||||
</scene>
|
||||
</scenes>
|
||||
<inferredMetricsTieBreakers>
|
||||
<segue reference="7PC-xN-zD4"/>
|
||||
<segue reference="czF-1h-sYn"/>
|
||||
<segue reference="Lgu-Yd-HSy"/>
|
||||
</inferredMetricsTieBreakers>
|
||||
</document>
|
||||
@@ -1,10 +0,0 @@
|
||||
import UIKit
|
||||
|
||||
class DemoViewController: UITableViewController {
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(true)
|
||||
navigationController?.isToolbarHidden = true
|
||||
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Demo", style: .plain, target: nil, action: nil)
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,6 @@
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>GRDB Demo</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
@@ -18,6 +16,8 @@
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
@@ -33,6 +33,8 @@
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,234 +0,0 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
class PersonsViewController: UITableViewController {
|
||||
var personsController: FetchedRecordsController<Person>!
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
navigationItem.rightBarButtonItems = [
|
||||
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: .addPerson),
|
||||
editButtonItem
|
||||
]
|
||||
|
||||
personsController = try! FetchedRecordsController(dbQueue, request: personsSortedByScore)
|
||||
personsController.trackChanges(
|
||||
willChange: { [unowned self] _ in
|
||||
self.tableView.beginUpdates()
|
||||
},
|
||||
onChange: { [unowned self] (controller, record, change) in
|
||||
switch change {
|
||||
case .insertion(let indexPath):
|
||||
self.tableView.insertRows(at: [indexPath], with: .fade)
|
||||
|
||||
case .deletion(let indexPath):
|
||||
self.tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
|
||||
case .update(let indexPath, _):
|
||||
if let cell = self.tableView.cellForRow(at: indexPath) {
|
||||
self.configure(cell, at: indexPath)
|
||||
}
|
||||
|
||||
case .move(let indexPath, let newIndexPath, _):
|
||||
// Actually move cells around for more demo effect :-)
|
||||
let cell = self.tableView.cellForRow(at: indexPath)
|
||||
self.tableView.moveRow(at: indexPath, to: newIndexPath)
|
||||
if let cell = cell {
|
||||
self.configure(cell, at: newIndexPath)
|
||||
}
|
||||
|
||||
// A quieter animation:
|
||||
// self.tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
// self.tableView.insertRows(at: [newIndexPath], with: .fade)
|
||||
}
|
||||
},
|
||||
didChange: { [unowned self] _ in
|
||||
self.tableView.endUpdates()
|
||||
})
|
||||
try! personsController.performFetch()
|
||||
|
||||
configureToolbar()
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
navigationController?.isToolbarHidden = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PersonsViewController : PersonEditionViewControllerDelegate {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "EditPerson" {
|
||||
let person = personsController.record(at: tableView.indexPathForSelectedRow!)
|
||||
let controller = segue.destination as! PersonEditionViewController
|
||||
controller.title = person.name
|
||||
controller.person = person
|
||||
controller.delegate = self // we will save person when back button is tapped
|
||||
controller.cancelButtonHidden = true
|
||||
controller.commitButtonHidden = true
|
||||
}
|
||||
else if segue.identifier == "NewPerson" {
|
||||
setEditing(false, animated: true)
|
||||
let navigationController = segue.destination as! UINavigationController
|
||||
let controller = navigationController.viewControllers.first as! PersonEditionViewController
|
||||
controller.title = "New Person"
|
||||
controller.person = Person(name: "", score: 0)
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func addPerson(_ sender: AnyObject?) {
|
||||
performSegue(withIdentifier: "NewPerson", sender: sender)
|
||||
}
|
||||
|
||||
@IBAction func cancelPersonEdition(_ segue: UIStoryboardSegue) {
|
||||
// Person creation: cancel button was tapped
|
||||
}
|
||||
|
||||
@IBAction func commitPersonEdition(_ segue: UIStoryboardSegue) {
|
||||
// Person creation: commit button was tapped
|
||||
let controller = segue.source as! PersonEditionViewController
|
||||
controller.applyChanges()
|
||||
let person = controller.person!
|
||||
if !person.name.isEmpty {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func personEditionControllerDidComplete(_ controller: PersonEditionViewController) {
|
||||
// Person edition: back button was tapped
|
||||
controller.applyChanges()
|
||||
let person = controller.person!
|
||||
if !person.name.isEmpty {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - UITableViewDataSource
|
||||
|
||||
extension PersonsViewController {
|
||||
func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
|
||||
let person = personsController.record(at: indexPath)
|
||||
cell.textLabel?.text = person.name
|
||||
cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point"
|
||||
}
|
||||
|
||||
override func numberOfSections(in tableView: UITableView) -> Int {
|
||||
return personsController.sections.count
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return personsController.sections[section].numberOfRecords
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath)
|
||||
configure(cell, at: indexPath)
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
|
||||
// Delete the person
|
||||
let person = personsController.record(at: indexPath)
|
||||
try! dbQueue.inDatabase { db in
|
||||
_ = try person.delete(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - FetchedRecordsController Demo
|
||||
|
||||
extension PersonsViewController {
|
||||
|
||||
fileprivate func configureToolbar() {
|
||||
toolbarItems = [
|
||||
UIBarButtonItem(title: "Name ⬆︎", style: .plain, target: self, action: .sortByName),
|
||||
UIBarButtonItem(title: "Score ⬇︎", style: .plain, target: self, action: .sortByScore),
|
||||
UIBarButtonItem(title: "Randomize", style: .plain, target: self, action: .randomizeScores),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(title: "💣", style: .plain, target: self, action: .stressTest)
|
||||
]
|
||||
}
|
||||
|
||||
@IBAction func sortByName() {
|
||||
setEditing(false, animated: true)
|
||||
try! personsController.setRequest(personsSortedByName)
|
||||
}
|
||||
|
||||
@IBAction func sortByScore() {
|
||||
setEditing(false, animated: true)
|
||||
try! personsController.setRequest(personsSortedByScore)
|
||||
}
|
||||
|
||||
@IBAction func randomizeScores() {
|
||||
setEditing(false, animated: true)
|
||||
|
||||
try! dbQueue.inTransaction { db in
|
||||
for person in try Person.fetchAll(db) {
|
||||
person.score = Person.randomScore()
|
||||
try person.update(db)
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func stressTest() {
|
||||
setEditing(false, animated: true)
|
||||
|
||||
for _ in 0..<50 {
|
||||
DispatchQueue.global().async {
|
||||
try! dbQueue.inTransaction { db in
|
||||
if try Person.fetchCount(db) == 0 {
|
||||
// Insert persons
|
||||
for _ in 0..<8 {
|
||||
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
|
||||
}
|
||||
} else {
|
||||
// Insert a person
|
||||
if arc4random_uniform(2) == 0 {
|
||||
let person = Person(name: Person.randomName(), score: Person.randomScore())
|
||||
try person.insert(db)
|
||||
}
|
||||
// Delete a person
|
||||
if arc4random_uniform(2) == 0 {
|
||||
if let person = try Person.order(sql: "RANDOM()").fetchOne(db) {
|
||||
try person.delete(db)
|
||||
}
|
||||
}
|
||||
// Update some persons
|
||||
for person in try Person.fetchAll(db) {
|
||||
if arc4random_uniform(2) == 0 {
|
||||
person.score = Person.randomScore()
|
||||
try person.update(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// https://medium.com/swift-programming/swift-selector-syntax-sugar-81c8a8b10df3
|
||||
private extension Selector {
|
||||
static let addPerson = #selector(PersonsViewController.addPerson(_:))
|
||||
static let sortByName = #selector(PersonsViewController.sortByName)
|
||||
static let sortByScore = #selector(PersonsViewController.sortByScore)
|
||||
static let randomizeScores = #selector(PersonsViewController.randomizeScores)
|
||||
static let stressTest = #selector(PersonsViewController.stressTest)
|
||||
}
|
||||
|
||||
private let personsSortedByName = Person.order(Column("name"))
|
||||
private let personsSortedByScore = Person.order(Column("score").desc, Column("name"))
|
||||
@@ -1,49 +1,28 @@
|
||||
import GRDB
|
||||
|
||||
class Person: Record {
|
||||
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
init(name: String, score: Int) {
|
||||
self.name = name
|
||||
self.score = score
|
||||
super.init()
|
||||
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, score
|
||||
}
|
||||
|
||||
// MARK: Record overrides
|
||||
|
||||
override class var databaseTableName: String {
|
||||
return "persons"
|
||||
}
|
||||
|
||||
required init(row: Row) {
|
||||
id = row["id"]
|
||||
name = row["name"]
|
||||
score = row["score"]
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
override func encode(to container: inout PersistenceContainer) {
|
||||
container["id"] = id
|
||||
container["name"] = name
|
||||
container["score"] = score
|
||||
}
|
||||
|
||||
override func didInsert(with rowID: Int64, for column: String?) {
|
||||
/// Update player id after successful insertion
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
|
||||
// MARK: Random
|
||||
|
||||
}
|
||||
|
||||
extension Player {
|
||||
private static let names = ["Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David", "Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette", "Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl", "Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole", "Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul", "Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain", "Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann", "Zazie", "Zoé"]
|
||||
|
||||
class func randomName() -> String {
|
||||
static func randomName() -> String {
|
||||
return names[Int(arc4random_uniform(UInt32(names.count)))]
|
||||
}
|
||||
|
||||
class func randomScore() -> Int {
|
||||
static func randomScore() -> Int {
|
||||
return 10 * Int(arc4random_uniform(101))
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
import UIKit
|
||||
|
||||
protocol PersonEditionViewControllerDelegate: class {
|
||||
func personEditionControllerDidComplete(_ controller: PersonEditionViewController)
|
||||
protocol PlayerEditionViewControllerDelegate: class {
|
||||
func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController)
|
||||
}
|
||||
|
||||
class PersonEditionViewController: UITableViewController {
|
||||
weak var delegate: PersonEditionViewControllerDelegate?
|
||||
var person: Person! { didSet { configureView() } }
|
||||
var cancelButtonHidden: Bool = false { didSet { configureView() } }
|
||||
class PlayerEditionViewController: UITableViewController {
|
||||
weak var delegate: PlayerEditionViewControllerDelegate?
|
||||
var player: Player! { didSet { configureView() } }
|
||||
var commitButtonHidden: Bool = false { didSet { configureView() } }
|
||||
|
||||
@IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem!
|
||||
@@ -17,37 +16,27 @@ class PersonEditionViewController: UITableViewController {
|
||||
@IBOutlet fileprivate weak var scoreCell: UITableViewCell!
|
||||
@IBOutlet fileprivate weak var scoreTextField: UITextField!
|
||||
|
||||
func applyChanges() {
|
||||
if let name = nameTextField.text, !name.isEmpty {
|
||||
person.name = name
|
||||
}
|
||||
person.score = scoreTextField.text.flatMap { Int($0) } ?? 0
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
configureView()
|
||||
}
|
||||
|
||||
private func configureView() {
|
||||
fileprivate func configureView() {
|
||||
guard isViewLoaded else { return }
|
||||
|
||||
nameTextField.text = person.name
|
||||
if person.score == 0 && person.id == nil {
|
||||
nameTextField.text = player.name
|
||||
|
||||
if player.score == 0 && player.id == nil {
|
||||
scoreTextField.text = ""
|
||||
} else {
|
||||
scoreTextField.text = "\(person.score)"
|
||||
scoreTextField.text = "\(player.score)"
|
||||
}
|
||||
|
||||
if cancelButtonHidden {
|
||||
if commitButtonHidden {
|
||||
navigationItem.leftBarButtonItem = nil
|
||||
} else {
|
||||
navigationItem.leftBarButtonItem = cancelBarButtonItem
|
||||
}
|
||||
|
||||
if cancelButtonHidden {
|
||||
navigationItem.rightBarButtonItem = nil
|
||||
} else {
|
||||
navigationItem.leftBarButtonItem = cancelBarButtonItem
|
||||
navigationItem.rightBarButtonItem = commitBarButtonItem
|
||||
}
|
||||
}
|
||||
@@ -56,7 +45,7 @@ class PersonEditionViewController: UITableViewController {
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PersonEditionViewController {
|
||||
extension PlayerEditionViewController {
|
||||
|
||||
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
|
||||
// Force keyboard to dismiss early
|
||||
@@ -64,12 +53,19 @@ extension PersonEditionViewController {
|
||||
return true
|
||||
}
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "Commit" {
|
||||
applyChanges()
|
||||
}
|
||||
}
|
||||
|
||||
override func willMove(toParentViewController parent: UIViewController?) {
|
||||
super.willMove(toParentViewController: parent)
|
||||
|
||||
if parent == nil {
|
||||
// Self is popping from its navigation controller
|
||||
delegate?.personEditionControllerDidComplete(self)
|
||||
applyChanges()
|
||||
delegate?.playerEditionControllerDidComplete(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +74,7 @@ extension PersonEditionViewController {
|
||||
|
||||
// MARK: - Form
|
||||
|
||||
extension PersonEditionViewController: UITextFieldDelegate {
|
||||
extension PlayerEditionViewController: UITextFieldDelegate {
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
@@ -101,4 +97,13 @@ extension PersonEditionViewController: UITextFieldDelegate {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private func applyChanges() {
|
||||
guard var player = self.player else {
|
||||
return
|
||||
}
|
||||
player.name = nameTextField.text ?? ""
|
||||
player.score = scoreTextField.text.flatMap { Int($0) } ?? 0
|
||||
self.player = player
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
class PlayersViewController: UITableViewController {
|
||||
enum PlayerOrdering {
|
||||
case byName
|
||||
case byScore
|
||||
|
||||
var request: QueryInterfaceRequest<Player> {
|
||||
switch self {
|
||||
case .byName:
|
||||
return Player.order(Player.Columns.name)
|
||||
case .byScore:
|
||||
return Player.order(Player.Columns.score.desc, Player.Columns.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var playersController: FetchedRecordsController<Player>!
|
||||
var playerOrdering: PlayerOrdering = .byScore {
|
||||
didSet {
|
||||
try! playersController.setRequest(playerOrdering.request)
|
||||
configureNavigationItem()
|
||||
}
|
||||
}
|
||||
|
||||
@IBOutlet weak var newPlayerButtonItem: UIBarButtonItem!
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
configureTableView()
|
||||
configureToolbar()
|
||||
configureNavigationItem()
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
navigationController?.isToolbarHidden = false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PlayersViewController : PlayerEditionViewControllerDelegate {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "Edit" {
|
||||
let player = playersController.record(at: tableView.indexPathForSelectedRow!)
|
||||
let controller = segue.destination as! PlayerEditionViewController
|
||||
controller.title = player.name
|
||||
controller.player = player
|
||||
controller.delegate = self // See playerEditionControllerDidComplete
|
||||
controller.commitButtonHidden = true
|
||||
}
|
||||
else if segue.identifier == "New" {
|
||||
setEditing(false, animated: true)
|
||||
let navigationController = segue.destination as! UINavigationController
|
||||
let controller = navigationController.viewControllers.first as! PlayerEditionViewController
|
||||
controller.title = "New Player"
|
||||
controller.player = Player(id: nil, name: "", score: 0)
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
|
||||
// Player creation: cancel button was tapped
|
||||
}
|
||||
|
||||
@IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) {
|
||||
// Player creation: commit button was tapped
|
||||
let controller = segue.source as! PlayerEditionViewController
|
||||
try! dbQueue.write { db in
|
||||
try controller.player.save(db)
|
||||
}
|
||||
}
|
||||
|
||||
func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController) {
|
||||
// Player edition: user has finished editing the player
|
||||
try! dbQueue.write { db in
|
||||
try controller.player.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - UITableViewDataSource
|
||||
|
||||
extension PlayersViewController {
|
||||
private func configureTableView() {
|
||||
playersController = try! FetchedRecordsController(dbQueue, request: playerOrdering.request)
|
||||
|
||||
playersController.trackChanges(
|
||||
willChange: { [unowned self] _ in
|
||||
self.tableView.beginUpdates()
|
||||
},
|
||||
onChange: { [unowned self] (controller, record, change) in
|
||||
switch change {
|
||||
case .insertion(let indexPath):
|
||||
self.tableView.insertRows(at: [indexPath], with: .fade)
|
||||
|
||||
case .deletion(let indexPath):
|
||||
self.tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
|
||||
case .update(let indexPath, _):
|
||||
if let cell = self.tableView.cellForRow(at: indexPath) {
|
||||
self.configure(cell, at: indexPath)
|
||||
}
|
||||
|
||||
case .move(let indexPath, let newIndexPath, _):
|
||||
// Actually move cells around for more demo effect :-)
|
||||
let cell = self.tableView.cellForRow(at: indexPath)
|
||||
self.tableView.moveRow(at: indexPath, to: newIndexPath)
|
||||
if let cell = cell {
|
||||
self.configure(cell, at: newIndexPath)
|
||||
}
|
||||
|
||||
// A quieter animation:
|
||||
// self.tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
// self.tableView.insertRows(at: [newIndexPath], with: .fade)
|
||||
}
|
||||
},
|
||||
didChange: { [unowned self] _ in
|
||||
self.tableView.endUpdates()
|
||||
})
|
||||
|
||||
try! playersController.performFetch()
|
||||
}
|
||||
|
||||
override func numberOfSections(in tableView: UITableView) -> Int {
|
||||
return playersController.sections.count
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return playersController.sections[section].numberOfRecords
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
|
||||
configure(cell, at: indexPath)
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
|
||||
// Delete the player
|
||||
let player = playersController.record(at: indexPath)
|
||||
try! dbQueue.write { db in
|
||||
_ = try player.delete(db)
|
||||
}
|
||||
}
|
||||
|
||||
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
|
||||
let player = playersController.record(at: indexPath)
|
||||
if player.name.isEmpty {
|
||||
cell.textLabel?.text = "(anonymous)"
|
||||
} else {
|
||||
cell.textLabel?.text = player.name
|
||||
}
|
||||
cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
extension PlayersViewController {
|
||||
private func configureNavigationItem() {
|
||||
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
|
||||
|
||||
switch playerOrdering {
|
||||
case .byScore:
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
title: "Score ⬇︎",
|
||||
style: .plain,
|
||||
target: self, action: #selector(sortByName))
|
||||
case .byName:
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
title: "Name ⬆︎",
|
||||
style: .plain,
|
||||
target: self, action: #selector(sortByScore))
|
||||
}
|
||||
}
|
||||
|
||||
private func configureToolbar() {
|
||||
toolbarItems = [
|
||||
UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)),
|
||||
]
|
||||
}
|
||||
|
||||
@IBAction func sortByName() {
|
||||
setEditing(false, animated: true)
|
||||
playerOrdering = .byName
|
||||
}
|
||||
|
||||
@IBAction func sortByScore() {
|
||||
setEditing(false, animated: true)
|
||||
playerOrdering = .byScore
|
||||
}
|
||||
|
||||
@IBAction func deletePlayers() {
|
||||
setEditing(false, animated: true)
|
||||
try! dbQueue.write { db in
|
||||
_ = try Player.deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func refresh() {
|
||||
setEditing(false, animated: true)
|
||||
refreshPlayers()
|
||||
}
|
||||
|
||||
@IBAction func stressTest() {
|
||||
setEditing(false, animated: true)
|
||||
for _ in 0..<50 {
|
||||
DispatchQueue.global().async {
|
||||
self.refreshPlayers()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func refreshPlayers() {
|
||||
try! dbQueue.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
// Insert new random players
|
||||
for _ in 0..<8 {
|
||||
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
|
||||
try player.insert(db)
|
||||
}
|
||||
} else {
|
||||
// Insert a player
|
||||
if arc4random_uniform(2) == 0 {
|
||||
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
|
||||
try player.insert(db)
|
||||
}
|
||||
// Delete a random player
|
||||
if arc4random_uniform(2) == 0 {
|
||||
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
|
||||
}
|
||||
// Update some players
|
||||
for var player in try Player.fetchAll(db) where arc4random_uniform(2) == 0 {
|
||||
player.score = Player.randomScore()
|
||||
try player.update(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
class SimplePersonsViewController: UITableViewController {
|
||||
var persons: [Person]!
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
navigationItem.rightBarButtonItems = [
|
||||
UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(SimplePersonsViewController.addPerson(_:))),
|
||||
editButtonItem
|
||||
]
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
loadPersons()
|
||||
tableView.reloadData()
|
||||
}
|
||||
|
||||
private func loadPersons() {
|
||||
persons = try! dbQueue.inDatabase { db in
|
||||
try Person.order(Column("score").desc, Column("name")).fetchAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension SimplePersonsViewController : PersonEditionViewControllerDelegate {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "EditPerson" {
|
||||
let person = persons[tableView.indexPathForSelectedRow!.row]
|
||||
let controller = segue.destination as! PersonEditionViewController
|
||||
controller.title = person.name
|
||||
controller.person = person
|
||||
controller.delegate = self // we will save person when back button is tapped
|
||||
controller.cancelButtonHidden = true
|
||||
controller.commitButtonHidden = true
|
||||
}
|
||||
else if segue.identifier == "NewPerson" {
|
||||
setEditing(false, animated: true)
|
||||
let navigationController = segue.destination as! UINavigationController
|
||||
let controller = navigationController.viewControllers.first as! PersonEditionViewController
|
||||
controller.title = "New Person"
|
||||
controller.person = Person(name: "", score: 0)
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func addPerson(_ sender: AnyObject?) {
|
||||
performSegue(withIdentifier: "NewPerson", sender: sender)
|
||||
}
|
||||
|
||||
@IBAction func cancelPersonEdition(_ segue: UIStoryboardSegue) {
|
||||
// Person creation: cancel button was tapped
|
||||
}
|
||||
|
||||
@IBAction func commitPersonEdition(_ segue: UIStoryboardSegue) {
|
||||
// Person creation: commit button was tapped
|
||||
let controller = segue.source as! PersonEditionViewController
|
||||
controller.applyChanges()
|
||||
let person = controller.person!
|
||||
if !person.name.isEmpty {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func personEditionControllerDidComplete(_ controller: PersonEditionViewController) {
|
||||
// Person edition: back button was tapped
|
||||
controller.applyChanges()
|
||||
let person = controller.person!
|
||||
if !person.name.isEmpty {
|
||||
try! dbQueue.inDatabase { db in
|
||||
try person.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - UITableViewDataSource
|
||||
|
||||
extension SimplePersonsViewController {
|
||||
func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
|
||||
let person = persons[indexPath.row]
|
||||
cell.textLabel?.text = person.name
|
||||
cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point"
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
return persons.count
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath)
|
||||
configure(cell, at: indexPath)
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
|
||||
// Delete the person
|
||||
let person = persons[indexPath.row]
|
||||
try! dbQueue.inDatabase { db in
|
||||
_ = try person.delete(db)
|
||||
}
|
||||
persons.remove(at: indexPath.row)
|
||||
tableView.deleteRows(at: [indexPath], with: .fade)
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ Custom SQLite Builds
|
||||
|
||||
By default, GRDB uses the version of SQLite that ships with the target operating system.
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.22.0](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.23.0](https://www.sqlite.org/changes.html).**
|
||||
|
||||
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
|
||||
|
||||
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
```sh
|
||||
cd [GRDB directory]
|
||||
git checkout v2.10.0
|
||||
git checkout v3.0.0-beta.1
|
||||
git submodule update --init SQLiteCustom/src
|
||||
````
|
||||
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
Migrating From GRDB 2 to GRDB 3
|
||||
===============================
|
||||
|
||||
GRDB 3 comes with new features, but also a few breaking changes, and a set of updated good practices. This guide aims at helping you upgrading your applications.
|
||||
|
||||
**For all users**
|
||||
|
||||
- [How To Upgrade]
|
||||
- [Swift 4.1 Required]
|
||||
- [iOS 8 Sunsetting]
|
||||
- [Database Schema Recommendations]
|
||||
- [Record Protocols Renaming]
|
||||
- [Columns Definition]
|
||||
|
||||
**By topic**
|
||||
|
||||
- [If You Use Database Queues]
|
||||
- [If You Use Database Pools]
|
||||
- [If You Use Database Snapshots]
|
||||
- [If You Use Record Types]
|
||||
- [If You Use Custom Requests]
|
||||
- [If You Use RxGRDB]
|
||||
- [Notable Documentation Updates]
|
||||
|
||||
|
||||
## How to Upgrade
|
||||
|
||||
Target the "GRDB3" branch:
|
||||
|
||||
### CocoaPods
|
||||
|
||||
Update your Podfile:
|
||||
|
||||
```ruby
|
||||
pod 'GRDB.swift', git: 'https://github.com/groue/GRDB.swift', branch: 'GRDB3'
|
||||
```
|
||||
|
||||
### Swift Package Manager
|
||||
|
||||
Update your Package.swift file:
|
||||
|
||||
```swift
|
||||
let package = Package(
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/groue/GRDB.swift.git", .branchItem("GRDB3"))
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
### Manually
|
||||
|
||||
Update your local copy of GRDB:
|
||||
|
||||
```sh
|
||||
git checkout GRDB3
|
||||
git pull
|
||||
```
|
||||
|
||||
## Swift 4.1 Required
|
||||
|
||||
GRDB 3 uses [conditional conformances], introduced in Swift 4.1. It can only be built on Xcode 9.3+.
|
||||
|
||||
|
||||
## iOS 8 Sunsetting
|
||||
|
||||
GRDB 3 is only tested on iOS 9+, due to a limitation in Xcode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported.
|
||||
|
||||
|
||||
## Database Schema Recommendations
|
||||
|
||||
GRDB 2 was totally schema-agnostic, and would gladly accept any database.
|
||||
|
||||
GRDB 3 still accepts any database, but brings two schema recommendations:
|
||||
|
||||
- :bulb: Integer primary keys should be auto-incremented, in order to avoid any row id to be reused.
|
||||
|
||||
When ids can be reused, your app and [database observation tools] may think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not.
|
||||
|
||||
GRDB 3 thus comes with a new good practice: use the `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key:
|
||||
|
||||
```diff
|
||||
try db.create(table: "author") { t in
|
||||
- t.column("id", .integer).primaryKey() // GRDB 2
|
||||
+ t.autoIncrementedPrimaryKey("id") // GRDB 3 recommendation
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
- :bulb: Database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, 'httpRequest'.
|
||||
|
||||
This will help you using the new [Associations] feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration.
|
||||
|
||||
This convention is applied by the default implementation of the `TableRecord.databaseTableName`: see [If You Use Record Types] below.
|
||||
|
||||
Since you are reading this guide, your application has already defined its database schema. You can migrate it in order to apply the new recommendations, if needed. Below is a sample code that uses [DatabaseMigrator], the recommended tool for managing your database schema:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
// Existing GRDB 2 migration:
|
||||
migrator.registerMigration("initial") { db in
|
||||
try db.create(table: "authors") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.create(table: "books") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("authorId", .integer).notNull().references("authors")
|
||||
t.column("title", .text).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
// New GRDB 3 migration:
|
||||
// - Rename tables so that they look like Swift identifiers (singular and camelCased)
|
||||
// - Make integer primary keys auto-incremented
|
||||
//
|
||||
// Since several tables are recreated from scratch, referential integrity
|
||||
// constraints may break during the process. The
|
||||
// registerMigrationWithDeferredForeignKeyCheck method makes sure that foreign
|
||||
// key checks are temporarily disabled, and checked at the end:
|
||||
migrator.registerMigrationWithDeferredForeignKeyCheck("GRDB3") { db in
|
||||
try db.create(table: "author") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("authorId", .integer).notNull().references("author")
|
||||
t.column("title", .text).notNull()
|
||||
}
|
||||
try db.execute("""
|
||||
INSERT INTO author SELECT * FROM authors;
|
||||
INSERT INTO book SELECT * FROM books;
|
||||
""")
|
||||
try db.drop(table: "authors")
|
||||
try db.drop(table: "books")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Record Protocols Renaming
|
||||
|
||||
GRDB 3 has renamed the [record protocols]:
|
||||
|
||||
- `RowConvertible` -> `FetchableRecord`
|
||||
- `TableMapping` -> `TableRecord`
|
||||
- `Persistable` -> `PersistableRecord`
|
||||
- `MutablePersistable` -> `MutablePersistableRecord`
|
||||
|
||||
After upgrading, build your project: the compiler will guide you through the renaming by the way of fixits.
|
||||
|
||||
|
||||
## Columns Definition
|
||||
|
||||
GRDB 2 has you define columns of the query interface with the Column type:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
let nameColumn = Column("name")
|
||||
let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
|
||||
```
|
||||
|
||||
A recommended practice was to define enum namespaces in record types:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
struct Player: RowConvertible, TableMapping {
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
static let score = Column("score")
|
||||
}
|
||||
|
||||
init(row: Row) {
|
||||
id = row[Columns.id]
|
||||
name = row[Columns.name]
|
||||
score = row[Columns.score]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In GRDB 3, `Column` is still there, but a new `ColumnExpression` protocol has been introduced in order to streamline column enums:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
struct Player: FetchableRecord, TableRecord {
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, score
|
||||
}
|
||||
|
||||
init(row: Row) {
|
||||
id = row[Columns.id]
|
||||
name = row[Columns.name]
|
||||
score = row[Columns.score]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol when you define a custom column type:
|
||||
|
||||
```swift
|
||||
struct TypedColumn: ColumnExpression {
|
||||
var name: String
|
||||
var sqlType: String
|
||||
}
|
||||
let nameColumn = TypedColumn(name: "name", sqlType: "VARCHAR")
|
||||
let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
|
||||
```
|
||||
|
||||
|
||||
## If You Use Database Queues
|
||||
|
||||
With GRDB 2, you used to access the database through the `inDatabase` or `inTransaction` [DatabaseQueue] methods:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
let players = try dbQueue.inDatabase { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try player.updateChanges(db)
|
||||
}
|
||||
|
||||
var balance: Amount! = nil
|
||||
try dbQueue.inTransaction { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
balance = try sourceAccount.fetchBalance(db)
|
||||
return .commit
|
||||
}
|
||||
```
|
||||
|
||||
The code above still runs, unchanged, in GRDB 3.
|
||||
|
||||
Yet it is now recommended that you use the `read` and `write` methods instead:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
let players = try dbQueue.read { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try player.updateChanges(db)
|
||||
}
|
||||
|
||||
let balance = try dbQueue.write { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
return try sourceAccount.fetchBalance(db)
|
||||
}
|
||||
```
|
||||
|
||||
The purpose of the new `read` and `write` methods is to soothe the "transaction mental load" of previous versions of GRDB, a legacy of the [FMDB] heritage. All developers can *forget* to open transactions, with the unfortunate consequence that the database may end up containing inconsistent values. Experienced developers may *wonder* whether they should open transactions or not, even when this doesn't matter a lot.
|
||||
|
||||
With GRDB 3, use `read` when you need to read values. It's impossible to write within a `read` block, which means that you can be sure that no unwanted side effect can happen.
|
||||
|
||||
When you need to write, use `write`: your database changes are automatically wrapped in a transaction, with the guarantee that all changes are written to disk, or, should any error happen, none at all.
|
||||
|
||||
Of course, precise transaction handling sometimes matter. Check the updated [Transactions and Savepoints] chapter.
|
||||
|
||||
|
||||
## If You Use Database Pools
|
||||
|
||||
With GRDB 2, you used to access the database through the `read`, `write` or `writeInTransaction` [DatabasePool] methods:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
let players = try dbPool.read { db in
|
||||
try Player.fetchAll(db)
|
||||
}
|
||||
|
||||
try dbPool.write { db in
|
||||
try player.updateChanges(db)
|
||||
}
|
||||
|
||||
var balance: Amount! = nil
|
||||
try dbPool.writeInTransaction { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
balance = try sourceAccount.fetchBalance(db)
|
||||
return .commit
|
||||
}
|
||||
```
|
||||
|
||||
In GRDB 3, the `write` method has changed: it now automatically wraps your database changes in a transaction, which means that the last block can be rewritten as below:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
let balance = try dbPool.write { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
return try sourceAccount.fetchBalance(db)
|
||||
}
|
||||
```
|
||||
|
||||
Side effect: you can no longer open explicit transactions inside a `write` block:
|
||||
|
||||
```swift
|
||||
// GRDB 2: OK
|
||||
// GRDB 3: SQLite error 1 with statement `BEGIN DEFERRED TRANSACTION`:
|
||||
// cannot start a transaction within a transaction
|
||||
try dbPool.write { db in
|
||||
try db.inTransaction { ... }
|
||||
}
|
||||
```
|
||||
|
||||
When precise transaction handling is needed, check the updated [Transactions and Savepoints] chapter.
|
||||
|
||||
The purpose of this change is to prevent an easy misuse of database pools in previous GRDB versions. Unless writes were wrapped inside an explicit transactions, concurrent reads could see an inconsistent state of the database:
|
||||
|
||||
```swift
|
||||
// GRDB 2: unsafe
|
||||
// GRDB 3: safe
|
||||
try dbPool.write { db in
|
||||
try Credit(destinationAccout, amount).insert(db)
|
||||
try Debit(sourceAccount, amount).insert(db)
|
||||
}
|
||||
```
|
||||
|
||||
Since `write` now wraps your changes in a transaction, you have the guarantee that concurrent reads can't see them until they are all written to disk.
|
||||
|
||||
|
||||
## If You Use Database Snapshots
|
||||
|
||||
With GRDB 2, you used to create [database snapshots] with the `makeSnaphot` [DatabasePool] method. For example:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
let snapshot: DatabaseSnapshot = try dbPool.write { db in
|
||||
try Player.deleteAll()
|
||||
return dbPool.makeSnapshot()
|
||||
}
|
||||
|
||||
// Guaranteed to be zero
|
||||
let count = try snapshot.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
GRDB 3 will crash the above code on the `makeSnapshot()` line, with a fatal error: "makeSnapshot() must not be called from inside a transaction."
|
||||
|
||||
To avoid this error, you will need [precise transaction handling]:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in
|
||||
try Player.deleteAll()
|
||||
return dbPool.makeSnapshot()
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## If You Use Record Types
|
||||
|
||||
Record types that adopt the former TableMapping protocol, renamed TableRecord, used to declare their table name:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
struct Place: TableMapping {
|
||||
static let databaseTableName = "place"
|
||||
}
|
||||
print(Place.databaseTableName) // print "place"
|
||||
```
|
||||
|
||||
With GRDB 3, the `databaseTableName` property gets a default implementation:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
struct Place: TableRecord { }
|
||||
print(Place.databaseTableName) // print "place"
|
||||
```
|
||||
|
||||
That default name follows the [Database Schema Recommendations]: it is singular, camel-cased, and looks like a Swift identifier:
|
||||
|
||||
- Place: `place`
|
||||
- Country: `country`
|
||||
- PostalAddress: `postalAddress`
|
||||
- HTTPRequest: `httpRequest`
|
||||
- TOEFL: `toefl`
|
||||
|
||||
When you subclass the Record class, the Swift compiler won't let you profit from this default name: you have to keep on providing an explicit table name:
|
||||
|
||||
```swift
|
||||
// GRDB 2 and GRDB 3
|
||||
class Place: Record {
|
||||
override var databaseTableName: String {
|
||||
return "place"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## If You Use Custom Requests
|
||||
|
||||
[Custom requests] let you escape the limitations of the [query interface], when it can not generate the requests you need.
|
||||
|
||||
You may, for example, use `SQLRequest`:
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
extension Player {
|
||||
static func filter(color: Color) -> AnyTypedRequest<Player> {
|
||||
let sql = "SELECT * FROM players WHERE color = ?"
|
||||
let request = SQLRequest(sql, arguments: [color])
|
||||
return request.asRequest(of: Player.self)
|
||||
}
|
||||
}
|
||||
|
||||
let players = try Player.filter(color: .red).fetchAll(db)
|
||||
```
|
||||
|
||||
The `AnyTypedRequest` type is no longer available, and `SQLRequest` is now a generic type:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
extension Player {
|
||||
static func filter(color: Color) -> SQLRequest<Player> {
|
||||
let sql = "SELECT * FROM players WHERE color = ?"
|
||||
return SQLRequest(sql, arguments: [color])
|
||||
}
|
||||
}
|
||||
|
||||
let players = try Player.filter(color: .red).fetchAll(db)
|
||||
```
|
||||
|
||||
See the updated [Custom Requests](../README.md#custom-requests) chapter for more information.
|
||||
|
||||
|
||||
## If You Use RxGRDB
|
||||
|
||||
To install the GRDB 3 flavor of RxGRDB, update your Podfile:
|
||||
|
||||
```ruby
|
||||
pod 'RxGRDB', git: 'https://github.com/groue/RxGRDB', branch: 'GRDB3'
|
||||
```
|
||||
|
||||
Some APIs have slighly changed. Did you track multiple requests at the same time with "fetch tokens"?
|
||||
|
||||
```swift
|
||||
// GRDB 2
|
||||
dbQueue.rx
|
||||
.fetchTokens(in: [...])
|
||||
.mapFetch { db in ... }
|
||||
.subscribe(...)
|
||||
```
|
||||
|
||||
Now you'll write instead:
|
||||
|
||||
```swift
|
||||
// GRDB 3
|
||||
dbQueue.rx
|
||||
.fetch(from: [...]) { db in ... }
|
||||
.subscribe(...)
|
||||
```
|
||||
|
||||
It's just a syntactic change, without any impact on the runtime.
|
||||
|
||||
RxGRDB for GRDB 3 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition.
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
// GRDB 2: Track a team and its players
|
||||
let teamId = 1
|
||||
let teamRequest = Team.filter(key: teamId)
|
||||
let playersRequest = Player.filter(teamId: teamId)
|
||||
dbQueue.rx
|
||||
.fetchTokens(in: [teamRequest, playersRequest])
|
||||
.mapFetch { db -> TeamInfo? in
|
||||
guard let team = try teamRequest.fetchOne(db) else {
|
||||
return nil
|
||||
}
|
||||
let players = try playersRequest.fetchAll(db)
|
||||
return TeamInfo(team: team, players: players)
|
||||
}
|
||||
.subscribe(onNext: { teamInfo: TeamInfo? in
|
||||
...
|
||||
})
|
||||
|
||||
// GRDB 3: Track a team and its players
|
||||
struct TeamInfoRequest: DatabaseRegionConvertible { ... }
|
||||
let request = TeamInfoRequest(teamId: 1)
|
||||
dbQueue.rx
|
||||
.fetch(from: [request]) { try request.fetchOne($0) }
|
||||
.subscribe(onNext: { teamInfo: TeamInfo? in
|
||||
...
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
## Notable Documentation Updates
|
||||
|
||||
If you have time, you may dig deeper in GRDB 3 with those updated documentation chapter:
|
||||
|
||||
- [Database Queues](../README.md#database-queues): focus on the new `read` and `write` methods.
|
||||
- [Transactions and Savepoints](../README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature.
|
||||
- [ScopeAdapter](../README.md#scopeadapter): do you use row adapters? If so, have a look.
|
||||
- [Examples of Record Definitions](../README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass).
|
||||
- [SQL Operators](../README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`.
|
||||
- [Custom Requests](../README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter.
|
||||
- [Migrations](../README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests).
|
||||
|
||||
|
||||
[How To Upgrade]: #how-to-upgrade
|
||||
[Database Schema Recommendations]: #database-schema-recommendations
|
||||
[Record Protocols Renaming]: #record-protocols-renaming
|
||||
[Columns Definition]: #columns-definition
|
||||
[Swift 4.1 Required]: #swift-41-required
|
||||
[iOS 8 Sunsetting]: #ios-8-sunsetting
|
||||
[If You Use Database Queues]: #if-you-use-database-queues
|
||||
[If You Use Database Pools]: #if-you-use-database-pools
|
||||
[If You Use Database Snapshots]: #if-you-use-database-snapshots
|
||||
[If You Use Record Types]: #if-you-use-record-types
|
||||
[If You Use Custom Requests]: #if-you-use-custom-requests
|
||||
[If You Use RxGRDB]: #if-you-use-rxgrdb
|
||||
[Notable Documentation Updates]: #notable-documentation-updates
|
||||
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[Associations]: AssociationsBasics.md
|
||||
[DatabaseMigrator]: ../README.md#migrations
|
||||
[database observation tools]: ../README.md#database-changes-observation
|
||||
[Transactions and Savepoints]: ../README.md#transactions-and-savepoints
|
||||
[precise transaction handling]: ../README.md#transactions-and-savepoints
|
||||
[DatabaseQueue]: ../README.md#database-queues
|
||||
[DatabasePool]: ../README.md#database-pools
|
||||
[database snapshots]: ../README.md#database-snapshots
|
||||
[FMDB]: http://github.com/ccgus/fmdb
|
||||
[record protocols]: ../README.md#record-protocols-overview
|
||||
[Custom requests]: ../README.md#custom-requests
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[DatabaseRegionConvertible]: https://github.com/groue/RxGRDB/blob/GRDB3/README.md#databaseregionconvertible-protocol
|
||||
[conditional conformances]: https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md
|
||||
@@ -0,0 +1,326 @@
|
||||
Good Practices for Designing Record Types
|
||||
=========================================
|
||||
|
||||
This guide aims at helping you leverage the best of GRDB [records] and [associations].
|
||||
|
||||
Since GRDB sits right between low-level libraries like SQLite itself or [FMDB], and high-level ORM like [Core Data] or [Realm], you may face questions when designing the model layer of your application.
|
||||
|
||||
To support this guide, we'll design a simply library application that lets the user crawl through books and their authors.
|
||||
|
||||
- [Trust SQLite More Than Yourself]
|
||||
- [Record Types are Responsible for Their Tables]
|
||||
- [Compose Records]
|
||||
- [Fetch In Time]
|
||||
- [Observe the Database and Refetch when Needed]
|
||||
|
||||
|
||||
## Trust SQLite More Than Yourself
|
||||
|
||||
SQLite is a robust database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk.
|
||||
|
||||
This is important because we developers write bugs, and some of them will ship in the wild, affecting your application users. But thanks to SQLite, those bugs will be unable to corrupt your precious users' data. All it takes a robust **database schema**.
|
||||
|
||||
For example, if we were to define a [migration] that sets up our library database, made of books and their authors, we could write:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createLibrary") { db in
|
||||
try db.create(table: "author") { t in // (1)
|
||||
t.autoIncrementedPrimaryKey("id") // (2)
|
||||
t.column("name", .text).notNull() // (3)
|
||||
}
|
||||
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("title", .text) // (4)
|
||||
t.column("authorId", .integer) // (5)
|
||||
.notNull() // (6)
|
||||
.indexed() // (7)
|
||||
.references("author", onDelete: .cascade) // (8)
|
||||
}
|
||||
}
|
||||
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
1. Our database table names follow the GRDB 3 recommendation: generally speaking they should be singular, and camel-cased. Make them look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
|
||||
2. Each author has a unique id.
|
||||
3. An author must have a name.
|
||||
4. A book must have a title.
|
||||
5. The `book.authorId` column is used to link a book to the author it belongs to.
|
||||
6. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
|
||||
7. The `book.authorId` column is indexed in order to ease the selection of an author's books.
|
||||
8. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
|
||||
|
||||
Thanks to this database schema, you can be confident so no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc.
|
||||
|
||||
> :bulb: **Tip**: Don't look at your local SQLite database as you look at the JSON you load from a remote server. You can't control the JSON, its format and content: your application must defend itself against wacky servers. But you can control the database. Put the database on your side, make it trustable. Learn about relational databases, and how they can help you guarantee the quality of your application data. Put as much energy as you can in the proper definition of your database schema.
|
||||
>
|
||||
> :bulb: **Tip**: Plan early for future versions of your application, and use [migrations].
|
||||
>
|
||||
> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with **strings**:
|
||||
>
|
||||
> ```swift
|
||||
> migrator.registerMigration("createLibrary") { db in
|
||||
> // RECOMMENDED
|
||||
> try db.create(table: "author") { t in
|
||||
> t.autoIncrementedPrimaryKey("id")
|
||||
> ...
|
||||
> }
|
||||
>
|
||||
> // NOT RECOMMENDED
|
||||
> try db.create(table: Author.databaseTableName) { t in
|
||||
> t.autoIncrementedPrimaryKey(Author.Columns.id.name)
|
||||
> ...
|
||||
> }
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> By using strings, you make sure that you will not have to change the Swift code of your migrations in the future. Even if author columns eventually change. Even if the Author type eventually gets replaced with another type. Even when your startup eventually pivots and starts selling pet food. A good migration that never changes is easy to test once and for good. A good migration that never changes will run smoothly on all devices in the wild, even if a user upgrades straight from version 1.0 to version 5.0 of your application.
|
||||
>
|
||||
> So make sure that migrations don't use application types and values: migrations should talk to the database, only to the database, and use the database language: **strings**.
|
||||
|
||||
|
||||
## Record Types are Responsible for Their Tables
|
||||
|
||||
Define one record type per database table.
|
||||
|
||||
In this sample code, we'll use codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
|
||||
|
||||
```swift
|
||||
struct Author: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
|
||||
struct Book: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`. See [record protocols] for more information.
|
||||
|
||||
> :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property.
|
||||
>
|
||||
> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(with:for:)` method:
|
||||
>
|
||||
> ```swift
|
||||
> var author = Author(id: nil, name: "Hermann Melville")
|
||||
> try author.insert(db)
|
||||
> print(author.id) // Some non-nil id
|
||||
> ```
|
||||
|
||||
Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*.
|
||||
|
||||
Applying the **[Single Responsibility Principle]** has a consequence: don't even try to have an author responsible for its books. Don't add a `books: [Book]` property in Author. Don't let Author write in the `book` table. When a new fellow coworker joins your team and asks you "who is saving books in the database?", you don't want to answer "it depends." You want to confidently answer: "the Book type".
|
||||
|
||||
> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table.
|
||||
|
||||
|
||||
## Compose Records
|
||||
|
||||
Now that we have two types for authors and books, we'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
|
||||
|
||||
GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations, along with their companion properties:
|
||||
|
||||
```swift
|
||||
extension Author {
|
||||
static let books = hasMany(Book.self)
|
||||
var books: QueryInterfaceRequest<Book> {
|
||||
return request(for: Author.books)
|
||||
}
|
||||
}
|
||||
|
||||
extension Book {
|
||||
static let author = belongsTo(Author.self)
|
||||
var author: QueryInterfaceRequest<Author> {
|
||||
return request(for: Book.author)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Thanks to this setup, you can fetch associated records:
|
||||
|
||||
```swift
|
||||
// Fetch an author and its books
|
||||
struct AuthorInfo {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, key: 123) else { return nil }
|
||||
let books = try author.books.fetchAll(db)
|
||||
return AuthorInfo(author: author, books: books)
|
||||
}
|
||||
|
||||
// Fetch all authorships
|
||||
struct Authorship: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
let authorships: [Authorship] = try dbQueue.read { db in
|
||||
let request = Book.including(required: Book.author)
|
||||
return try Authorship.fetchAll(db, request)
|
||||
}
|
||||
```
|
||||
|
||||
The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
|
||||
|
||||
That is because other ORMs perform lazy loading:
|
||||
|
||||
```ruby
|
||||
# Ruby's Active Record
|
||||
author = Author.find(123) # fetch author
|
||||
books = author.books # lazily fetches books on demand
|
||||
```
|
||||
|
||||
GRDB does not perform lazy loading. Lazy loading either requires record to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer. This is why GRDB has removed lazy loading from the list of desirable features. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information.
|
||||
|
||||
The consequence is that each part of your application will load the data it needs, at the moment it needs it, as below:
|
||||
|
||||
1. Prepare the application screen that lists all authors:
|
||||
|
||||
```swift
|
||||
let authors: [Author] = dbQueue.read { db in
|
||||
Author.order(Colum("name")).fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
2. Prepare the application screen that displays an author and her books:
|
||||
|
||||
```swift
|
||||
struct AuthorInfo {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
let authorId = 123
|
||||
let authorInfo: AuthorInfo? = dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, key: authorId) else { return nil }
|
||||
let books = try author.books.order(Column("publishDate").desc).fetchAll(db)
|
||||
return AuthorInfo(author: author, books: books)
|
||||
}
|
||||
```
|
||||
|
||||
3. Prepare the application screen that displays a book information:
|
||||
|
||||
```swift
|
||||
struct BookInfo {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
let bookId = 123
|
||||
let bookInfo: BookInfo? = dbQueue.read { db in
|
||||
guard let book = try Book.fetchOne(db, key: bookId) else { return nil }
|
||||
let author = try book.author.fetchOne(db)!
|
||||
return BookInfo(book: book, author: author)
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing the basic record types. Fetch the data your application needs, at the moment it needs it, no more, no less.
|
||||
|
||||
|
||||
## Fetch In Time
|
||||
|
||||
> :bulb: **Tip**: Make sure you fetch all the data your application needs in a **single database read**.
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
let bookId = 123
|
||||
let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
guard let book = try Book.fetchOne(db, key: bookId) else { return nil }
|
||||
let author = try book.author.fetchOne(db)!
|
||||
return BookInfo(book: book, author: author)
|
||||
}
|
||||
if let bookInfo = bookInfo {
|
||||
// use bookInfo
|
||||
}
|
||||
|
||||
// NOT RECOMMENDED
|
||||
let bookId = 123
|
||||
if let book = databaseManager.getBook(id: bookId) {
|
||||
let author = databaseManager.getAuthor(id: book.authorId)!
|
||||
// use book and author
|
||||
}
|
||||
```
|
||||
|
||||
This tip is paramount, and deserves an explanation: when you do not fetch your data in a single database read, other threads of your application may modify the database in the background, and have you fetch inconsistent data. This leads to hard-to-reproduce bugs, from funny values on screen to data loss.
|
||||
|
||||
Wrapping all fetches in a `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
|
||||
|
||||
```ruby
|
||||
# Ruby's Active Record
|
||||
if book = Book.find(123) # fetch book
|
||||
author = book.author # fetch author
|
||||
# use book and author
|
||||
end
|
||||
```
|
||||
|
||||
The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests.
|
||||
|
||||
This isolation can be achieved with record management, as in [Core Data] or [Realm], that target with long-running multi-threaded applications. Most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others.
|
||||
|
||||
GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. Unlike web-oriented ORMs, though, GRDB can't provide *implicit* isolation: the application must decide when it wants to safely read information in the database, and this decision is made *explicit* with the `read` GRDB method.
|
||||
|
||||
Do not overlook this advice, or your application will exhibit weird concurrency-related bugs. Read the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale.
|
||||
|
||||
|
||||
## Observe the Database and Refetch when Needed
|
||||
|
||||
We have seen above that the Author and Book record types are [responsible](#record-types-are-responsible-for-their-tables) for their own dedicated database tables. Later we [composed](#compose-records) them into more complex types such as `BookInfo` or `AuthorInfo`. We advised the application to fetch database information [right on time](#fetch-in-time), when it needs to process it.
|
||||
|
||||
Fetched information eventually becomes obsoleted, as the application modifies the database content.
|
||||
|
||||
It is up to the application to decide how long it should keep fetched information in memory. Very often though, the application will want to keep memory information synchronized with the database content.
|
||||
|
||||
This synchronization is not automatic with GRDB: records do not "auto-update". That is because applications do not always want this feature, and because it is difficult to write correct multi-threaded applications when values can change in unexpected ways.
|
||||
|
||||
Instead, have a look at [Database Observation]:
|
||||
|
||||
> :bulb: **Tip**: Use [FetchedRecordsController] when a table or collection views should remained synchronized with the database, in an animated way.
|
||||
>
|
||||
> :bulb: **Tip**: Use [RxGRDB] when your application needs to react to all changes in the results of a database request.
|
||||
>
|
||||
> :bulb: **Tip**: Use [TransactionObserver], the low-level protocol for database observation, for your most advanced needs.
|
||||
>
|
||||
> :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones.
|
||||
|
||||
|
||||
[records]: ../README.md#records
|
||||
[associations]: AssociationsBasics.md
|
||||
[FMDB]: https://github.com/ccgus/fmdb
|
||||
[Core Data]: https://developer.apple.com/documentation/coredata
|
||||
[Realm]: https://realm.io
|
||||
[Active Record]: http://guides.rubyonrails.org/active_record_basics.html
|
||||
[Django]: https://docs.djangoproject.com/en/2.0/topics/db/
|
||||
[record protocols]: ../README.md#record-protocols-overview
|
||||
[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns
|
||||
[Single Responsibility Principle]: https://en.wikipedia.org/wiki/Single_responsibility_principle
|
||||
[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth
|
||||
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
|
||||
[Why Adopt GRDB?]: WhyAdoptGRDB.md
|
||||
[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
|
||||
[migrations]: ../README.md#migrations
|
||||
[migration]: ../README.md#migrations
|
||||
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
|
||||
[Concurrency Guide]: ../README.md#concurrency
|
||||
[PersistableRecord]: ../README.md#persistablerecord-protocol
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
[TransactionObserver]: ../README.md#transactionobserver-protocol
|
||||
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
|
||||
[Record Types are Responsible for Their Tables]: #record-types-are-responsible-for-their-tables
|
||||
[Compose Records]: #compose-records
|
||||
[Fetch In Time]: #fetch-in-time
|
||||
[Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed
|
||||
@@ -0,0 +1,154 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="468px" height="145px" viewBox="0 0 468 145" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>AmbiguousForeignKeys</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
|
||||
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
|
||||
<stop stop-color="#FFFFFF" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<rect id="path-2" x="0" y="0" width="200" height="127" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-9.1%" width="114.5%" height="122.8%" filterUnits="objectBoundingBox" id="filter-4">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-5" x="0" y="0" width="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" filterUnits="objectBoundingBox" id="filter-7">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<circle id="path-8" cx="3.5" cy="28.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-9"></path>
|
||||
<circle id="path-10" cx="3.5" cy="47.5" r="3.5"></circle>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="AmbiguousForeignKeys" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table">
|
||||
<mask id="mask-3" fill="white">
|
||||
<use xlink:href="#path-2"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="128" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">authorId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">translatorId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 103.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">title</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="book" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="82.9443359" y="21">book</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2" transform="translate(250.000000, 0.000000)">
|
||||
<mask id="mask-6" fill="white">
|
||||
<use xlink:href="#path-5"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-7)" xlink:href="#path-5"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="person" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="76.2109375" y="21">person</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group-3" transform="translate(197.000000, 39.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="28.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-9"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,28.5 C2.5,28.5 2.5,28.5 16.5,28.5 C30.5,28.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
<g id="Group-3" transform="translate(197.000000, 44.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-10"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="47.5" r="4"></circle>
|
||||
</g>
|
||||
<path d="M2.5,47.5 C2.5,47.5 2.5,47.5 16.5,47.5 C30.5,47.5 27.5,0.5 40.5,0.5 C49.1666667,0.5 53.5,0.5 53.5,0.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 12 KiB |
@@ -0,0 +1,133 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="468px" height="121px" viewBox="0 0 468 121" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>BelongsToSchema</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
|
||||
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
|
||||
<stop stop-color="#FFFFFF" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<rect id="path-2" x="0" y="0" width="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" filterUnits="objectBoundingBox" id="filter-4">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-5" x="0" y="0" width="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" filterUnits="objectBoundingBox" id="filter-7">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<circle id="path-8" cx="200.5" cy="67.5" r="3.5"></circle>
|
||||
<path d="M254.40688,43.6237841 L247.481919,39.8150553 C246.997998,39.5488989 246.38994,39.7254318 246.123784,40.2093525 C246.042579,40.3569975 246,40.5227683 246,40.6912712 L246,48.3087288 C246,48.8610135 246.447715,49.3087288 247,49.3087288 C247.168503,49.3087288 247.334274,49.2661494 247.481919,49.1849447 L254.40688,45.3762159 C254.890801,45.1100595 255.067334,44.5020019 254.801177,44.0180813 C254.709789,43.8519215 254.57304,43.7151719 254.40688,43.6237841 Z" id="path-9"></path>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="BelongsToSchema" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table">
|
||||
<mask id="mask-3" fill="white">
|
||||
<use xlink:href="#path-2"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">authorId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">title</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="book" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="82.9443359" y="21">book</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2" transform="translate(250.000000, 0.000000)">
|
||||
<mask id="mask-6" fill="white">
|
||||
<use xlink:href="#path-5"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-7)" xlink:href="#path-5"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="author" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="77.3867188" y="21">author</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="200.5" cy="67.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-9"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M254.64784,43.1856761 C254.897079,43.3227579 255.102204,43.5278823 255.239285,43.7771219 C255.63852,44.5030029 255.373721,45.4150893 254.64784,45.8143239 L247.722878,49.6230526 C247.501411,49.7448598 247.252754,49.8087288 247,49.8087288 C246.171573,49.8087288 245.5,49.1371559 245.5,48.3087288 L245.5,40.6912712 C245.5,40.4385168 245.563869,40.1898606 245.685676,39.9683931 C246.084911,39.2425121 246.996997,38.9777128 247.722878,39.3769474 L254.64784,43.1856761 Z"></path>
|
||||
</g>
|
||||
<path d="M199.5,67.5 C199.5,67.5 199.5,67.5 213.5,67.5 C227.5,67.5 224.5,44.5 237.5,44.5 C246.166667,44.5 250.5,44.5 250.5,44.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,135 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="468px" height="121px" viewBox="0 0 468 121" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>HasManySchema</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
|
||||
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
|
||||
<stop stop-color="#FFFFFF" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<rect id="path-2" x="0" y="0" width="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" filterUnits="objectBoundingBox" id="filter-4">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-5" x="0" y="0" width="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" filterUnits="objectBoundingBox" id="filter-7">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<circle id="path-8" cx="3.5" cy="28.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-9"></path>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="HasManySchema" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table" transform="translate(250.000000, 0.000000)">
|
||||
<mask id="mask-3" fill="white">
|
||||
<use xlink:href="#path-2"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">authorId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">title</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="book" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="82.9443359" y="21">book</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2">
|
||||
<mask id="mask-6" fill="white">
|
||||
<use xlink:href="#path-5"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-7)" xlink:href="#path-5"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="author" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="77.3867188" y="21">author</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group" transform="translate(224.000000, 55.000000) scale(-1, 1) translate(-224.000000, -55.000000) translate(195.000000, 39.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="28.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-9"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,28.5 C2.5,28.5 2.5,28.5 16.5,28.5 C30.5,28.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 10 KiB |
@@ -0,0 +1,185 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="468px" height="200px" viewBox="0 0 468 200" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>HasManyThroughSchema</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
|
||||
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
|
||||
<stop stop-color="#FFFFFF" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<rect id="path-2" x="0" y="0" width="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" filterUnits="objectBoundingBox" id="filter-4">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-5" x="0" y="0" width="200" height="79" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-14.6%" width="114.5%" height="136.7%" filterUnits="objectBoundingBox" id="filter-7">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-8" x="0" y="0" width="200" height="79" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-14.6%" width="114.5%" height="136.7%" filterUnits="objectBoundingBox" id="filter-10">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<circle id="path-11" cx="3.5" cy="44.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-12"></path>
|
||||
<circle id="path-13" cx="3.5" cy="3.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,42.6237841 L50.4819187,38.8150553 C49.9979981,38.5488989 49.3899405,38.7254318 49.1237841,39.2093525 C49.0425794,39.3569975 49,39.5227683 49,39.6912712 L49,47.3087288 C49,47.8610135 49.4477153,48.3087288 50,48.3087288 C50.168503,48.3087288 50.3342738,48.2661494 50.4819187,48.1849447 L57.4068802,44.3762159 C57.8908008,44.1100595 58.0673337,43.5020019 57.8011773,43.0180813 C57.7097895,42.8519215 57.5730399,42.7151719 57.4068802,42.6237841 Z" id="path-14"></path>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="HasManyThroughSchema" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table" transform="translate(250.000000, 40.000000)">
|
||||
<mask id="mask-3" fill="white">
|
||||
<use xlink:href="#path-2"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">countryCode</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">citizenId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">issueDate</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">date</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="passport" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="69.3613281" y="21">passport</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2">
|
||||
<mask id="mask-6" fill="white">
|
||||
<use xlink:href="#path-5"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-7)" xlink:href="#path-5"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="80" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">code</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="country" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="73.3740234" y="21">country</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2" transform="translate(0.000000, 103.000000)">
|
||||
<mask id="mask-9" fill="white">
|
||||
<use xlink:href="#path-8"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-10)" xlink:href="#path-8"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="80" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-9)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-9)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="citizen" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="77.1782227" y="21">citizen</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group" transform="translate(224.000000, 63.000000) scale(-1, 1) translate(-224.000000, -63.000000) translate(195.000000, 39.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="44.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-12"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,44.5 C2.5,44.5 2.5,44.5 16.5,44.5 C30.5,44.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
<g id="Group" transform="translate(224.000000, 128.500000) scale(-1, 1) translate(-224.000000, -128.500000) translate(195.000000, 104.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-13"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="3.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-14"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,42.1856761 C57.8970791,42.3227579 58.1022035,42.5278823 58.2392853,42.7771219 C58.6385198,43.5030029 58.3737206,44.4150893 57.6478395,44.8143239 L50.7228781,48.6230526 C50.5014107,48.7448598 50.2527545,48.8087288 50,48.8087288 C49.1715729,48.8087288 48.5,48.1371559 48.5,47.3087288 L48.5,39.6912712 C48.5,39.4385168 48.563869,39.1898606 48.6856761,38.9683931 C49.0849107,38.2425121 49.9969971,37.9777128 50.7228781,38.3769474 L57.6478395,42.1856761 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,3.5 C2.5,3.5 2.5,3.5 16.5,3.5 C30.5,3.5 27.5,43.5 40.5,43.5 C49.1666667,43.5 53.5,43.5 53.5,43.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 15 KiB |
@@ -0,0 +1,153 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="468px" height="145px" viewBox="0 0 468 145" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>HasOneSchema</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
|
||||
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
|
||||
<stop stop-color="#FFFFFF" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<rect id="path-2" x="0" y="0" width="200" height="127" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-9.1%" width="114.5%" height="122.8%" filterUnits="objectBoundingBox" id="filter-4">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-5" x="0" y="0" width="200" height="127" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-9.1%" width="114.5%" height="122.8%" filterUnits="objectBoundingBox" id="filter-7">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<circle id="path-8" cx="3.5" cy="28.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-9"></path>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="HasOneSchema" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table" transform="translate(250.000000, 0.000000)">
|
||||
<mask id="mask-3" fill="white">
|
||||
<use xlink:href="#path-2"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="128" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">countryCode</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">population</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 103.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">density</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">double</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="demographics" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="50.894043" y="21">demographics</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2">
|
||||
<mask id="mask-6" fill="white">
|
||||
<use xlink:href="#path-5"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-7)" xlink:href="#path-5"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="128" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">code</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 103.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="country" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="73.3740234" y="21">country</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group" transform="translate(224.000000, 55.000000) scale(-1, 1) translate(-224.000000, -55.000000) translate(195.000000, 39.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="28.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-9"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,28.5 C2.5,28.5 2.5,28.5 16.5,28.5 C30.5,28.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 12 KiB |
@@ -0,0 +1,198 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="468px" height="247px" viewBox="0 0 468 247" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>HasOneThroughSchema</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
|
||||
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
|
||||
<stop stop-color="#FFFFFF" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<rect id="path-2" x="0" y="0" width="200" height="79" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-14.6%" width="114.5%" height="136.7%" filterUnits="objectBoundingBox" id="filter-4">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-5" x="0" y="0" width="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" filterUnits="objectBoundingBox" id="filter-7">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-8" x="0" y="0" width="200" height="102" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.3%" width="114.5%" height="128.4%" filterUnits="objectBoundingBox" id="filter-10">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<circle id="path-11" cx="3.5" cy="56.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,4.62378409 L50.4819187,0.815055312 C49.9979981,0.548898936 49.3899405,0.725431787 49.1237841,1.20935247 C49.0425794,1.35699745 49,1.52276825 49,1.69127122 L49,9.30872878 C49,9.86101353 49.4477153,10.3087288 50,10.3087288 C50.168503,10.3087288 50.3342738,10.2661494 50.4819187,10.1849447 L57.4068802,6.37621591 C57.8908008,6.11005953 58.0673337,5.50200193 57.8011773,5.01808125 C57.7097895,4.85192153 57.5730399,4.71517193 57.4068802,4.62378409 Z" id="path-12"></path>
|
||||
<circle id="path-13" cx="3.5" cy="3.5" r="3.5"></circle>
|
||||
<path d="M57.4068802,54.6237841 L50.4819187,50.8150553 C49.9979981,50.5488989 49.3899405,50.7254318 49.1237841,51.2093525 C49.0425794,51.3569975 49,51.5227683 49,51.6912712 L49,59.3087288 C49,59.8610135 49.4477153,60.3087288 50,60.3087288 C50.168503,60.3087288 50.3342738,60.2661494 50.4819187,60.1849447 L57.4068802,56.3762159 C57.8908008,56.1100595 58.0673337,55.5020019 57.8011773,55.0180813 C57.7097895,54.8519215 57.5730399,54.7151719 57.4068802,54.6237841 Z" id="path-14"></path>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="HasOneThroughSchema" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table" transform="translate(250.000000, 75.000000)">
|
||||
<mask id="mask-3" fill="white">
|
||||
<use xlink:href="#path-2"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="80" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="library" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="77.800293" y="21">library</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group-2">
|
||||
<g id="Table-Copy-2">
|
||||
<mask id="mask-6" fill="white">
|
||||
<use xlink:href="#path-5"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-7)" xlink:href="#path-5"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">libraryId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-6)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">title</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="book" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="82.9443359" y="21">book</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-2" transform="translate(0.000000, 127.000000)">
|
||||
<mask id="mask-9" fill="white">
|
||||
<use xlink:href="#path-8"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-10)" xlink:href="#path-8"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="103" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-9)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">libraryId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-9)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">street</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-9)">
|
||||
<g transform="translate(0.000000, 78.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">city</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="address" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="72.4545898" y="21">address</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Group" transform="translate(226.000000, 93.500000) scale(1, -1) translate(-226.000000, -93.500000) translate(197.000000, 63.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="56.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-12"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,4.18567614 C57.8970791,4.3227579 58.1022035,4.5278823 58.2392853,4.77712188 C58.6385198,5.5030029 58.3737206,6.4150893 57.6478395,6.81432386 L50.7228781,10.6230526 C50.5014107,10.7448598 50.2527545,10.8087288 50,10.8087288 C49.1715729,10.8087288 48.5,10.1371559 48.5,9.30872878 L48.5,1.69127122 C48.5,1.43851677 48.563869,1.18986057 48.6856761,0.968393096 C49.0849107,0.242512071 49.9969971,-0.0222872062 50.7228781,0.376947358 L57.6478395,4.18567614 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,56.5 C2.5,56.5 2.5,56.5 16.5,56.5 C30.5,56.5 27.5,5.5 40.5,5.5 C49.1666667,5.5 53.5,5.5 53.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
<g id="Group" transform="translate(226.000000, 143.500000) scale(1, -1) translate(-226.000000, -143.500000) translate(197.000000, 113.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-13"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="3.5" cy="3.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-14"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M57.6478395,54.1856761 C57.8970791,54.3227579 58.1022035,54.5278823 58.2392853,54.7771219 C58.6385198,55.5030029 58.3737206,56.4150893 57.6478395,56.8143239 L50.7228781,60.6230526 C50.5014107,60.7448598 50.2527545,60.8087288 50,60.8087288 C49.1715729,60.8087288 48.5,60.1371559 48.5,59.3087288 L48.5,51.6912712 C48.5,51.4385168 48.563869,51.1898606 48.6856761,50.9683931 C49.0849107,50.2425121 49.9969971,49.9777128 50.7228781,50.3769474 L57.6478395,54.1856761 Z"></path>
|
||||
</g>
|
||||
<path d="M2.5,3.5 C2.5,3.5 2.5,3.5 16.5,3.5 C30.5,3.5 27.5,55.5 40.5,55.5 C49.1666667,55.5 53.5,55.5 53.5,55.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 16 KiB |
@@ -0,0 +1,3 @@
|
||||
fixfonts:
|
||||
sed -i '' -- 's/SFUIText-Regular, SF UI Text/-apple-system,sans-serif/g' *.svg
|
||||
sed -i '' -- 's/SFUIText-Semibold, SF UI Text/-apple-system,sans-serif/g' *.svg
|
||||
@@ -0,0 +1,91 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="233px" height="121px" viewBox="0 0 233 121" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>RecursiveSchema</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
|
||||
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
|
||||
<stop stop-color="#FFFFFF" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<rect id="path-2" x="0" y="0" width="200" height="103" rx="10"></rect>
|
||||
<filter x="-7.2%" y="-11.2%" width="114.5%" height="128.2%" filterUnits="objectBoundingBox" id="filter-4">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<circle id="path-5" cx="22.5" cy="28.5" r="3.5"></circle>
|
||||
<path d="M27.4068802,4.62378409 L20.4819187,0.815055312 C19.9979981,0.548898936 19.3899405,0.725431787 19.1237841,1.20935247 C19.0425794,1.35699745 19,1.52276825 19,1.69127122 L19,9.30872878 C19,9.86101353 19.4477153,10.3087288 20,10.3087288 C20.168503,10.3087288 20.3342738,10.2661494 20.4819187,10.1849447 L27.4068802,6.37621591 C27.8908008,6.11005953 28.0673337,5.50200193 27.8011773,5.01808125 C27.7097895,4.85192153 27.5730399,4.71517193 27.4068802,4.62378409 Z" id="path-6"></path>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="RecursiveSchema" transform="translate(9.000000, 6.000000)">
|
||||
<g id="Table-Copy-2">
|
||||
<mask id="mask-3" fill="white">
|
||||
<use xlink:href="#path-2"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="201" height="104" rx="10"></rect>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 31.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">id</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 55.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">managerId</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">integer</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500">
|
||||
<tspan x="10" y="17" fill="#000000">name</tspan>
|
||||
</text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal">
|
||||
<tspan x="110" y="17" fill="#000000">text</tspan>
|
||||
</text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<g id="Field" mask="url(#mask-3)">
|
||||
<g transform="translate(0.000000, 79.000000)">
|
||||
<text id="name" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="500"></text>
|
||||
<text id="type" fill="none" font-family="-apple-system,sans-serif" font-size="14" font-weight="normal"></text>
|
||||
<rect id="Rectangle" fill-opacity="0.12" fill="#000000" fill-rule="evenodd" x="0" y="0" width="200" height="1"></rect>
|
||||
</g>
|
||||
</g>
|
||||
<text id="employee" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="66.8730469" y="21">employee</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group" transform="translate(209.000000, 55.000000) scale(-1, 1) translate(-209.000000, -55.000000) translate(195.000000, 39.000000)">
|
||||
<g id="Oval">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<circle stroke="#FFFFFF" stroke-width="1" cx="22.5" cy="28.5" r="4"></circle>
|
||||
</g>
|
||||
<g id="Path-3">
|
||||
<use fill="#000000" fill-rule="evenodd" xlink:href="#path-6"></use>
|
||||
<path stroke="#FFFFFF" stroke-width="1" d="M27.6478395,4.18567614 C27.8970791,4.3227579 28.1022035,4.5278823 28.2392853,4.77712188 C28.6385198,5.5030029 28.3737206,6.4150893 27.6478395,6.81432386 L20.7228781,10.6230526 C20.5014107,10.7448598 20.2527545,10.8087288 20,10.8087288 C19.1715729,10.8087288 18.5,10.1371559 18.5,9.30872878 L18.5,1.69127122 C18.5,1.43851677 18.563869,1.18986057 18.6856761,0.968393096 C19.0849107,0.242512071 19.9969971,-0.0222872062 20.7228781,0.376947358 L27.6478395,4.18567614 Z"></path>
|
||||
</g>
|
||||
<path d="M23.5,28.5 C23.5,28.5 19.1666667,28.5 10.5,28.5 C-2.5,28.5 -2.5,5.5 10.5,5.5 C19.1666667,5.5 23.5,5.5 23.5,5.5" id="Path-2" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 7.1 KiB |
@@ -0,0 +1,110 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="292px" height="166px" viewBox="0 0 292 166" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>TreeOfAssociationKeys</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
|
||||
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
|
||||
<stop stop-color="#FFFFFF" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<rect id="path-2" x="0" y="0" width="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" filterUnits="objectBoundingBox" id="filter-4">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-5" x="0" y="0" width="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" filterUnits="objectBoundingBox" id="filter-7">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-8" x="0" y="0" width="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" filterUnits="objectBoundingBox" id="filter-10">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-11" x="0" y="0" width="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" filterUnits="objectBoundingBox" id="filter-13">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="TreeOfAssociationKeys" transform="translate(9.000000, 6.000000)">
|
||||
<path d="M60,78 L60,114" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path id="Line-decoration-1" d="M57,103.2 L60,114 L63,103.2" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path d="M139,14 L77,57" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path id="Line-decoration-1" d="M84.1648227,48.3799469 L77,57 L87.5842165,53.3102356" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path d="M140,14 L206,57" id="Line-Copy" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path id="Line-Copy-decoration-1" d="M195.313438,53.61808 L206,57 L198.58872,48.5909017" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<g id="Table-Copy-2" transform="translate(80.000000, 0.000000)">
|
||||
<mask id="mask-3" fill="white">
|
||||
<use xlink:href="#path-2"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id="root" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="45.390625" y="19">root</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-3" transform="translate(0.000000, 62.000000)">
|
||||
<mask id="mask-6" fill="white">
|
||||
<use xlink:href="#path-5"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-7)" xlink:href="#path-5"></use>
|
||||
<use fill="#417505" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id=""author"" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="30.2421875" y="19">"author"</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-5" transform="translate(155.000000, 62.000000)">
|
||||
<mask id="mask-9" fill="white">
|
||||
<use xlink:href="#path-8"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-10)" xlink:href="#path-8"></use>
|
||||
<use fill="#9013FE" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id=""coverImage"" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="12.8037109" y="19">"coverImage"</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-4" transform="translate(0.000000, 120.000000)">
|
||||
<mask id="mask-12" fill="white">
|
||||
<use xlink:href="#path-11"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-13)" xlink:href="#path-11"></use>
|
||||
<use fill="#D0021B" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id=""country"" mask="url(#mask-12)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="26.2294922" y="19">"country"</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,130 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg width="421px" height="227px" viewBox="0 0 421 227" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<!-- Generator: Sketch 49 (51002) - http://www.bohemiancoding.com/sketch -->
|
||||
<title>TreeOfAssociationKeysMapping</title>
|
||||
<desc>Created with Sketch.</desc>
|
||||
<defs>
|
||||
<linearGradient x1="50%" y1="100%" x2="50%" y2="1.41638472e-14%" id="linearGradient-1">
|
||||
<stop stop-color="#FFFFFF" stop-opacity="0.9" offset="0%"></stop>
|
||||
<stop stop-color="#FFFFFF" offset="100%"></stop>
|
||||
</linearGradient>
|
||||
<rect id="path-2" x="0" y="0" width="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" filterUnits="objectBoundingBox" id="filter-4">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-5" x="0" y="0" width="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" filterUnits="objectBoundingBox" id="filter-7">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-8" x="0" y="0" width="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" filterUnits="objectBoundingBox" id="filter-10">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
<rect id="path-11" x="0" y="0" width="119" height="28" rx="10"></rect>
|
||||
<filter x="-12.2%" y="-41.1%" width="124.4%" height="203.6%" filterUnits="objectBoundingBox" id="filter-13">
|
||||
<feMorphology radius="1" operator="dilate" in="SourceAlpha" result="shadowSpreadOuter1"></feMorphology>
|
||||
<feOffset dx="0" dy="3" in="shadowSpreadOuter1" result="shadowOffsetOuter1"></feOffset>
|
||||
<feGaussianBlur stdDeviation="4" in="shadowOffsetOuter1" result="shadowBlurOuter1"></feGaussianBlur>
|
||||
<feComposite in="shadowBlurOuter1" in2="SourceAlpha" operator="out" result="shadowBlurOuter1"></feComposite>
|
||||
<feColorMatrix values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.1 0" type="matrix" in="shadowBlurOuter1"></feColorMatrix>
|
||||
</filter>
|
||||
</defs>
|
||||
<g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
|
||||
<g id="TreeOfAssociationKeysMapping" transform="translate(0.000000, 6.000000)">
|
||||
<g id="Group-4">
|
||||
<path d="M83,36 L83,186" id="Line-Copy-2" stroke="#727272" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4,8"></path>
|
||||
<path d="M159,96 L159,186" id="Line-Copy-3" stroke="#727272" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4,8"></path>
|
||||
<path d="M246,156 L246,186" id="Line-Copy-4" stroke="#727272" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4,8"></path>
|
||||
<path d="M352,96 L352,186" id="Line-Copy-5" stroke="#727272" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="4,8"></path>
|
||||
<path d="M85,14 L136,57" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path id="Line-decoration-1" d="M125.809367,52.3319166 L136,57 L129.676951,47.7447827" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path d="M85,14 L292,57" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path id="Line-decoration-1" d="M280.815576,57.7407092 L292,57 L282.035901,51.8661193" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path d="M156,72 L207,115" id="Line" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<path id="Line-decoration-1" d="M196.809367,110.331917 L207,115 L200.676951,105.744783" stroke="#000000" stroke-linecap="round" stroke-linejoin="round"></path>
|
||||
<g id="Table-Copy-6" transform="translate(23.000000, 0.000000)">
|
||||
<mask id="mask-3" fill="white">
|
||||
<use xlink:href="#path-2"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-4)" xlink:href="#path-2"></use>
|
||||
<use fill="#005CC5" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-2"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id="root" mask="url(#mask-3)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="45.390625" y="19">root</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-7" transform="translate(100.000000, 62.000000)">
|
||||
<mask id="mask-6" fill="white">
|
||||
<use xlink:href="#path-5"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-7)" xlink:href="#path-5"></use>
|
||||
<use fill="#417505" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-5"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id=""author"" mask="url(#mask-6)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="30.2421875" y="19">"author"</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-8" transform="translate(293.000000, 62.000000)">
|
||||
<mask id="mask-9" fill="white">
|
||||
<use xlink:href="#path-8"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-10)" xlink:href="#path-8"></use>
|
||||
<use fill="#9013FE" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-8"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id=""coverImage"" mask="url(#mask-9)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="12.8037109" y="19">"coverImage"</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Table-Copy-9" transform="translate(187.000000, 120.000000)">
|
||||
<mask id="mask-12" fill="white">
|
||||
<use xlink:href="#path-11"></use>
|
||||
</mask>
|
||||
<g id="Rectangle">
|
||||
<use fill="black" fill-opacity="1" filter="url(#filter-13)" xlink:href="#path-11"></use>
|
||||
<use fill="#D0021B" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<use fill="url(#linearGradient-1)" fill-rule="evenodd" xlink:href="#path-11"></use>
|
||||
<rect stroke-opacity="0.25" stroke="#000000" stroke-width="1" x="-0.5" y="-0.5" width="120" height="29" rx="10"></rect>
|
||||
</g>
|
||||
<text id=""country"" mask="url(#mask-12)" font-family="-apple-system,sans-serif" font-size="14" font-weight="500" fill="#000000">
|
||||
<tspan x="26.2294922" y="19">"country"</tspan>
|
||||
</text>
|
||||
</g>
|
||||
<g id="Group-5" transform="translate(0.000000, 191.000000)" font-family="Menlo-Regular, Menlo" font-size="14" font-weight="normal">
|
||||
<text id="SELECT-book.*,-autho">
|
||||
<tspan x="0" y="13" fill="#404040">SELECT </tspan>
|
||||
<tspan x="59.0009766" y="13" fill="#4A90E2">book.*</tspan>
|
||||
<tspan x="109.573242" y="13" fill="#404040">, </tspan>
|
||||
<tspan x="126.430664" y="13" fill="#417505">author.*</tspan>
|
||||
<tspan x="193.860352" y="13" fill="#404040">, </tspan>
|
||||
<tspan x="210.717773" y="13" fill="#D0021B">country.*</tspan>
|
||||
<tspan x="286.576172" y="13" fill="#404040">, </tspan>
|
||||
<tspan x="303.433594" y="13" fill="#9013FE">coverImage.*</tspan>
|
||||
<tspan x="404.578125" y="13" fill="#404040"></tspan>
|
||||
<tspan x="0" y="29" fill="#404040">FROM …</tspan>
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 10 KiB |
@@ -1 +1 @@
|
||||
The main documentation is available in [README.md](../../../#documentation).
|
||||
The main documentation is available in [README.md](../README.md#documentation).
|
||||
@@ -10,7 +10,7 @@ We'll start with a few [core principles](#core-principles), so that you see wher
|
||||
|
||||
### It is generally easier to access a database through "record types".
|
||||
|
||||
This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow[nameColumn]`, doesn't it?
|
||||
This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow["name"]`, doesn't it?
|
||||
|
||||
The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that comes with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause.
|
||||
|
||||
@@ -37,9 +37,9 @@ GRDB puts all bets on SQLite, and focuses on front-end GUI applications.
|
||||
|
||||
This means that dealing with servers, MySQL, or PostgreSQL is out of scope. GRDB is not an alternative to IBM's [Swift-Kuery], Vapor's [Fluent], or Perfect's [StORM].
|
||||
|
||||
Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, changes tracking, database observation, multi-threading safety, table view animations, support for reactive streams...
|
||||
Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, record comparison, database observation, multi-threading safety, table view animations, support for reactive streams...
|
||||
|
||||
Some will call GRDB "opinionated", or "bloated". Well, the bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face.
|
||||
The bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face.
|
||||
|
||||
Since you don't have to take my words for granted, we'll now see how GRDB actually solves common problems that developers face with other database libraries.
|
||||
|
||||
@@ -51,7 +51,7 @@ What is the purpose of the above principles, if not providing solutions to diffi
|
||||
|
||||
### Allow any Swift struct or class to become a database record
|
||||
|
||||
Most libraries that provide record types want you to subclass a root class: NSManagedObject, Realm.Object, FCModel.
|
||||
Most libraries that provide record types want you to subclass a root class: [NSManagedObject](https://developer.apple.com/documentation/coredata/nsmanagedobject), [Realm.Object](https://www.realm.io/docs/swift/latest), [FCModel](https://github.com/marcoarment/FCModel).
|
||||
|
||||
The main problem with those root classes is that they are classes. You can't define records from plain Swift structs, and leverage all advantages of Swift value types: immutability, multi-threading safety, etc.
|
||||
|
||||
@@ -65,28 +65,28 @@ struct Place {
|
||||
}
|
||||
```
|
||||
|
||||
By adopting the [RowConvertible] protocol, places can be loaded from SQL requests:
|
||||
By adopting the [FetchableRecord] protocol, places can be loaded from SQL requests:
|
||||
|
||||
```swift
|
||||
extension Place: RowConvertible { ... }
|
||||
let places = try Place.fetchAll(db, "SELECT * FROM places") // [Place]
|
||||
extension Place: FetchableRecord { ... }
|
||||
let places = try Place.fetchAll(db, "SELECT * FROM place") // [Place]
|
||||
```
|
||||
|
||||
Add the [TableMapping] protocol, and SQL requests are generated for you:
|
||||
Add the [TableRecord] protocol, and SQL requests are generated for you:
|
||||
|
||||
```swift
|
||||
extension Place: TableMapping { ... }
|
||||
extension Place: TableRecord { ... }
|
||||
let place = try Place.fetchOne(db, key: 1) // Place?
|
||||
```
|
||||
|
||||
Add the [Persistable] protocol, and places know how to insert, update and delete themselves:
|
||||
Add the [PersistableRecord] protocol, and places know how to insert, update and delete themselves:
|
||||
|
||||
```swift
|
||||
extension Place: Persistable { ... }
|
||||
extension Place: PersistableRecord { ... }
|
||||
try place.delete(db)
|
||||
```
|
||||
|
||||
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with database change notifications, with many advantages.
|
||||
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
|
||||
|
||||
|
||||
### Allow database records to cross threads
|
||||
@@ -129,16 +129,16 @@ First, notifications only come from database changes safely saved on disk. This
|
||||
|
||||
Next, you choose the dispatch queue on which notifications happen. It can be on the special "writer queue", which allows you to process changes before any other thread has any opportunity to perform further database modifications. But notifications can also happen on the queue of your choice (generally the main queue, by default, as in the example above). Of course, GRDB makes sure notifications happen in the same order as database transactions.
|
||||
|
||||
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers.
|
||||
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
|
||||
|
||||
|
||||
### Non-blocking database reads
|
||||
|
||||
GRDB ships with two ways to access databases, [database queues](https://github.com/groue/GRDB.swift/blob/master/README.md#database-queues) and [pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools).
|
||||
GRDB ships with two ways to access databases, [database queues](../README.md#database-queues) and [pools](../README.md#database-pools).
|
||||
|
||||
Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen.
|
||||
|
||||
[Database pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
|
||||
[Database pools](../README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
|
||||
|
||||
|
||||
### Strong and clear multi-threading guarantees
|
||||
@@ -162,9 +162,9 @@ The more threats are handled by the application, the more skilled and careful a
|
||||
| GRDB's DatabaseQueue | :white_check_mark: | :white_check_mark: | Handled by the application | UI is blocked |
|
||||
| GRDB's DatabasePool | :white_check_mark: | :white_check_mark: | Handled by the application | :white_check_mark: (as long as the maximum number of readers has not been reached) |
|
||||
|
||||
I had to omit Realm and FCModel from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue.
|
||||
I had to omit [Realm] and [FCModel] from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue.
|
||||
|
||||
We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to use or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way. A weaker way to say this is that conflict handling at the library level can wait :sweat_smile:.
|
||||
We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to plan, use, or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way.
|
||||
|
||||
Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and you'd better be a very skilled developer in order to use them properly.
|
||||
|
||||
@@ -175,79 +175,89 @@ For further information about GRDB concurrency, check its detailed [Concurrency
|
||||
|
||||
SQL is a weird language. Born in the 70s, easy to [misuse](https://xkcd.com/327/), feared by some developers, despised by others, and yet wonderfully concise and powerful.
|
||||
|
||||
GRDB provides high-level record methods that generate SQL for you:
|
||||
GRDB [query interface] and [associations] can generate SQL for you:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM players ORDER BY score DESC LIMIT 10
|
||||
// SELECT * FROM player ORDER BY score DESC LIMIT 10
|
||||
let bestPlayers: [Player] = try Player
|
||||
.order(scoreColumn.desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
// SELECT MAX(score) FROM players
|
||||
// SELECT MAX(score) FROM player
|
||||
let maximumScore: Int? = try Player
|
||||
.select(max(scoreColumn))
|
||||
.asRequestOf(Int.self)
|
||||
.fetchOne(db)
|
||||
|
||||
// SELECT COUNT(*) FROM players WHERE score = ?
|
||||
let exAequoCount: Int = try Player
|
||||
.filter(scoreColumn == maximumScore)
|
||||
.fetchCount(db)
|
||||
|
||||
// SELECT book.*, author.*
|
||||
// FROM book
|
||||
// LEFT JOIN author ON author.id = book.authorId
|
||||
let request = Book.including(optional: Book.author)
|
||||
let bookInfos: [BookInfo] = BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
But you can *always* switch to SQL when you want to:
|
||||
But you can always switch to SQL when you want to:
|
||||
|
||||
```swift
|
||||
let bestPlayers: [Player] = try Player.fetchAll(db, """
|
||||
SELECT * FROM players ORDER BY score DESC LIMIT 10
|
||||
SELECT * FROM player ORDER BY score DESC LIMIT 10
|
||||
""")
|
||||
|
||||
let maximumScore: Int? = try Int.fetchOne(db, """
|
||||
SELECT MAX(score) FROM players
|
||||
SELECT MAX(score) FROM player
|
||||
""")
|
||||
|
||||
let exAequoCount: Int? = try Int.fetchOne(db, """
|
||||
SELECT COUNT(*) FROM players WHERE score = ?
|
||||
""", arguments: [maximumScore])
|
||||
```
|
||||
|
||||
SQL is also welcome in high-level database observation tools like [FetchedRecordsController] and [RxGRDB]:
|
||||
Power users can also consume complex joined SQL queries into handy record values, by *adapting* raw database rows to the decoded records (see [Joined Queries Support](#../README.md#joined-queries-support)):
|
||||
|
||||
```swift
|
||||
SQLRequest("SELECT * FROM players ORDER BY score DESC LIMIT 10")
|
||||
.asRequest(of: Player.self)
|
||||
.rx
|
||||
.fetchAll(in: dbQueue)
|
||||
.subscribe(onNext: { players: [Player] in
|
||||
print("Best 10 players have changed")
|
||||
})
|
||||
let bookInfos: [BookInfo] = SQLRequest<BookInfo>("""
|
||||
SELECT book.*, author.*
|
||||
FROM book
|
||||
LEFT JOIN author ON author.id = book.authorId
|
||||
""")
|
||||
.adapted { db in
|
||||
let adapters = try splittingRowAdapters(columnCounts: [
|
||||
db.columns(in: "book").count,
|
||||
db.columns(in: "author").count])
|
||||
return ScopeAdapter([
|
||||
"book": adapters[0],
|
||||
"author": adapters[1]])
|
||||
}
|
||||
```
|
||||
|
||||
You can of course deal with raw database rows, and fetch [lazy cursors](https://github.com/groue/GRDB.swift/blob/master/README.md#cursors) instead of arrays:
|
||||
In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](../README.md#cursors) instead of arrays:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT * FROM players")
|
||||
let rows = try Row.fetchCursor(db, "SELECT id, name, score FROM player")
|
||||
while let row = try rows.next() {
|
||||
let id: Int64 = row["id"]
|
||||
let name: String = row["name"]
|
||||
let score: Int = row["score"]
|
||||
let id: Int64 = row[0]
|
||||
let name: String = row[1]
|
||||
let score: Int = row[2]
|
||||
}
|
||||
```
|
||||
|
||||
When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](https://github.com/groue/GRDB.swift/blob/master/README.md#custom-requests):
|
||||
When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](../README.md#custom-requests):
|
||||
|
||||
```swift
|
||||
extension Player {
|
||||
static func customRequest(...) -> AnyTypedRequest<Player> {
|
||||
return SQLRequest("""
|
||||
SELECT ...
|
||||
""", arguments: ...)
|
||||
.asRequestOf(Player.self)
|
||||
static func customRequest(...) -> SQLRequest<Player> {
|
||||
return SQLRequest<Player>("SELECT ...", arguments: ...)
|
||||
}
|
||||
}
|
||||
|
||||
let players = Player.customRequest(...).fetchAll(db)
|
||||
let players = try Player.customRequest(...).fetchAll(db)
|
||||
```
|
||||
|
||||
Those custom requests are welcome in database observation tools like [FetchedRecordsController] and [RxGRDB]:
|
||||
|
||||
```swift
|
||||
Player.customRequest(...).rx
|
||||
.fetchAll(in: dbQueue)
|
||||
.subscribe(onNext: { players: [Player] in
|
||||
print("Players have changed")
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
@@ -258,23 +268,25 @@ And if you happen to maintain an Objective-C application that uses FMDB, checkou
|
||||
|
||||
Happy GRDB! :gift:
|
||||
|
||||
[Concurrency Guide]: https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency
|
||||
[Concurrency Guide]: ../README.md#concurrency
|
||||
[Core Data]: https://developer.apple.com/documentation/coredata
|
||||
[DatabasePool]: https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools
|
||||
[DatabasePool]: ../README.md#database-pools
|
||||
[Diesel]: http://diesel.rs
|
||||
[FCModel]: https://github.com/marcoarment/FCModel
|
||||
[FetchedRecordsController]: https://github.com/groue/GRDB.swift/blob/master/README.md#fetchedrecordscontroller
|
||||
[FetchedRecordsController]: ../README.md#fetchedrecordscontroller
|
||||
[Fluent]: https://github.com/vapor/fluent
|
||||
[FMDB]: http://github.com/ccgus/fmdb
|
||||
[GRDB]: http://github.com/groue/GRDB.swift
|
||||
[GRDBObjc]: http://github.com/groue/GRDBObjc
|
||||
[Persistable]: https://github.com/groue/GRDB.swift/blob/master/README.md#records
|
||||
[PersistableRecord]: ../README.md#records
|
||||
[Realm]: http://realm.io
|
||||
[RowConvertible]: https://github.com/groue/GRDB.swift/blob/master/README.md#records
|
||||
[FetchableRecord]: ../README.md#records
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[RxSwift]: https://github.com/ReactiveX/RxSwift
|
||||
[SQLite.swift]: http://github.com/stephencelis/SQLite.swift
|
||||
[StORM]: https://www.perfect.org/docs/StORM.html
|
||||
[Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery
|
||||
[TableMapping]: https://github.com/groue/GRDB.swift/blob/master/README.md#records
|
||||
[TransactionObserver]: https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol
|
||||
[TableRecord]: ../README.md#records
|
||||
[TransactionObserver]: ../README.md#transactionobserver-protocol
|
||||
[query interface]: ../README.md#the-query-interface
|
||||
[associations]: AssociationsBasics.md
|
||||
@@ -3,7 +3,7 @@ Pod::Spec.new do |s|
|
||||
s.version = '2.10.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
s.homepage = 'https://github.com/groue/GRDB.swift'
|
||||
s.author = { 'Gwendal Roué' => 'gr@pierlis.com' }
|
||||
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
|
||||
|
||||
@@ -19,6 +19,9 @@
|
||||
<FileRef
|
||||
location = "group:Issue156.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:/Users/groue/Documents/git/groue/GRDB.swift/Playgrounds/CustomizedDecodingOfDatabaseRows.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:MyPlayground.playground">
|
||||
</FileRef>
|
||||
|
||||
@@ -28,8 +28,8 @@ 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<IteratorCursor<Iterator>, SegmentOfResult>> {
|
||||
return IteratorCursor(self).flatMap(transform)
|
||||
public func flatMap<SegmentOfResult: Cursor>(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<AnyCursor<Iterator.Element>, SegmentOfResult>> {
|
||||
return AnyCursor(self).flatMap(transform)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,7 +132,6 @@ extension Cursor {
|
||||
return nil
|
||||
}
|
||||
|
||||
#if swift(>=4.1)
|
||||
/// 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> {
|
||||
@@ -143,13 +142,6 @@ extension Cursor {
|
||||
public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
|
||||
return compactMap(transform)
|
||||
}
|
||||
#else
|
||||
/// Returns a cursor over the concatenated non-nil results of mapping
|
||||
/// transform over this cursor.
|
||||
public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
|
||||
return map(transform).filter { $0 != nil }.map { $0! }
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Returns a cursor that skips any initial elements that satisfy
|
||||
/// `predicate`.
|
||||
@@ -168,7 +160,7 @@ extension Cursor {
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the cursor, the result is an empty cursor.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst(2))
|
||||
/// // Prints "[3, 4, 5]"
|
||||
/// try print(numbers.dropFirst(10))
|
||||
@@ -186,7 +178,7 @@ extension Cursor {
|
||||
///
|
||||
/// The following example drops the first element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst())
|
||||
/// // Prints "[2, 3, 4, 5]"
|
||||
///
|
||||
@@ -203,7 +195,7 @@ extension Cursor {
|
||||
/// The cursor must be finite. If the number of elements to drop exceeds
|
||||
/// the number of elements in the cursor, the result is an empty array.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast(2))
|
||||
/// // Prints "[1, 2, 3]"
|
||||
/// try print(numbers.dropLast(10))
|
||||
@@ -236,7 +228,7 @@ extension Cursor {
|
||||
///
|
||||
/// The following example drops the last element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast())
|
||||
/// // Prints "[1, 2, 3, 4]"
|
||||
///
|
||||
@@ -249,8 +241,8 @@ 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, IteratorCursor<SegmentOfResult.Iterator>>> {
|
||||
return flatMap { try IteratorCursor(transform($0)) }
|
||||
public func flatMap<SegmentOfResult: Sequence>(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor<MapCursor<Self, AnyCursor<SegmentOfResult.Element>>> {
|
||||
return flatMap { try AnyCursor(transform($0)) }
|
||||
}
|
||||
|
||||
/// Returns a cursor over the concatenated results of mapping transform
|
||||
@@ -318,7 +310,7 @@ extension Cursor {
|
||||
/// If the maximum length exceeds the number of elements in the cursor,
|
||||
/// the result contains all the elements in the cursor.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.prefix(2))
|
||||
/// // Prints "[1, 2]"
|
||||
/// try print(numbers.prefix(10))
|
||||
@@ -378,7 +370,7 @@ extension Cursor {
|
||||
/// elements in the cursor, the result contains all the elements in the
|
||||
/// cursor.
|
||||
///
|
||||
/// let numbers = IteratorCursor([1, 2, 3, 4, 5])
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.suffix(2))
|
||||
/// // Prints "[4, 5]"
|
||||
/// try print(numbers.suffix(10))
|
||||
@@ -472,7 +464,7 @@ extension Cursor where Element: Cursor {
|
||||
|
||||
extension Cursor where Element: Sequence {
|
||||
/// Returns the elements of this cursor of sequences, concatenated.
|
||||
public func joined() -> FlattenCursor<MapCursor<Self, IteratorCursor<Element.Iterator>>> {
|
||||
public func joined() -> FlattenCursor<MapCursor<Self, AnyCursor<Element.Element>>> {
|
||||
return flatMap { $0 }
|
||||
}
|
||||
}
|
||||
@@ -509,7 +501,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 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
|
||||
@@ -518,6 +510,19 @@ public class AnyCursor<Element> : Cursor {
|
||||
element = base.next
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps a base iterator but whose type depends only
|
||||
/// on the base iterator’s element type
|
||||
public convenience init<I: IteratorProtocol>(iterator: I) where I.Element == Element {
|
||||
var iterator = iterator
|
||||
self.init { iterator.next() }
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps a base sequence but whose type depends only
|
||||
/// on the base sequence’s element type
|
||||
public convenience init<S: Sequence>(_ s: S) where S.Element == Element {
|
||||
self.init(iterator: s.makeIterator())
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
public init(_ body: @escaping () throws -> Element?) {
|
||||
element = body
|
||||
@@ -749,25 +754,3 @@ public final class PrefixWhileCursor<Base: Cursor> : Cursor {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// A Cursor whose elements are those of a sequence iterator.
|
||||
public final class IteratorCursor<Base: IteratorProtocol> : Cursor {
|
||||
private var base: Base
|
||||
|
||||
/// Creates a cursor from a sequence iterator.
|
||||
public init(_ base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
/// Creates a cursor from a sequence.
|
||||
public init<S: Sequence>(_ s: S) where S.Iterator == Base {
|
||||
self.base = s.makeIterator()
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next
|
||||
/// element exists.
|
||||
/// :nodoc:
|
||||
public func next() -> Base.Element? {
|
||||
return base.next()
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,28 @@ extension Database {
|
||||
return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ?", arguments: [tableName.lowercased()]) != nil
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal SQLite table.
|
||||
///
|
||||
/// Those are tables whose name begins with "sqlite_".
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/fileformat2.html
|
||||
public func isSQLiteInternalTable(_ tableName: String) -> Bool {
|
||||
// https://www.sqlite.org/fileformat2.html#internal_schema_objects
|
||||
// > The names of internal schema objects always begin with "sqlite_"
|
||||
// > and any table, index, view, or trigger whose name begins with
|
||||
// > "sqlite_" is an internal schema object. SQLite prohibits
|
||||
// > applications from creating objects whose names begin with
|
||||
// > "sqlite_".
|
||||
return tableName.starts(with: "sqlite_")
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal GRDB table.
|
||||
///
|
||||
/// Those are tables whose name begins with "grdb_".
|
||||
public func isGRDBInternalTable(_ tableName: String) -> Bool {
|
||||
return tableName.starts(with: "grdb_")
|
||||
}
|
||||
|
||||
/// Returns whether a view exists.
|
||||
public func viewExists(_ viewName: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
|
||||
@@ -129,14 +151,6 @@ extension Database {
|
||||
return primaryKey
|
||||
}
|
||||
|
||||
/// The number of columns in the table named `tableName`.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
@available(*, deprecated, message: "Use db.columns(in: tableName).count instead")
|
||||
public func columnCount(in tableName: String) throws -> Int {
|
||||
return try columns(in: tableName).count
|
||||
}
|
||||
|
||||
/// The indexes on table named `tableName`; returns the empty array if the
|
||||
/// table does not exist.
|
||||
///
|
||||
@@ -160,6 +174,14 @@ extension Database {
|
||||
return IndexInfo(name: indexName, columns: columns, unique: unique)
|
||||
}
|
||||
|
||||
if indexes.isEmpty {
|
||||
// PRAGMA index_list doesn't throw any error when table does
|
||||
// not exist. So let's check if table exists:
|
||||
if try tableExists(tableName) == false {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
}
|
||||
|
||||
schemaCache.set(indexes: indexes, forTable: tableName)
|
||||
return indexes
|
||||
}
|
||||
@@ -179,7 +201,7 @@ extension Database {
|
||||
var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = []
|
||||
var previousId: Int? = nil
|
||||
for row in try Row.fetchAll(self, "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
|
||||
// row = <Row id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"...">
|
||||
// row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."]
|
||||
let id: Int = row[0]
|
||||
let seq: Int = row[1]
|
||||
let table: String = row[2]
|
||||
@@ -194,6 +216,14 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
if rawForeignKeys.isEmpty {
|
||||
// PRAGMA foreign_key_list doesn't throw any error when table does
|
||||
// not exist. So let's check if table exists:
|
||||
if try tableExists(tableName) == false {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
}
|
||||
|
||||
let foreignKeys = try rawForeignKeys.map { (destinationTable, columnMapping) -> ForeignKeyInfo in
|
||||
let orderedMapping = columnMapping
|
||||
.sorted { $0.seq < $1.seq }
|
||||
@@ -218,24 +248,24 @@ extension Database {
|
||||
}
|
||||
|
||||
/// Returns the actual name of the database table
|
||||
func canonicalName(table: String) throws -> String {
|
||||
if let canonicalName = schemaCache.canonicalName(table: table) {
|
||||
return canonicalName
|
||||
func canonicalTableName(_ tableName: String) throws -> String {
|
||||
if let canonicalTableName = schemaCache.canonicalTableName(tableName) {
|
||||
return canonicalTableName
|
||||
}
|
||||
|
||||
guard let canonicalName = try String.fetchOne(self, """
|
||||
guard let canonicalTableName = try String.fetchOne(self, """
|
||||
SELECT name FROM (
|
||||
SELECT name, type FROM sqlite_master
|
||||
UNION
|
||||
SELECT name, type FROM sqlite_temp_master)
|
||||
WHERE type = 'table' AND LOWER(name) = ?
|
||||
""", arguments: [table.lowercased()])
|
||||
""", arguments: [tableName.lowercased()])
|
||||
else {
|
||||
throw DatabaseError(message: "no such table: \(table)")
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
|
||||
schemaCache.set(canonicalName: canonicalName, forTable: table)
|
||||
return canonicalName
|
||||
schemaCache.set(canonicalTableName: canonicalTableName, forTable: tableName)
|
||||
return canonicalTableName
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,11 +343,11 @@ extension Database {
|
||||
/// This type closely matches the information returned by the
|
||||
/// `table_info` pragma.
|
||||
///
|
||||
/// > CREATE TABLE players (
|
||||
/// > CREATE TABLE player (
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// firstName TEXT,
|
||||
/// lastName TEXT)
|
||||
/// > PRAGMA table_info("players")
|
||||
/// > PRAGMA table_info("player")
|
||||
/// cid name type notnull dflt_value pk
|
||||
/// ---- ----- ------- -------- ---------- ---
|
||||
/// 0 id INTEGER 0 NULL 1
|
||||
@@ -325,7 +355,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 : RowConvertible {
|
||||
public struct ColumnInfo : FetchableRecord {
|
||||
let cid: Int
|
||||
|
||||
/// The column name
|
||||
@@ -348,14 +378,14 @@ public struct ColumnInfo : RowConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE players(
|
||||
/// CREATE TABLE player(
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// name TEXT DEFAULT 'Anonymous',
|
||||
/// score INT DEFAULT 0,
|
||||
/// creationDate DATE DEFAULT CURRENT_TIMESTAMP
|
||||
/// )
|
||||
/// """)
|
||||
/// let columnInfos = try db.columns(in: "players")
|
||||
/// let columnInfos = try db.columns(in: "player")
|
||||
/// columnInfos[0].defaultValueSQL // nil
|
||||
/// columnInfos[1].defaultValueSQL // "'Anoynymous'"
|
||||
/// columnInfos[2].defaultValueSQL // "0"
|
||||
@@ -410,38 +440,38 @@ public struct IndexInfo {
|
||||
///
|
||||
/// When the table's primary key is the rowid:
|
||||
///
|
||||
/// // CREATE TABLE items (name TEXT)
|
||||
/// let pk = try db.primaryKey("items")
|
||||
/// // CREATE TABLE item (name TEXT)
|
||||
/// let pk = try db.primaryKey("item")
|
||||
/// pk.columns // ["rowid"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // true
|
||||
///
|
||||
/// // CREATE TABLE citizens (
|
||||
/// // CREATE TABLE citizen (
|
||||
/// // id INTEGER PRIMARY KEY,
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = try db.primaryKey("citizens")!
|
||||
/// let pk = try db.primaryKey("citizen")!
|
||||
/// pk.columns // ["id"]
|
||||
/// pk.rowIDColumn // "id"
|
||||
/// pk.isRowID // true
|
||||
///
|
||||
/// When the table's primary key is not the rowid:
|
||||
///
|
||||
/// // CREATE TABLE countries (
|
||||
/// // CREATE TABLE country (
|
||||
/// // isoCode TEXT NOT NULL PRIMARY KEY
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = db.primaryKey("countries")!
|
||||
/// let pk = db.primaryKey("country")!
|
||||
/// pk.columns // ["isoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
///
|
||||
/// // CREATE TABLE citizenships (
|
||||
/// // citizenID INTEGER NOT NULL REFERENCES citizens(id)
|
||||
/// // countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode)
|
||||
/// // CREATE TABLE citizenship (
|
||||
/// // citizenID INTEGER NOT NULL REFERENCES citizen(id)
|
||||
/// // countryIsoCode TEXT NOT NULL REFERENCES country(isoCode)
|
||||
/// // PRIMARY KEY (citizenID, countryIsoCode)
|
||||
/// // )
|
||||
/// let pk = db.primaryKey("citizenships")!
|
||||
/// let pk = db.primaryKey("citizenship")!
|
||||
/// pk.columns // ["citizenID", "countryIsoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import Foundation
|
||||
|
||||
extension Database {
|
||||
|
||||
|
||||
// MARK: - Statements
|
||||
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
@@ -19,7 +19,7 @@ extension Database {
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?", prepFlags: 0)
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
@@ -34,7 +34,7 @@ extension Database {
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
|
||||
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
@@ -55,7 +55,7 @@ extension Database {
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)")
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
@@ -68,7 +68,7 @@ extension Database {
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)", prepFlags: 0)
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)", prepFlags: 0)
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
@@ -83,7 +83,7 @@ extension Database {
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedUpdateStatement("INSERT INTO players (name) VALUES (?)")
|
||||
/// let statement = try db.cachedUpdateStatement("INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
@@ -105,13 +105,13 @@ extension Database {
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// try db.execute(
|
||||
/// "INSERT INTO players (name) VALUES (:name)",
|
||||
/// "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
///
|
||||
/// try db.execute("""
|
||||
/// INSERT INTO players (name) VALUES (?);
|
||||
/// INSERT INTO players (name) VALUES (?);
|
||||
/// INSERT INTO players (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments; ['Arthur', 'Barbara', 'Craig'])
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
|
||||
@@ -21,8 +21,8 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// let dbQueue = DatabaseQueue(...)
|
||||
///
|
||||
/// // The Database is the `db` in the closure:
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.execute(...)
|
||||
/// try dbQueue.write { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
public final class Database {
|
||||
// The Database class is not thread-safe. An instance should always be
|
||||
@@ -98,8 +98,6 @@ public final class Database {
|
||||
|
||||
/// True if the database connection is currently in a transaction.
|
||||
public var isInsideTransaction: Bool {
|
||||
if isClosed { return false }
|
||||
|
||||
// https://sqlite.org/c3ref/get_autocommit.html
|
||||
//
|
||||
// > The sqlite3_get_autocommit() interface returns non-zero or zero if
|
||||
@@ -109,6 +107,12 @@ public final class Database {
|
||||
// > Autocommit mode is on by default. Autocommit mode is disabled by a
|
||||
// > BEGIN statement. Autocommit mode is re-enabled by a COMMIT
|
||||
// > or ROLLBACK.
|
||||
//
|
||||
// > If another thread changes the autocommit status of the database
|
||||
// > connection while this routine is running, then the return value
|
||||
// > is undefined.
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
if isClosed { return false } // Support for SerializedDatabasae.deinit
|
||||
return sqlite3_get_autocommit(sqliteConnection) == 0
|
||||
}
|
||||
|
||||
@@ -146,7 +150,9 @@ public final class Database {
|
||||
lazy var observationBroker = DatabaseObservationBroker(self)
|
||||
|
||||
/// The list of compile options used when building SQLite
|
||||
static let sqliteCompileOptions: Set<String> = DatabaseQueue().inDatabase { try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS")) }
|
||||
static let sqliteCompileOptions: Set<String> = DatabaseQueue().inDatabase {
|
||||
try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS"))
|
||||
}
|
||||
|
||||
// MARK: - Private properties
|
||||
|
||||
@@ -298,7 +304,7 @@ extension Database {
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.configuration.trace!(sql)
|
||||
}, dbPointer)
|
||||
#else
|
||||
#elseif !os(Linux)
|
||||
if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) {
|
||||
sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
|
||||
guard let stmt = stmt else { return SQLITE_OK }
|
||||
@@ -316,6 +322,12 @@ extension Database {
|
||||
db.configuration.trace!(sql)
|
||||
}, dbPointer)
|
||||
}
|
||||
#else
|
||||
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
|
||||
guard let sql = sql.map({ String(cString: $0) }) else { return }
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.configuration.trace!(sql)
|
||||
}, dbPointer)
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -523,6 +535,25 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Read-Only Access
|
||||
|
||||
/// Grants read-only access, starting SQLite 3.8.0
|
||||
func readOnly<T>(_ block: () throws -> T) rethrows -> T {
|
||||
if configuration.readonly {
|
||||
return try block()
|
||||
}
|
||||
|
||||
// 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)
|
||||
// Assume those pragmas never fail
|
||||
try! execute("PRAGMA query_only = 1")
|
||||
defer { try! execute("PRAGMA query_only = 0") }
|
||||
return try block()
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Transactions & Savepoint
|
||||
@@ -544,7 +575,7 @@ extension Database {
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
@@ -639,6 +670,7 @@ extension Database {
|
||||
switch completion {
|
||||
case .commit:
|
||||
try execute("RELEASE SAVEPOINT grdb")
|
||||
assert(!topLevelSavepoint || !isInsideTransaction)
|
||||
needsRollback = false
|
||||
case .rollback:
|
||||
needsRollback = true
|
||||
@@ -675,7 +707,7 @@ extension Database {
|
||||
///
|
||||
/// - parameter kind: The transaction type (default nil). If nil, the
|
||||
/// transaction type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
|
||||
@@ -724,14 +756,17 @@ extension Database {
|
||||
// The second technique is more robust, because we don't have to guess
|
||||
// which rollback errors should be ignored, and which rollback errors
|
||||
// should be exposed to the library user.
|
||||
SchedulingWatchdog.preconditionValidQueue(self) // guard sqlite3_get_autocommit
|
||||
if sqlite3_get_autocommit(sqliteConnection) == 0 {
|
||||
try execute("ROLLBACK TRANSACTION")
|
||||
}
|
||||
assert(!isInsideTransaction)
|
||||
}
|
||||
|
||||
/// Commits a database transaction.
|
||||
public func commit() throws {
|
||||
try execute("COMMIT TRANSACTION")
|
||||
assert(!isInsideTransaction)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -841,14 +876,6 @@ extension Database {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
#if !swift(>=4.1)
|
||||
/// The hash value
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
return rawValue.hashValue
|
||||
}
|
||||
#endif
|
||||
|
||||
/// The `BINARY` built-in SQL collation
|
||||
public static let binary = CollationName("BINARY")
|
||||
|
||||
@@ -861,8 +888,8 @@ extension Database {
|
||||
|
||||
/// An SQL column type.
|
||||
///
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("id", .integer).primaryKey()
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.column("title", .text)
|
||||
/// }
|
||||
///
|
||||
@@ -880,14 +907,6 @@ extension Database {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
#if !swift(>=4.1)
|
||||
/// The hash value
|
||||
/// :nodoc:
|
||||
public var hashValue: Int {
|
||||
return rawValue.hashValue
|
||||
}
|
||||
#endif
|
||||
|
||||
/// The `TEXT` SQL column type
|
||||
public static let text = ColumnType("TEXT")
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ public final class DatabaseCollation {
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
|
||||
/// try db.execute("CREATE TABLE file (name TEXT COLLATE localized_standard")
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
|
||||
@@ -139,16 +139,6 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
|
||||
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
|
||||
}
|
||||
|
||||
#if !swift(>=4.1)
|
||||
// Equatable
|
||||
extension ResultCode {
|
||||
/// :nodoc:
|
||||
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
|
||||
return lhs.rawValue == rhs.rawValue
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// CustomStringConvertible
|
||||
extension ResultCode {
|
||||
/// :nodoc:
|
||||
|
||||
@@ -10,16 +10,6 @@ public final class DatabaseFunction: Hashable {
|
||||
private struct Identity: Hashable {
|
||||
let name: String
|
||||
let nArg: Int32 // -1 for variadic functions
|
||||
|
||||
#if !swift(>=4.1)
|
||||
var hashValue: Int {
|
||||
return name.hashValue ^ nArg.hashValue
|
||||
}
|
||||
|
||||
static func == (lhs: Identity, rhs: Identity) -> Bool {
|
||||
return lhs.name == rhs.name && lhs.nArg == rhs.nArg
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
public var name: String { return identity.name }
|
||||
@@ -82,7 +72,7 @@ public final class DatabaseFunction: Hashable {
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute("CREATE TABLE test(i)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (2)")
|
||||
@@ -357,7 +347,7 @@ extension DatabaseFunction {
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute("CREATE TABLE test(i)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (2)")
|
||||
@@ -373,10 +363,10 @@ public protocol DatabaseAggregate {
|
||||
/// aggregate function.
|
||||
///
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM players
|
||||
/// SELECT maxLength(name) FROM player
|
||||
///
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM players
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM player
|
||||
///
|
||||
/// This method is never called after the finalize() method has been called.
|
||||
mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
|
||||
@@ -9,7 +9,7 @@ import Foundation
|
||||
#endif
|
||||
|
||||
/// A DatabasePool grants concurrent accesses to an SQLite database.
|
||||
public final class DatabasePool {
|
||||
public final class DatabasePool: DatabaseWriter {
|
||||
private let writer: SerializedDatabase
|
||||
private var readerConfig: Configuration
|
||||
private var readerPool: Pool<SerializedDatabase>!
|
||||
@@ -119,7 +119,7 @@ extension DatabasePool {
|
||||
///
|
||||
/// - parameter kind: The checkpoint mode (default passive)
|
||||
public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws {
|
||||
try write { db in
|
||||
try writer.sync { db in
|
||||
// TODO: read https://www.sqlite.org/c3ref/wal_checkpoint_v2.html and
|
||||
// check whether we need a busy handler on writer and/or readers
|
||||
// when kind is not .Passive.
|
||||
@@ -142,7 +142,7 @@ extension DatabasePool {
|
||||
/// See also setupMemoryManagement(application:)
|
||||
public func releaseMemory() {
|
||||
// TODO: test that this method blocks the current thread until all database accesses are completed.
|
||||
write { $0.releaseMemory() }
|
||||
writer.sync { $0.releaseMemory() }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.releaseMemory() }
|
||||
}
|
||||
@@ -201,7 +201,7 @@ extension DatabasePool {
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
try readerPool.clear(andThen: {
|
||||
try write { try $0.change(passphrase: passphrase) }
|
||||
try writer.sync { try $0.change(passphrase: passphrase) }
|
||||
readerConfig.passphrase = passphrase
|
||||
})
|
||||
}
|
||||
@@ -224,14 +224,14 @@ extension DatabasePool : DatabaseReader {
|
||||
///
|
||||
/// try dbPool.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `wines` table is modified between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// // `wine` table is modified between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// }
|
||||
///
|
||||
/// try dbPool.read { db in
|
||||
/// // Now this value may be different:
|
||||
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
@@ -266,8 +266,8 @@ extension DatabasePool : DatabaseReader {
|
||||
/// try dbPool.unsafeRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iteration is safe, though:
|
||||
@@ -303,8 +303,8 @@ extension DatabasePool : DatabaseReader {
|
||||
/// try dbPool.unsafeReentrantRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iteration is safe, though:
|
||||
@@ -315,8 +315,8 @@ extension DatabasePool : DatabaseReader {
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
@@ -335,179 +335,6 @@ extension DatabasePool : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
var readers: [SerializedDatabase] = []
|
||||
readerPool.forEach { reader in
|
||||
// We can't check for reader.onValidQueue here because
|
||||
// Pool.forEach() runs its closure argument in some arbitrary
|
||||
// dispatch queue. We thus extract the reader so that we can query
|
||||
// it below.
|
||||
readers.append(reader)
|
||||
}
|
||||
|
||||
// Now the readers array contains some readers. The pool readers may
|
||||
// already be different, because some other thread may have started
|
||||
// a new read, for example.
|
||||
//
|
||||
// This doesn't matter: the reader we are looking for is already on
|
||||
// its own dispatch queue. If it exists, is still in use, thus still
|
||||
// in the pool, and thus still relevant for our check:
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// dbPool.add(function: fn)
|
||||
/// try dbPool.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
functions.update(with: function)
|
||||
write { $0.add(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(function: function) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
functions.remove(function)
|
||||
write { $0.remove(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(function: function) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// dbPool.add(collation: collation)
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
collations.update(with: collation)
|
||||
write { $0.add(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
collations.remove(collation)
|
||||
write { $0.remove(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool : DatabaseWriter {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// To maintain database integrity, and preserve eventual concurrent reads
|
||||
/// from seeing an inconsistent database state, prefer the
|
||||
/// writeInTransaction method.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters block: A block that executes SQL statements and return
|
||||
/// either .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the block returns .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent readers do not see partial changes:
|
||||
///
|
||||
/// dbPool.writeInTransaction { db in
|
||||
/// // Eventually preserve a zero balance
|
||||
/// try db.execute(db, "INSERT INTO credits ...", arguments: [amount])
|
||||
/// try db.execute(db, "INSERT INTO debits ...", arguments: [amount])
|
||||
/// }
|
||||
///
|
||||
/// dbPool.read { db in
|
||||
/// // Here the balance is guaranteed to be zero
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block, or any error establishing the
|
||||
/// transaction.
|
||||
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try write { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// try dbPool.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue,
|
||||
/// wrapped in a deferred transaction.
|
||||
///
|
||||
@@ -519,12 +346,12 @@ extension DatabasePool : DatabaseWriter {
|
||||
/// database updates are *not visible* inside the block.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("DELETE FROM players")
|
||||
/// try db.execute("DELETE FROM player")
|
||||
/// try dbPool.readFromCurrentState { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM player")!
|
||||
/// }
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// try db.execute("INSERT INTO player ...")
|
||||
/// }
|
||||
///
|
||||
/// This method blocks the current thread until the isolation guarantee has
|
||||
@@ -581,7 +408,7 @@ extension DatabasePool : DatabaseWriter {
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
|
||||
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction. If this error is raised from a DatabasePool.write block, use DatabasePool.writeWithoutTransaction instead (and use transactions when needed).")
|
||||
}
|
||||
|
||||
// The semaphore that blocks the writing dispatch queue until snapshot
|
||||
@@ -615,6 +442,193 @@ extension DatabasePool : DatabaseWriter {
|
||||
throw readError
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
var readers: [SerializedDatabase] = []
|
||||
readerPool.forEach { reader in
|
||||
// We can't check for reader.onValidQueue here because
|
||||
// Pool.forEach() runs its closure argument in some arbitrary
|
||||
// dispatch queue. We thus extract the reader so that we can query
|
||||
// it below.
|
||||
readers.append(reader)
|
||||
}
|
||||
|
||||
// Now the readers array contains some readers. The pool readers may
|
||||
// already be different, because some other thread may have started
|
||||
// a new read, for example.
|
||||
//
|
||||
// This doesn't matter: the reader we are looking for is already on
|
||||
// its own dispatch queue. If it exists, is still in use, thus still
|
||||
// in the pool, and thus still relevant for our check:
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result of the block.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed not to see any changes
|
||||
/// performed in the block until they are all saved in the database.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters block: A block that executes SQL statements.
|
||||
/// - throws: The error thrown by the block, or by the wrapping transaction.
|
||||
public func write<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try writer.sync { db in
|
||||
var result: T? = nil
|
||||
try db.inTransaction {
|
||||
result = try block(db)
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// Eventual concurrent reads may see changes performed in the block before
|
||||
/// the block completes.
|
||||
///
|
||||
/// The block is guaranteed to be executed outside of a transaction.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters block: A block that executes SQL statements and return
|
||||
/// either .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the block returns .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed not to see any changes
|
||||
/// performed in the block until they are all saved in the database.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block, or any error establishing the
|
||||
/// transaction.
|
||||
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes an update block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// try dbPool.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// Eventual concurrent reads may see changes performed in the block before
|
||||
/// the block completes.
|
||||
///
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// dbPool.add(function: fn)
|
||||
/// try dbPool.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
functions.update(with: function)
|
||||
writer.sync { $0.add(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(function: function) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
functions.remove(function)
|
||||
writer.sync { $0.remove(function: function) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(function: function) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// dbPool.add(collation: collation)
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
collations.update(with: collation)
|
||||
writer.sync { $0.add(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.add(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
collations.remove(collation)
|
||||
writer.sync { $0.remove(collation: collation) }
|
||||
readerPool.forEach { reader in
|
||||
reader.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
@@ -622,7 +636,7 @@ extension DatabasePool {
|
||||
// MARK: - Snapshots
|
||||
|
||||
/// Creates a database snapshot.
|
||||
//:
|
||||
///
|
||||
/// The snapshot sees an unchanging database content, as it existed at the
|
||||
/// moment it was created.
|
||||
///
|
||||
@@ -631,7 +645,7 @@ extension DatabasePool {
|
||||
///
|
||||
/// let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in
|
||||
/// try Player.deleteAll()
|
||||
/// return dbPool.makeSnapshot()
|
||||
/// return try dbPool.makeSnapshot()
|
||||
/// }
|
||||
/// // <- Other threads may modify the database here
|
||||
/// let snapshot2 = try dbPool.makeSnapshot()
|
||||
@@ -646,11 +660,47 @@ extension DatabasePool {
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// It is forbidden to create a snapshot from the writer protected dispatch
|
||||
/// queue when a transaction is opened, though, because it is likely a
|
||||
/// programmer error:
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// // fatal error: makeSnapshot() must not be called from inside a transaction
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// return .commit
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// To avoid this fatal error, create the snapshot *before* or *after* the
|
||||
/// transaction:
|
||||
///
|
||||
/// try dbPool.writeWithoutTransaction { db in
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// }
|
||||
///
|
||||
/// You can create as many snapshots as you need, regardless of the maximum
|
||||
/// number of reader connections in the pool.
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
|
||||
public func makeSnapshot() throws -> DatabaseSnapshot {
|
||||
// Sanity check
|
||||
if writer.onValidQueue {
|
||||
writer.execute { db in
|
||||
GRDBPrecondition(!db.isInsideTransaction, "makeSnapshot() must not be called from inside a transaction.")
|
||||
}
|
||||
}
|
||||
|
||||
let snapshot = try DatabaseSnapshot(path: path, configuration: writer.configuration)
|
||||
snapshot.read { setupDatabase($0) }
|
||||
return snapshot
|
||||
|
||||
@@ -5,22 +5,22 @@ import UIKit
|
||||
#endif
|
||||
|
||||
/// A DatabaseQueue serializes access to an SQLite database.
|
||||
public final class DatabaseQueue {
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
public final class DatabaseQueue: DatabaseWriter {
|
||||
private var writer: SerializedDatabase
|
||||
#if os(iOS)
|
||||
private weak var application: UIApplication?
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
return writer.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
public var path: String {
|
||||
return serializedDatabase.path
|
||||
return writer.path
|
||||
}
|
||||
|
||||
// MARK: - Initializers
|
||||
@@ -36,7 +36,7 @@ public final class DatabaseQueue {
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache())
|
||||
@@ -51,7 +51,7 @@ public final class DatabaseQueue {
|
||||
/// - parameter configuration: A configuration.
|
||||
public init(configuration: Configuration = Configuration()) {
|
||||
// Assume SQLite always succeeds creating an in-memory database
|
||||
serializedDatabase = try! SerializedDatabase(
|
||||
writer = try! SerializedDatabase(
|
||||
path: ":memory:",
|
||||
configuration: configuration,
|
||||
schemaCache: SimpleDatabaseSchemaCache())
|
||||
@@ -68,56 +68,6 @@ public final class DatabaseQueue {
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Database Access
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let players = try dbQueue.inDatabase { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inDatabase<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the block returns .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try inDatabase { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Memory management
|
||||
@@ -128,7 +78,7 @@ extension DatabaseQueue {
|
||||
///
|
||||
/// See also setupMemoryManagement(application:)
|
||||
public func releaseMemory() {
|
||||
inDatabase { $0.releaseMemory() }
|
||||
writer.sync { $0.releaseMemory() }
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
@@ -181,12 +131,12 @@ extension DatabaseQueue {
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
try inDatabase { try $0.change(passphrase: passphrase) }
|
||||
try writer.sync { try $0.change(passphrase: passphrase) }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension DatabaseQueue : DatabaseReader {
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@@ -194,51 +144,178 @@ extension DatabaseQueue : DatabaseReader {
|
||||
/// and returns its result.
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and
|
||||
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
|
||||
/// resultCode is `SQLITE_READONLY`.
|
||||
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
|
||||
/// SQLCipher), attempts to write in the database from this meethod throw a
|
||||
/// DatabaseError of resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
// 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)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return try inDatabase { try readOnly($0, block) }
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
return try inDatabase { try readOnly($0, block) }
|
||||
} else {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseReader.unsafeRead`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
return try writer.sync { db in
|
||||
try db.readOnly { try block(db) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// try dbQueue.unsafeReentrantRead { db in
|
||||
/// try db.execute(...)
|
||||
/// let players = try dbQueue.unsafeRead { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let players = try dbQueue.unsafeReentrantRead { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
return try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes *block*.
|
||||
///
|
||||
/// This method must be called from the protected database dispatch queue,
|
||||
/// outside of a transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
|
||||
/// SQLCipher), attempts to write in the database from this meethod throw a
|
||||
/// DatabaseError of resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// See `DatabaseWriter.readFromCurrentState`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
|
||||
// Check that we're on the correct queue...
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
|
||||
db.readOnly { block(db) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown.
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that executes SQL statements.
|
||||
/// - throws: An eventual database error, or the error thrown by the block.
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync { db in
|
||||
var result: T? = nil
|
||||
try db.inTransaction {
|
||||
result = try block(db)
|
||||
return .commit
|
||||
}
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, wrapped
|
||||
/// inside a transaction.
|
||||
///
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the block returns .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws {
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let players = try dbQueue.writeWithoutTransaction { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// // INSERT INTO player ...
|
||||
/// let players = try dbQueue.inDatabase { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inDatabase<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.sync(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// // INSERT INTO player ...
|
||||
/// try dbQueue.unsafeReentrantWrite { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It is unsafe because it fosters dangerous
|
||||
/// concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
@@ -252,16 +329,16 @@ extension DatabaseQueue : DatabaseReader {
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try dbQueue.read { db in
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
|
||||
/// }
|
||||
public func add(function: DatabaseFunction) {
|
||||
inDatabase { $0.add(function: function) }
|
||||
writer.sync { $0.add(function: function) }
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
inDatabase { $0.remove(function: function) }
|
||||
writer.sync { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
@@ -272,83 +349,16 @@ extension DatabaseQueue : DatabaseReader {
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// dbQueue.add(collation: collation)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
inDatabase { $0.add(collation: collation) }
|
||||
writer.sync { $0.add(collation: collation) }
|
||||
}
|
||||
|
||||
/// Remove a collation.
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
inDatabase { $0.remove(collation: collation) }
|
||||
writer.sync { $0.remove(collation: collation) }
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseQueue : DatabaseWriter {
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes *block*.
|
||||
///
|
||||
/// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and
|
||||
/// SQLCipher, attempts to write in the database throw a DatabaseError whose
|
||||
/// resultCode is `SQLITE_READONLY`.
|
||||
///
|
||||
/// This method must be called from the protected database dispatch queue,
|
||||
/// outside of a transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// See `DatabaseWriter.readFromCurrentState`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
|
||||
// Check that we're on the correct queue...
|
||||
serializedDatabase.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
|
||||
|
||||
// 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)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
readOnly(db, block)
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, *) {
|
||||
readOnly(db, block)
|
||||
} else {
|
||||
block(db)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Unsafe Database Access
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// try dbQueue.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
}
|
||||
|
||||
private func readOnly<T>(_ db: Database, _ block: (Database) throws -> T) rethrows -> T {
|
||||
guard !db.configuration.readonly else {
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
// Assume those pragmas never fail
|
||||
try! db.execute("PRAGMA query_only = 1")
|
||||
defer { try! db.execute("PRAGMA query_only = 0") }
|
||||
return try block(db)
|
||||
}
|
||||
@@ -31,14 +31,14 @@ public protocol DatabaseReader : class {
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `wines` table is modified between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// // `wine` table is modified between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// }
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Now this value may be different:
|
||||
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// }
|
||||
///
|
||||
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
|
||||
@@ -61,8 +61,8 @@ public protocol DatabaseReader : class {
|
||||
/// try reader.unsafeRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iterations are isolated, though:
|
||||
@@ -92,8 +92,8 @@ public protocol DatabaseReader : class {
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iterations are isolated, though:
|
||||
@@ -144,7 +144,7 @@ public protocol DatabaseReader : class {
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// reader.add(collation: collation)
|
||||
/// try reader.execute("SELECT * FROM files ORDER BY name COLLATE localized_standard")
|
||||
/// try reader.execute("SELECT * FROM file ORDER BY name COLLATE localized_standard")
|
||||
func add(collation: DatabaseCollation)
|
||||
|
||||
/// Remove a collation.
|
||||
|
||||
@@ -6,39 +6,39 @@
|
||||
/// cover a full table, or the combination of columns and rows (identified by
|
||||
/// their rowids):
|
||||
///
|
||||
/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
|
||||
/// |-------| |-------| |-------| |-------| |-------|
|
||||
/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
|
||||
/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
|
||||
/// |-------| |-------| |-------| |-------| |-------|
|
||||
/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
|
||||
///
|
||||
/// You don't create a database region directly. Instead, you use one of
|
||||
/// those methods:
|
||||
///
|
||||
/// - `SelectStatement.fetchedRegion`:
|
||||
/// - `SelectStatement.databaseRegion`:
|
||||
///
|
||||
/// let statement = db.makeSelectStatement("SELECT name, score FROM players")
|
||||
/// print(statement.fetchedRegion)
|
||||
/// // prints "players(name,score)"
|
||||
/// let statement = db.makeSelectStatement("SELECT name, score FROM player")
|
||||
/// print(statement.databaseRegion)
|
||||
/// // prints "player(name,score)"
|
||||
///
|
||||
/// - `Request.fetchedRegion(_:)`
|
||||
/// - `FetchRequest.databaseRegion(_:)`
|
||||
///
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// try print(request.fetchedRegion(db))
|
||||
/// // prints "players(*)[1]"
|
||||
/// try print(request.databaseRegion(db))
|
||||
/// // prints "player(*)[1]"
|
||||
///
|
||||
/// Database regions returned by requests can be more precise than regions
|
||||
/// returned by select statements. Especially, regions returned by statements
|
||||
/// don't know about rowids:
|
||||
///
|
||||
/// // A plain statement
|
||||
/// let statement = db.makeSelectStatement("SELECT * FROM players WHERE id = 1")
|
||||
/// statement.fetchedRegion // "players(*)"
|
||||
/// let statement = db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
|
||||
/// statement.databaseRegion // "player(*)"
|
||||
///
|
||||
/// // A query interface request that executes the same statement:
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// try request.fetchedRegion(db) // "players(*)[1]"
|
||||
/// try request.databaseRegion(db) // "player(*)[1]"
|
||||
public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
private let tableRegions: [String: TableRegion]?
|
||||
private init(tableRegions: [String: TableRegion]?) {
|
||||
@@ -51,8 +51,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
return tableRegions.isEmpty
|
||||
}
|
||||
|
||||
/// The full database: (All columns in all tables) × (all rows)
|
||||
static let fullDatabase = DatabaseRegion(tableRegions: nil)
|
||||
/// The region that covers the full database: all columns and all rows
|
||||
/// from all tables.
|
||||
public static let fullDatabase = DatabaseRegion(tableRegions: nil)
|
||||
|
||||
/// The empty database region
|
||||
public init() {
|
||||
@@ -255,14 +256,6 @@ private struct TableRegion: Equatable {
|
||||
return false
|
||||
}
|
||||
|
||||
#if !swift(>=4.1)
|
||||
static func == (lhs: TableRegion, rhs: TableRegion) -> Bool {
|
||||
if lhs.columns != rhs.columns { return false }
|
||||
if lhs.rowIds != rhs.rowIds { return false }
|
||||
return true
|
||||
}
|
||||
#endif
|
||||
|
||||
func intersection(_ other: TableRegion) -> TableRegion {
|
||||
let columnsIntersection: Set<String>?
|
||||
switch (self.columns, other.columns) {
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
protocol DatabaseSchemaCache {
|
||||
mutating func clear()
|
||||
|
||||
func canonicalName(table: String) -> String?
|
||||
mutating func set(canonicalName: String, forTable table: String)
|
||||
func canonicalTableName(_ table: String) -> String?
|
||||
mutating func set(canonicalTableName: String, forTable table: String)
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
|
||||
@@ -20,26 +20,26 @@ protocol DatabaseSchemaCache {
|
||||
|
||||
/// A thread-unsafe database schema cache
|
||||
struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private var canonicalNames: [String: String] = [:]
|
||||
private var canonicalTableNames: [String: String] = [:]
|
||||
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
|
||||
private var columns: [String: [ColumnInfo]] = [:]
|
||||
private var indexes: [String: [IndexInfo]] = [:]
|
||||
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
|
||||
|
||||
mutating func clear() {
|
||||
canonicalNames = [:]
|
||||
canonicalTableNames = [:]
|
||||
primaryKeys = [:]
|
||||
columns = [:]
|
||||
indexes = [:]
|
||||
foreignKeys = [:]
|
||||
}
|
||||
|
||||
func canonicalName(table: String) -> String? {
|
||||
return canonicalNames[table]
|
||||
func canonicalTableName(_ table: String) -> String? {
|
||||
return canonicalTableNames[table]
|
||||
}
|
||||
|
||||
mutating func set(canonicalName: String, forTable table: String) {
|
||||
canonicalNames[table] = table
|
||||
mutating func set(canonicalTableName: String, forTable table: String) {
|
||||
canonicalTableNames[table] = table
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
@@ -79,8 +79,8 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
struct EmptyDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
func clear() { }
|
||||
|
||||
func canonicalName(table: String) -> String? { return nil }
|
||||
func set(canonicalName: String, forTable table: String) { }
|
||||
func canonicalTableName(_ table: String) -> String? { return nil }
|
||||
func set(canonicalTableName: String, forTable table: String) { }
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil }
|
||||
func set(primaryKey: PrimaryKeyInfo, forTable table: String) { }
|
||||
|
||||
@@ -110,7 +110,7 @@ extension DatabaseSnapshot {
|
||||
/// }
|
||||
/// snapshot.add(collation: collation)
|
||||
/// let files = try snapshot.read { db in
|
||||
/// try File.fetchAll(db, "SELECT * FROM files ORDER BY name COLLATE localized_standard")
|
||||
/// try File.fetchAll(db, "SELECT * FROM file ORDER BY name COLLATE localized_standard")
|
||||
/// }
|
||||
public func add(collation: DatabaseCollation) {
|
||||
serializedDatabase.sync { $0.add(collation: collation) }
|
||||
|
||||
@@ -10,7 +10,7 @@ import Foundation
|
||||
/// DatabaseValue is the intermediate type between SQLite and your values.
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html
|
||||
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpressible, SQLExpression {
|
||||
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpression {
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
@@ -204,17 +204,6 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLSelectable
|
||||
|
||||
extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> DatabaseValue {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Lossless conversions
|
||||
|
||||
extension DatabaseValue {
|
||||
@@ -319,14 +308,13 @@ extension DatabaseValue {
|
||||
extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
public func expressionSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
// fast path for NULL
|
||||
if isNull {
|
||||
return "NULL"
|
||||
}
|
||||
|
||||
if arguments != nil {
|
||||
arguments!.values.append(self)
|
||||
if context.appendArguments([self]) {
|
||||
return "?"
|
||||
} else {
|
||||
// Correctness above all: use SQLite to quote the value.
|
||||
@@ -360,6 +348,18 @@ extension DatabaseValue {
|
||||
return SQLExpressionNot(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
@@ -376,7 +376,7 @@ extension DatabaseValue {
|
||||
case .string(let string):
|
||||
return String(reflecting: string)
|
||||
case .blob(let data):
|
||||
return data.description
|
||||
return "Data(\(data.description))"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,8 +41,8 @@ extension DatabaseValueConvertible {
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM links")
|
||||
/// try dbQueue.read { db in
|
||||
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM link")
|
||||
/// while let url = urls.next() { // URL
|
||||
/// print(url)
|
||||
/// }
|
||||
@@ -81,8 +81,8 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor
|
||||
/// A cursor of optional database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM links")
|
||||
/// try dbQueue.read { db in
|
||||
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM link")
|
||||
/// while let url = urls.next() { // URL?
|
||||
/// print(url)
|
||||
/// }
|
||||
@@ -194,64 +194,6 @@ extension DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From Request
|
||||
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// for let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseValueCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a fetch request.
|
||||
///
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchOne(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
@@ -276,7 +218,7 @@ extension DatabaseValueConvertible {
|
||||
/// - 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? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
@@ -291,7 +233,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An array.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
|
||||
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
@@ -309,10 +251,122 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From FetchRequest
|
||||
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// while let name = try name.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - 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 -> DatabaseValueCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Self] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a fetch request.
|
||||
///
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request = Player.filter(key: 1).select(Column("name"))
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> Self? {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchOne(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch cursors
|
||||
/// and arrays of optional DatabaseValueConvertible:
|
||||
@@ -368,48 +422,6 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From Request
|
||||
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - requet: A fetch request.
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
@@ -434,7 +446,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - 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? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
@@ -449,6 +461,87 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - 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? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From FetchRequest
|
||||
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - 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> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Wrapped?] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchAll(db) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,8 +23,13 @@ public protocol DatabaseWriter : DatabaseReader {
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed not to see any changes
|
||||
/// performed in the block until they are all saved in the database.
|
||||
///
|
||||
/// The block may, or may not, be wrapped inside a transaction.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
func write<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
func write<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
@@ -32,6 +37,23 @@ public protocol DatabaseWriter : DatabaseReader {
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// Eventual concurrent reads may see changes performed in the block before
|
||||
/// the block completes.
|
||||
///
|
||||
/// The block is guaranteed to be executed outside of a transaction.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the block
|
||||
/// has executed.
|
||||
///
|
||||
/// Eventual concurrent reads may see changes performed in the block before
|
||||
/// the block completes.
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
@@ -51,12 +73,12 @@ public protocol DatabaseWriter : DatabaseReader {
|
||||
/// For example:
|
||||
///
|
||||
/// try writer.write { db in
|
||||
/// try db.execute("DELETE FROM players")
|
||||
/// try db.execute("DELETE FROM player")
|
||||
/// try writer.readFromCurrentState { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM player")!
|
||||
/// }
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// try db.execute("INSERT INTO player ...")
|
||||
/// }
|
||||
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
|
||||
}
|
||||
@@ -73,12 +95,12 @@ extension DatabaseWriter {
|
||||
/// the observer lifetime (observation lasts until observer
|
||||
/// is deallocated).
|
||||
public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) {
|
||||
write { $0.add(transactionObserver: transactionObserver, extent: extent) }
|
||||
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
|
||||
}
|
||||
|
||||
/// Remove a transaction observer.
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
write { $0.remove(transactionObserver: transactionObserver) }
|
||||
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,9 +141,14 @@ public final class AnyDatabaseWriter : DatabaseWriter {
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// :nodoc:
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
public func write<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.write(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try base.writeWithoutTransaction(block)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
// MARK: - FetchRequest
|
||||
|
||||
/// The protocol for all requests that run from a single select statement, and
|
||||
/// tell how fetched rows should be interpreted.
|
||||
///
|
||||
/// struct Player: FetchableRecord { ... }
|
||||
/// let request: ... // Some FetchRequest that fetches Player
|
||||
/// try request.fetchCursor(db) // Cursor of Player
|
||||
/// try request.fetchAll(db) // [Player]
|
||||
/// try request.fetchOne(db) // Player?
|
||||
public protocol FetchRequest {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
/// Returns a tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A prepared statement and an eventual row adapter.
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// The default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `prepare` method:
|
||||
/// `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// Adopting types can refine this method in order to use more
|
||||
/// efficient SQL.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
|
||||
/// Returns the database region that the request looks into.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func databaseRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
extension FetchRequest {
|
||||
/// Returns an adapted request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
return AdaptedFetchRequest(self, adapter)
|
||||
}
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// This default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
let (statement, _) = try prepare(db)
|
||||
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
|
||||
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
|
||||
}
|
||||
|
||||
/// Returns the database region that the request looks into.
|
||||
///
|
||||
/// This default implementation returns a region built from the statement
|
||||
/// returned by the `prepare` method.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
let (statement, _) = try prepare(db)
|
||||
return statement.databaseRegion
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AdaptedFetchRequest
|
||||
|
||||
/// An adapted request.
|
||||
public struct AdaptedFetchRequest<Base: FetchRequest> : FetchRequest {
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
private let base: Base
|
||||
private let adapter: (Database) throws -> RowAdapter
|
||||
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let (statement, baseAdapter) = try base.prepare(db)
|
||||
if let baseAdapter = baseAdapter {
|
||||
return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db)))
|
||||
} else {
|
||||
return try (statement, adapter(db))
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.databaseRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AnyFetchRequest
|
||||
|
||||
/// A type-erased FetchRequest.
|
||||
///
|
||||
/// An AnyFetchRequest forwards its operations to an underlying request,
|
||||
/// hiding its specifics.
|
||||
public struct AnyFetchRequest<T> : FetchRequest {
|
||||
public typealias RowDecoder = T
|
||||
|
||||
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
private let _fetchCount: (Database) throws -> Int
|
||||
private let _databaseRegion: (Database) throws -> DatabaseRegion
|
||||
|
||||
/// Creates a request that wraps and forwards operations to `request`.
|
||||
public init<Request: FetchRequest>(_ request: Request) {
|
||||
_prepare = request.prepare
|
||||
_fetchCount = request.fetchCount
|
||||
_databaseRegion = request.databaseRegion
|
||||
}
|
||||
|
||||
/// Creates a request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
|
||||
_prepare = { db in
|
||||
try prepare(db)
|
||||
}
|
||||
|
||||
_fetchCount = { db in
|
||||
let (statement, _) = try prepare(db)
|
||||
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
|
||||
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
|
||||
}
|
||||
|
||||
_databaseRegion = { db in
|
||||
let (statement, _) = try prepare(db)
|
||||
return statement.databaseRegion
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try _prepare(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try _fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try _databaseRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLRequest
|
||||
|
||||
/// A FetchRequest built from raw SQL.
|
||||
public struct SQLRequest<T> : FetchRequest {
|
||||
public typealias RowDecoder = T
|
||||
|
||||
public var sql: String
|
||||
public var arguments: StatementArguments?
|
||||
public var adapter: RowAdapter?
|
||||
private let cache: Cache?
|
||||
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest("SELECT * FROM player")
|
||||
/// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil)
|
||||
}
|
||||
|
||||
/// Creates an SQL request from any other fetch request.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A request.
|
||||
/// - 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 {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
self.init(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
|
||||
}
|
||||
|
||||
/// Creates an SQL request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest("SELECT * FROM player")
|
||||
/// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - statementCacheName: Optional statement cache name.
|
||||
/// - returns: A SQLRequest
|
||||
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
self.adapter = adapter
|
||||
self.cache = cache
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let statement: SelectStatement
|
||||
switch cache {
|
||||
case .none:
|
||||
statement = try db.makeSelectStatement(sql)
|
||||
case .public?:
|
||||
statement = try db.cachedSelectStatement(sql)
|
||||
case .internal?:
|
||||
statement = try db.internalCachedSelectStatement(sql)
|
||||
}
|
||||
if let arguments = arguments {
|
||||
try statement.setArgumentsWithValidation(arguments)
|
||||
}
|
||||
return (statement, adapter)
|
||||
}
|
||||
|
||||
/// There are two statement caches: one for statements generated by the
|
||||
/// user, and one for the statements generated by GRDB. Those are separated
|
||||
/// so that GRDB has no opportunity to inadvertently modify the arguments of
|
||||
/// user's cached statements.
|
||||
enum Cache {
|
||||
/// The public cache, for library user
|
||||
case `public`
|
||||
|
||||
/// The internal cache, for grdb
|
||||
case `internal`
|
||||
}
|
||||
}
|
||||
@@ -1,622 +0,0 @@
|
||||
/// The protocol for all types that define a way to fetch database rows.
|
||||
///
|
||||
/// Requests can feed the fetching methods of any fetchable type (Row,
|
||||
/// value, record):
|
||||
///
|
||||
/// let request: Request = ...
|
||||
/// try Row.fetchCursor(db, request) // RowCursor
|
||||
/// try String.fetchAll(db, request) // [String]
|
||||
/// try Player.fetchOne(db, request) // Player?
|
||||
public protocol Request {
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// Default implementation builds a naive SQL query based on the statement
|
||||
/// returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// Adopting types can refine this countRequest method and return more
|
||||
/// efficient SQL.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
|
||||
/// The database region that the request looks into.
|
||||
///
|
||||
/// This method has a default implementation.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchedRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
extension Request {
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// This default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
let (statement, _) = try prepare(db)
|
||||
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
|
||||
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
|
||||
}
|
||||
|
||||
/// Returns an equivalent SQLRequest.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: An SQLRequest
|
||||
public func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest {
|
||||
let (statement, adapter) = try prepare(db)
|
||||
return SQLRequest(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
|
||||
}
|
||||
|
||||
/// The database region that the request looks into.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
let (statement, _) = try prepare(db)
|
||||
return statement.fetchedRegion
|
||||
}
|
||||
}
|
||||
|
||||
extension Request {
|
||||
/// Returns a request bound to type T.
|
||||
///
|
||||
/// The returned request can fetch if the type T is fetchable (Row,
|
||||
/// value, record).
|
||||
///
|
||||
/// // Int?
|
||||
/// let maxScore = Player
|
||||
/// .select(max(scoreColumn))
|
||||
/// .asRequest(of: Int.self) // <--
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// - parameter type: The fetched type T
|
||||
/// - returns: A typed request bound to type T.
|
||||
public func asRequest<T>(of type: T.Type) -> AnyTypedRequest<T> {
|
||||
return AnyTypedRequest(self)
|
||||
}
|
||||
|
||||
/// Returns an adapted request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self> {
|
||||
return AdaptedRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
/// An adapted request.
|
||||
public struct AdaptedRequest<Base: Request> : Request {
|
||||
private let base: Base
|
||||
private let adapter: (Database) throws -> RowAdapter
|
||||
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let (statement, baseAdapter) = try base.prepare(db)
|
||||
if let baseAdapter = baseAdapter {
|
||||
return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db)))
|
||||
} else {
|
||||
return try (statement, adapter(db))
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased Request.
|
||||
///
|
||||
/// An instance of AnyRequest forwards its operations to an underlying request,
|
||||
/// hiding its specifics.
|
||||
public struct AnyRequest : Request {
|
||||
private let base: Request
|
||||
|
||||
/// Creates a new request that wraps and forwards operations to `request`.
|
||||
public init(_ request: Request) {
|
||||
base = request
|
||||
}
|
||||
|
||||
/// Creates a new request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
|
||||
struct PrepareRequest: Request {
|
||||
let base: (Database) throws -> (SelectStatement, RowAdapter?)
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try base(db)
|
||||
}
|
||||
}
|
||||
base = PrepareRequest(base: prepare)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try base.prepare(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// A Request built from raw SQL.
|
||||
public struct SQLRequest : Request {
|
||||
public let sql: String
|
||||
public let arguments: StatementArguments?
|
||||
public let adapter: RowAdapter?
|
||||
private let cache: Cache?
|
||||
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest("SELECT * FROM players")
|
||||
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil)
|
||||
}
|
||||
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest("SELECT * FROM players")
|
||||
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - statementCacheName: Optional statement cache name.
|
||||
/// - returns: A SQLRequest
|
||||
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
self.adapter = adapter
|
||||
self.cache = cache
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let statement: SelectStatement
|
||||
switch cache {
|
||||
case .none:
|
||||
statement = try db.makeSelectStatement(sql)
|
||||
case .public?:
|
||||
statement = try db.cachedSelectStatement(sql)
|
||||
case .internal?:
|
||||
statement = try db.internalCachedSelectStatement(sql)
|
||||
}
|
||||
if let arguments = arguments {
|
||||
try statement.setArgumentsWithValidation(arguments)
|
||||
}
|
||||
return (statement, adapter)
|
||||
}
|
||||
|
||||
/// There are two statement caches: one for statements generated by the
|
||||
/// user, and one for the statements generated by GRDB. Those are separated
|
||||
/// so that GRDB has no opportunity to inadvertently modify the arguments of
|
||||
/// user's cached statements.
|
||||
enum Cache {
|
||||
/// The public cache, for library user
|
||||
case `public`
|
||||
|
||||
/// The internal cache, for grdb
|
||||
case `internal`
|
||||
}
|
||||
}
|
||||
|
||||
/// The protocol for requests that know how to decode database rows.
|
||||
///
|
||||
/// Typed requests can fetch if their associated type RowDecoder is able to
|
||||
/// decode rows (Row, value, record)
|
||||
///
|
||||
/// struct Player: RowConvertible { ... }
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// try request.fetchCursor(db) // Cursor of Player
|
||||
/// try request.fetchAll(db) // [Player]
|
||||
/// try request.fetchOne(db) // Player?
|
||||
public protocol TypedRequest : Request {
|
||||
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
associatedtype RowDecoder
|
||||
}
|
||||
|
||||
extension TypedRequest {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an adapted typed request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest<Self> {
|
||||
return AdaptedTypedRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
/// An adapted typed request.
|
||||
public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
private let base: AdaptedRequest<Base>
|
||||
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
self.base = AdaptedRequest(base, adapter)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try base.prepare(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased TypedRequest.
|
||||
///
|
||||
/// An instance of AnyTypedRequest forwards its operations to an underlying
|
||||
/// typed request, hiding its specifics.
|
||||
public struct AnyTypedRequest<T> : TypedRequest {
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
public typealias RowDecoder = T
|
||||
private let base: Request
|
||||
|
||||
/// Support for Request.asRequest(of:)
|
||||
/// Not public because not type-safe.
|
||||
fileprivate init(_ request: Request) {
|
||||
base = request
|
||||
}
|
||||
|
||||
/// Creates a new request that wraps and forwards operations to `request`.
|
||||
public init<Request>(_ request: Request) where Request: TypedRequest, Request.RowDecoder == RowDecoder {
|
||||
base = request
|
||||
}
|
||||
|
||||
/// Creates a new request whose `prepare()` method wraps and forwards
|
||||
/// operations the argument closure.
|
||||
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
|
||||
base = AnyRequest(prepare)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try base.prepare(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try base.fetchedRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: RowConvertible {
|
||||
|
||||
// MARK: Fetching Record and RowConvertible
|
||||
|
||||
/// A cursor over fetched records.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// let players = try request.fetchCursor(db) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched records.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// let players = try request.fetchAll(db) // [Player]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched record.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// let player = try request.fetchOne(db) // Player?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchAll(db) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchAll(db) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TypedRequest where RowDecoder: Row {
|
||||
|
||||
// MARK: Fetching Rows
|
||||
|
||||
/// A cursor over fetched rows.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let rows = try request.fetchCursor(db) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
|
||||
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
|
||||
/// instead.
|
||||
///
|
||||
/// For the same reason, make sure you make a copy whenever you extract a
|
||||
/// row for later use: `row.copy()`.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> RowCursor {
|
||||
return try Row.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched rows.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let rows = try request.fetchAll(db)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
return try Row.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let row = try request.fetchOne(db)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A,n optional rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> Row? {
|
||||
return try Row.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import Foundation
|
||||
#endif
|
||||
|
||||
/// A database row.
|
||||
public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible {
|
||||
public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible {
|
||||
let impl: RowImpl
|
||||
|
||||
/// Unless we are producing a row array, we use a single row when iterating
|
||||
@@ -61,7 +61,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl
|
||||
/// the iteration of a query: make sure to make a copy of it whenever you
|
||||
/// want to keep a specific one: `row.copy()`.
|
||||
public func copy() -> Row {
|
||||
return impl.copy(self)
|
||||
return impl.copiedRow(self)
|
||||
}
|
||||
|
||||
// MARK: - Not Public
|
||||
@@ -143,11 +143,11 @@ extension Row {
|
||||
/// let row = try Row.fetchOne(db, "SELECT NULL, NULL")!
|
||||
/// row.containsNonNullValue // false
|
||||
public var containsNonNullValue: Bool {
|
||||
for i in (0..<count) {
|
||||
if !hasNull(atIndex: i) { return true }
|
||||
for i in (0..<count) where !hasNull(atIndex: i) {
|
||||
return true
|
||||
}
|
||||
|
||||
for name in scopeNames where scoped(on: name)!.containsNonNullValue {
|
||||
for (_, scopedRow) in scopes where scopedRow.containsNonNullValue {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -347,7 +347,7 @@ extension Row {
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// The result is nil if the row does not contain the column.
|
||||
public subscript(_ column: Column) -> DatabaseValueConvertible? {
|
||||
public subscript(_ column: ColumnExpression) -> DatabaseValueConvertible? {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
@@ -359,7 +359,7 @@ extension Row {
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. Otherwise the SQLite value is converted to the requested type
|
||||
/// `Value`. Should this conversion fail, a fatal error is raised.
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value? {
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: ColumnExpression) -> Value? {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
@@ -375,7 +375,7 @@ extension Row {
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value? {
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: ColumnExpression) -> Value? {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
@@ -388,7 +388,7 @@ extension Row {
|
||||
///
|
||||
/// This method crashes if the fetched SQLite value is NULL, or if the
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value {
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: ColumnExpression) -> Value {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
@@ -405,7 +405,7 @@ extension Row {
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value {
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: ColumnExpression) -> Value {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
@@ -453,7 +453,7 @@ extension Row {
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
public func dataNoCopy(_ column: Column) -> Data? {
|
||||
public func dataNoCopy(_ column: ColumnExpression) -> Data? {
|
||||
return dataNoCopy(named: column.name)
|
||||
}
|
||||
}
|
||||
@@ -482,8 +482,8 @@ extension Row {
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// for more information.
|
||||
public subscript<Record: RowConvertible>(_ scope: String) -> Record {
|
||||
guard let scopedRow = scoped(on: scope) else {
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
|
||||
guard let scopedRow = scopesTree[scope] else {
|
||||
// Programmer error
|
||||
fatalError("no such scope: \(scope)")
|
||||
}
|
||||
@@ -498,8 +498,8 @@ extension Row {
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// for more information.
|
||||
public subscript<Record: RowConvertible>(_ scope: String) -> Record? {
|
||||
guard let scopedRow = scoped(on: scope), scopedRow.containsNonNullValue else {
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record? {
|
||||
guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else {
|
||||
return nil
|
||||
}
|
||||
return Record(row: scopedRow)
|
||||
@@ -510,48 +510,80 @@ extension Row {
|
||||
|
||||
// MARK: - Scopes
|
||||
|
||||
var scopeNames: Set<String> {
|
||||
return impl.scopeNames
|
||||
}
|
||||
|
||||
/// Returns a scoped row, if the row was fetched with a row adapter that
|
||||
/// defines this scope.
|
||||
/// Returns a view on the scopes defined by row adapters.
|
||||
///
|
||||
/// // Two adapters
|
||||
/// let fooAdapter = ColumnMapping(["value": "foo"])
|
||||
/// let barAdapter = ColumnMapping(["value": "bar"])
|
||||
/// For example:
|
||||
///
|
||||
/// // Define scopes
|
||||
/// // Define a tree of nested scopes
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "foo": fooAdapter,
|
||||
/// "bar": barAdapter])
|
||||
/// "foo": RangeRowAdapter(0..<1),
|
||||
/// "bar": RangeRowAdapter(1..<2).addingScopes([
|
||||
/// "baz" : RangeRowAdapter(2..<3)])])
|
||||
///
|
||||
/// // Fetch
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
|
||||
///
|
||||
/// // Scoped rows:
|
||||
/// if let fooRow = row.scoped(on: "foo") {
|
||||
/// fooRow["value"] // "foo"
|
||||
/// }
|
||||
/// if let barRow = row.scopeed(on: "bar") {
|
||||
/// barRow["value"] // "bar"
|
||||
/// }
|
||||
public func scoped(on name: String) -> Row? {
|
||||
return impl.scoped(on: name)
|
||||
/// row.scopes.count // 2
|
||||
/// row.scopes.names // ["foo", "bar"]
|
||||
///
|
||||
/// row.scopes["foo"] // [foo:1]
|
||||
/// row.scopes["bar"] // [bar:2]
|
||||
/// row.scopes["baz"] // nil
|
||||
public var scopes: ScopesView {
|
||||
return impl.scopes
|
||||
}
|
||||
|
||||
/// Returns a copy of the row, without any scoped row (if the row was fetched
|
||||
/// with a row adapter that defines scopes).
|
||||
/// Returns a view on the scopes tree defined by row adapters.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // Define a tree of nested scopes
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "foo": RangeRowAdapter(0..<1),
|
||||
/// "bar": RangeRowAdapter(1..<2).addingScopes([
|
||||
/// "baz" : RangeRowAdapter(2..<3)])])
|
||||
///
|
||||
/// // Fetch
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
|
||||
///
|
||||
/// row.scopesTree.names // ["foo", "bar", "baz"]
|
||||
///
|
||||
/// row.scopesTree["foo"] // [foo:1]
|
||||
/// row.scopesTree["bar"] // [bar:2]
|
||||
/// row.scopesTree["baz"] // [baz:3]
|
||||
public var scopesTree: ScopesTreeView {
|
||||
return ScopesTreeView(scopes: scopes)
|
||||
}
|
||||
|
||||
/// Returns a copy of the row, without any scopes.
|
||||
///
|
||||
/// This property can turn out useful when you want to test the content of
|
||||
/// adapted rows, such as rows fetched from joined requests.
|
||||
///
|
||||
/// let row = ...
|
||||
/// // Failure because row equality tests for row scopes:
|
||||
/// XCTAssertEqual(row, ["id": 1, "name": "foo"])
|
||||
/// // Success:
|
||||
/// XCTAssertEqual(row.unscoped, ["id": 1, "name": "foo"])
|
||||
public var unscoped: Row {
|
||||
return Row(impl: ArrayRowImpl(columns: map { ($0, $1) }))
|
||||
return impl.unscopedRow(self)
|
||||
}
|
||||
|
||||
/// Return the raw row fetched from the database.
|
||||
///
|
||||
/// This property can turn out useful when you debug the consumption of
|
||||
/// adapted rows, such as rows fetched from joined requests.
|
||||
public var unadapted: Row {
|
||||
return impl.unadaptedRow(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of database rows. For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM players")
|
||||
/// try dbQueue.read { db in
|
||||
/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM player")
|
||||
/// }
|
||||
public final class RowCursor : Cursor {
|
||||
public let statement: SelectStatement
|
||||
@@ -652,80 +684,13 @@ extension Row {
|
||||
}
|
||||
}
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Fetching From Request
|
||||
|
||||
/// Returns a cursor over rows fetched from a fetch request.
|
||||
///
|
||||
/// let idColumn = Column("id")
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(idColumn, nameColumn)
|
||||
/// let rows = try Row.fetchCursor(db) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
|
||||
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
|
||||
/// instead.
|
||||
///
|
||||
/// For the same reason, make sure you make a copy whenever you extract a
|
||||
/// row for later use: `row.copy()`.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> RowCursor {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of rows fetched from a fetch request.
|
||||
///
|
||||
/// let idColumn = Column("id")
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(idColumn, nameColumn)
|
||||
/// let rows = try Row.fetchAll(db, request)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Row] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single row fetched from a fetch request.
|
||||
///
|
||||
/// let idColumn = Column("id")
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(idColumn, nameColumn)
|
||||
/// let row = try Row.fetchOne(db, request)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ request: Request) throws -> Row? {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchOne(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Fetching From SQL
|
||||
|
||||
/// Returns a cursor over rows fetched from an SQL query.
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT id, name FROM players") // RowCursor
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT id, name FROM player") // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
@@ -752,7 +717,7 @@ extension Row {
|
||||
/// - 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? = nil, adapter: RowAdapter? = nil) throws -> RowCursor {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of rows fetched from an SQL query.
|
||||
@@ -767,7 +732,7 @@ extension Row {
|
||||
/// - 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? = nil, adapter: RowAdapter? = nil) throws -> [Row] {
|
||||
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single row fetched from an SQL query.
|
||||
@@ -782,10 +747,135 @@ extension Row {
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? {
|
||||
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Fetching From FetchRequest
|
||||
|
||||
/// Returns a cursor over rows fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.all()
|
||||
/// let rows = try Row.fetchCursor(db, request) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row["id"]
|
||||
/// let name: String = row["name"]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
|
||||
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
|
||||
/// instead.
|
||||
///
|
||||
/// For the same reason, make sure you make a copy whenever you extract a
|
||||
/// row for later use: `row.copy()`.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> RowCursor {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of rows fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.all()
|
||||
/// let rows = try Row.fetchAll(db, request)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array of rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Row] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single row fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// let row = try Row.fetchOne(db, request)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> Row? {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchOne(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder: Row {
|
||||
|
||||
// MARK: Fetching Rows
|
||||
|
||||
/// A cursor over fetched rows.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let rows = try request.fetchCursor(db) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
/// cursor into an array with `Array(rows)` or `rows.filter { ... }` since
|
||||
/// you would not get the distinct rows you expect. Use `Row.fetchAll(...)`
|
||||
/// instead.
|
||||
///
|
||||
/// For the same reason, make sure you make a copy whenever you extract a
|
||||
/// row for later use: `row.copy()`.
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> RowCursor {
|
||||
return try Row.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched rows.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let rows = try request.fetchAll(db)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
return try Row.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let row = try request.fetchOne(db)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A,n optional rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> Row? {
|
||||
return try Row.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
// ExpressibleByDictionaryLiteral
|
||||
extension Row {
|
||||
|
||||
@@ -794,7 +884,7 @@ extension Row {
|
||||
///
|
||||
/// let row: Row = ["foo": 1, "foo": "bar", "baz": nil]
|
||||
/// print(row)
|
||||
/// // Prints <Row foo:1 foo:"bar" baz:NULL>
|
||||
/// // Prints [foo:1 foo:"bar" baz:NULL]
|
||||
public convenience init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) {
|
||||
self.init(impl: ArrayRowImpl(columns: elements.map { ($0, $1?.databaseValue ?? .null) }))
|
||||
}
|
||||
@@ -852,15 +942,15 @@ extension Row {
|
||||
}
|
||||
}
|
||||
|
||||
let lscopeNames = lhs.impl.scopeNames
|
||||
let rscopeNames = rhs.impl.scopeNames
|
||||
let lscopeNames = lhs.scopes.names
|
||||
let rscopeNames = rhs.scopes.names
|
||||
guard lscopeNames == rscopeNames else {
|
||||
return false
|
||||
}
|
||||
|
||||
for name in lscopeNames {
|
||||
let lscope = lhs.scoped(on: name)
|
||||
let rscope = rhs.scoped(on: name)
|
||||
let lscope = lhs.scopes[name]
|
||||
let rscope = rhs.scopes[name]
|
||||
guard lscope == rscope else {
|
||||
return false
|
||||
}
|
||||
@@ -880,15 +970,40 @@ extension Row {
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
// CustomStringConvertible & CustomDebugStringConvertible
|
||||
extension Row {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
return "<Row"
|
||||
+ map { (column, dbValue) in
|
||||
" \(column):\(dbValue)"
|
||||
}.joined(separator: "")
|
||||
+ ">"
|
||||
return "["
|
||||
+ map { (column, dbValue) in "\(column):\(dbValue)" }.joined(separator: " ")
|
||||
+ "]"
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var debugDescription: String {
|
||||
return debugDescription(level: 0)
|
||||
}
|
||||
|
||||
private func debugDescription(level: Int) -> String {
|
||||
if level == 0 && self == self.unadapted {
|
||||
return description
|
||||
}
|
||||
let prefix = repeatElement(" ", count: level + 1).joined(separator: "")
|
||||
var str = ""
|
||||
if level == 0 {
|
||||
str = "▿ " + description
|
||||
let unadapted = self.unadapted
|
||||
if self != unadapted {
|
||||
str += "\n" + prefix + "unadapted: " + unadapted.description
|
||||
}
|
||||
} else {
|
||||
str = description
|
||||
}
|
||||
for (name, scopedRow) in scopes.sorted(by: { $0.name < $1.name }) {
|
||||
str += "\n" + prefix + "- " + name + ": " + scopedRow.debugDescription(level: level + 1)
|
||||
}
|
||||
|
||||
return str
|
||||
}
|
||||
}
|
||||
|
||||
@@ -927,6 +1042,134 @@ extension RowIndex {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Row.ScopesView
|
||||
|
||||
extension Row {
|
||||
/// A view of the scopes defined by row adapters. It is a collection of
|
||||
/// tuples made of a scope name and a scoped row, which behaves like a
|
||||
/// dictionary.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // Define a tree of nested scopes
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "foo": RangeRowAdapter(0..<1),
|
||||
/// "bar": RangeRowAdapter(1..<2).addingScopes([
|
||||
/// "baz" : RangeRowAdapter(2..<3)])])
|
||||
///
|
||||
/// // Fetch
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
|
||||
///
|
||||
/// row.scopes.count // 2
|
||||
/// row.scopes.names // ["foo", "bar"]
|
||||
///
|
||||
/// row.scopes["foo"] // [foo:1]
|
||||
/// row.scopes["bar"] // [bar:2]
|
||||
/// row.scopes["baz"] // nil
|
||||
public struct ScopesView: Collection {
|
||||
public typealias Index = Dictionary<String, LayoutedRowAdapter>.Index
|
||||
private let row: Row
|
||||
private let scopes: [String: LayoutedRowAdapter]
|
||||
|
||||
/// The scopes defined on this row.
|
||||
public var names: Dictionary<String, LayoutedRowAdapter>.Keys {
|
||||
return scopes.keys
|
||||
}
|
||||
|
||||
init() {
|
||||
self.init(row: Row(), scopes: [:])
|
||||
}
|
||||
|
||||
init(row: Row, scopes: [String: LayoutedRowAdapter]) {
|
||||
self.row = row
|
||||
self.scopes = scopes
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var startIndex: Index {
|
||||
return scopes.startIndex
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var endIndex: Index {
|
||||
return scopes.endIndex
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func index(after i: Index) -> Index {
|
||||
return scopes.index(after: i)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public subscript(position: Index) -> (name: String, row: Row) {
|
||||
let (name, adapter) = scopes[position]
|
||||
return (name: name, row: Row(base: row, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns the row associated with the given scope, or nil if the
|
||||
/// scope is not defined.
|
||||
public subscript(_ name: String) -> Row? {
|
||||
guard let adapter = scopes[name] else {
|
||||
return nil
|
||||
}
|
||||
return Row(base: row, adapter: adapter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Row.ScopesTreeView
|
||||
|
||||
extension Row {
|
||||
|
||||
/// A view on the scopes tree defined by row adapters.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // Define a tree of nested scopes
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "foo": RangeRowAdapter(0..<1),
|
||||
/// "bar": RangeRowAdapter(1..<2).addingScopes([
|
||||
/// "baz" : RangeRowAdapter(2..<3)])])
|
||||
///
|
||||
/// // Fetch
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
|
||||
///
|
||||
/// row.scopesTree.names // ["foo", "bar", "baz"]
|
||||
///
|
||||
/// row.scopesTree["foo"] // [foo:1]
|
||||
/// row.scopesTree["bar"] // [bar:2]
|
||||
/// row.scopesTree["baz"] // [baz:3]
|
||||
public struct ScopesTreeView {
|
||||
let scopes: ScopesView
|
||||
|
||||
/// The scopes defined on this row, recursively.
|
||||
public var names: Set<String> {
|
||||
var names = Set<String>()
|
||||
for (name, row) in scopes {
|
||||
names.insert(name)
|
||||
names.formUnion(row.scopesTree.names)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
/// Returns the row associated with the given scope, by performing a
|
||||
/// breadth-first search in this row's scopes and the scopes of its
|
||||
/// scoped rows, recursively.
|
||||
public subscript(_ name: String) -> Row? {
|
||||
var fifo = Array(scopes)
|
||||
while !fifo.isEmpty {
|
||||
let scope = fifo.removeFirst()
|
||||
if scope.name == name {
|
||||
return scope.row
|
||||
}
|
||||
fifo.append(contentsOf: scope.row.scopes)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - RowImpl
|
||||
|
||||
@@ -934,6 +1177,7 @@ extension RowIndex {
|
||||
protocol RowImpl {
|
||||
var count: Int { get }
|
||||
var isFetched: Bool { get }
|
||||
var scopes: Row.ScopesView { get }
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value
|
||||
func fastValue<Value: DatabaseValueConvertible & StatementColumnConvertible>(atUncheckedIndex index: Int) -> Value?
|
||||
@@ -945,14 +1189,29 @@ protocol RowImpl {
|
||||
// leftmost column that matches *name*.
|
||||
func index(ofColumn name: String) -> Int?
|
||||
|
||||
func scoped(on name: String) -> Row?
|
||||
var scopeNames: Set<String> { get }
|
||||
|
||||
// row.impl is guaranteed to be self.
|
||||
func copy(_ row: Row) -> Row
|
||||
func unscopedRow(_ row: Row) -> Row
|
||||
func unadaptedRow(_ row: Row) -> Row
|
||||
func copiedRow(_ row: Row) -> Row
|
||||
}
|
||||
|
||||
extension RowImpl {
|
||||
func copiedRow(_ row: Row) -> Row {
|
||||
return row
|
||||
}
|
||||
|
||||
func unscopedRow(_ row: Row) -> Row {
|
||||
return row
|
||||
}
|
||||
|
||||
func unadaptedRow(_ row: Row) -> Row {
|
||||
return row
|
||||
}
|
||||
|
||||
var scopes: Row.ScopesView {
|
||||
return Row.ScopesView()
|
||||
}
|
||||
|
||||
func hasNull(atUncheckedIndex index:Int) -> Bool {
|
||||
return databaseValue(atUncheckedIndex: index).isNull
|
||||
}
|
||||
@@ -1008,18 +1267,6 @@ private struct ArrayRowImpl : RowImpl {
|
||||
let lowercaseName = name.lowercased()
|
||||
return columns.index { (column, _) in column.lowercased() == lowercaseName }
|
||||
}
|
||||
|
||||
func scoped(on name: String) -> Row? {
|
||||
return nil
|
||||
}
|
||||
|
||||
var scopeNames: Set<String> {
|
||||
return []
|
||||
}
|
||||
|
||||
func copy(_ row: Row) -> Row {
|
||||
return row
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1060,18 +1307,6 @@ private struct StatementCopyRowImpl : RowImpl {
|
||||
let lowercaseName = name.lowercased()
|
||||
return columnNames.index { $0.lowercased() == lowercaseName }
|
||||
}
|
||||
|
||||
func scoped(on name: String) -> Row? {
|
||||
return nil
|
||||
}
|
||||
|
||||
var scopeNames: Set<String> {
|
||||
return []
|
||||
}
|
||||
|
||||
func copy(_ row: Row) -> Row {
|
||||
return row
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1142,20 +1377,11 @@ private struct StatementRowImpl : RowImpl {
|
||||
return lowercaseColumnIndexes[name.lowercased()]
|
||||
}
|
||||
|
||||
func scoped(on name: String) -> Row? {
|
||||
return nil
|
||||
}
|
||||
|
||||
var scopeNames: Set<String> {
|
||||
return []
|
||||
}
|
||||
|
||||
func copy(_ row: Row) -> Row {
|
||||
func copiedRow(_ row: Row) -> Row {
|
||||
return Row(copiedFromSQLiteStatement: sqliteStatement, statementRef: statementRef)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// See Row.init()
|
||||
private struct EmptyRowImpl : RowImpl {
|
||||
var count: Int {
|
||||
@@ -1184,16 +1410,4 @@ private struct EmptyRowImpl : RowImpl {
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
return nil
|
||||
}
|
||||
|
||||
func scoped(on name: String) -> Row? {
|
||||
return nil
|
||||
}
|
||||
|
||||
var scopeNames: Set<String> {
|
||||
return []
|
||||
}
|
||||
|
||||
func copy(_ row: Row) -> Row {
|
||||
return row
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,10 @@ import Foundation
|
||||
/// "c": adapters[2],
|
||||
/// "d": adapters[3]])
|
||||
/// let row = try Row.fetchOne(db, sql, adapter: adapter)
|
||||
/// row.scoped(on: "a") // [1]
|
||||
/// row.scoped(on: "b") // [2, 3, 4]
|
||||
/// row.scoped(on: "c") // [5, 6]
|
||||
/// row.scoped(on: "d") // [7, 8]
|
||||
/// row.scopes["a"] // [1]
|
||||
/// row.scopes["b"] // [2, 3, 4]
|
||||
/// row.scopes["c"] // [5, 6]
|
||||
/// row.scopes["d"] // [7, 8]
|
||||
public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] {
|
||||
guard !columnCounts.isEmpty else {
|
||||
// Identity adapter
|
||||
@@ -77,7 +77,7 @@ public struct LayoutedColumnMapping {
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // <Row foo:"foo" bar: "bar">
|
||||
/// // [foo:"foo" bar: "bar"]
|
||||
/// try Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
|
||||
public init<S: Sequence>(layoutColumns: S) where S.Iterator.Element == (Int, String) {
|
||||
self.layoutColumns = Array(layoutColumns)
|
||||
@@ -173,14 +173,12 @@ public protocol RowLayout {
|
||||
|
||||
extension SelectStatement : RowLayout {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public var layoutColumns: [(Int, String)] {
|
||||
return Array(columnNames.enumerated())
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutIndex(ofColumn name: String) -> Int? {
|
||||
return index(ofColumn: name)
|
||||
@@ -202,7 +200,7 @@ extension SelectStatement : RowLayout {
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
///
|
||||
/// // <Row baz:3>
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
public protocol RowAdapter {
|
||||
|
||||
@@ -225,7 +223,7 @@ public protocol RowAdapter {
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // <Row foo:1>
|
||||
/// // [foo:1]
|
||||
/// try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
|
||||
func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter
|
||||
}
|
||||
@@ -239,7 +237,11 @@ extension RowAdapter {
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter {
|
||||
return ScopeAdapter(base: self, scopes: scopes)
|
||||
if scopes.isEmpty {
|
||||
return self
|
||||
} else {
|
||||
return ScopeAdapter(base: self, scopes: scopes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -255,7 +257,6 @@ public struct EmptyRowAdapter: RowAdapter {
|
||||
public init() { }
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: [])
|
||||
@@ -267,7 +268,7 @@ public struct EmptyRowAdapter: RowAdapter {
|
||||
/// let adapter = ColumnMapping(["foo": "bar"])
|
||||
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
|
||||
///
|
||||
/// // <Row foo:"bar">
|
||||
/// // [foo:"bar"]
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
public struct ColumnMapping : RowAdapter {
|
||||
/// A dictionary from mapped column names to column names in a base row.
|
||||
@@ -280,7 +281,6 @@ public struct ColumnMapping : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
let layoutColumns = try mapping
|
||||
@@ -302,7 +302,7 @@ public struct ColumnMapping : RowAdapter {
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
///
|
||||
/// // <Row baz:3>
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
public struct SuffixRowAdapter : RowAdapter {
|
||||
/// The suffix index
|
||||
@@ -318,7 +318,6 @@ public struct SuffixRowAdapter : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index))
|
||||
@@ -330,7 +329,7 @@ public struct SuffixRowAdapter : RowAdapter {
|
||||
/// let adapter = RangeRowAdapter(1..<3)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
|
||||
///
|
||||
/// // <Row bar:2 baz: 3>
|
||||
/// // [bar:2 baz:3]
|
||||
/// try Row.fetchOne(db, sql, adapter: adapter)
|
||||
public struct RangeRowAdapter : RowAdapter {
|
||||
/// The range
|
||||
@@ -349,7 +348,6 @@ public struct RangeRowAdapter : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range])
|
||||
@@ -372,10 +370,10 @@ public struct RangeRowAdapter : RowAdapter {
|
||||
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
|
||||
///
|
||||
/// // Scoped rows:
|
||||
/// if let fooRow = row.scoped(on: "foo") {
|
||||
/// if let fooRow = row.scopes["foo"] {
|
||||
/// fooRow["value"] // "foo"
|
||||
/// }
|
||||
/// if let barRow = row.scopeed(on: "bar") {
|
||||
/// if let barRow = row.scopes["bar"] {
|
||||
/// barRow["value"] // "bar"
|
||||
/// }
|
||||
public struct ScopeAdapter : RowAdapter {
|
||||
@@ -392,8 +390,8 @@ public struct ScopeAdapter : RowAdapter {
|
||||
///
|
||||
/// let adapter = ScopeAdapter(["suffix": SuffixRowAdapter(fromIndex: 1)])
|
||||
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
|
||||
/// row // [1, 2, 3]
|
||||
/// row.scoped(on: "suffix") // [2, 3]
|
||||
/// row // [1, 2, 3]
|
||||
/// row.scopes["suffix"] // [2, 3]
|
||||
///
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
@@ -409,8 +407,8 @@ public struct ScopeAdapter : RowAdapter {
|
||||
/// let baseAdapter = RangeRowAdapter(0..<1)
|
||||
/// let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)])
|
||||
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
|
||||
/// row // [1]
|
||||
/// row.scoped(on: "initial") // [2, 3]
|
||||
/// row // [1]
|
||||
/// row.scopes["initial"] // [2, 3]
|
||||
///
|
||||
/// If the base adapter already defines scopes, the given scopes replace
|
||||
/// eventual existing scopes with the same name.
|
||||
@@ -427,7 +425,6 @@ public struct ScopeAdapter : RowAdapter {
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter {
|
||||
let layoutedAdapter = try base.layoutedAdapter(from: layout)
|
||||
@@ -459,7 +456,7 @@ struct ChainedAdapter : RowAdapter {
|
||||
extension Row {
|
||||
/// Creates a row from a base row and a statement adapter
|
||||
convenience init(base: Row, adapter: LayoutedRowAdapter) {
|
||||
self.init(impl: AdapterRowImpl(base: base, adapter: adapter))
|
||||
self.init(impl: AdaptedRowImpl(base: base, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns self if adapter is nil
|
||||
@@ -471,7 +468,7 @@ extension Row {
|
||||
}
|
||||
}
|
||||
|
||||
struct AdapterRowImpl : RowImpl {
|
||||
struct AdaptedRowImpl : RowImpl {
|
||||
let base: Row
|
||||
let adapter: LayoutedRowAdapter
|
||||
let mapping: LayoutedColumnMapping
|
||||
@@ -490,6 +487,10 @@ struct AdapterRowImpl : RowImpl {
|
||||
return base.isFetched
|
||||
}
|
||||
|
||||
var scopes: Row.ScopesView {
|
||||
return Row.ScopesView(row: base, scopes: adapter.scopes)
|
||||
}
|
||||
|
||||
func hasNull(atUncheckedIndex index: Int) -> Bool {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return base.impl.hasNull(atUncheckedIndex: mappedIndex)
|
||||
@@ -523,18 +524,16 @@ struct AdapterRowImpl : RowImpl {
|
||||
return mapping.layoutIndex(ofColumn: name)
|
||||
}
|
||||
|
||||
func scoped(on name: String) -> Row? {
|
||||
guard let adapter = adapter.scopes[name] else {
|
||||
return nil
|
||||
}
|
||||
return Row(base: base, adapter: adapter)
|
||||
}
|
||||
|
||||
var scopeNames: Set<String> {
|
||||
return Set(adapter.scopes.keys)
|
||||
}
|
||||
|
||||
func copy(_ row: Row) -> Row {
|
||||
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)
|
||||
}
|
||||
|
||||
func unadaptedRow(_ row: Row) -> Row {
|
||||
return base.unadapted
|
||||
}
|
||||
}
|
||||
@@ -61,27 +61,27 @@ final class SerializedDatabase {
|
||||
//
|
||||
// 1. A database is invoked from some queue like the main queue:
|
||||
//
|
||||
// dbQueue.inDatabase { db in // <-- we're here
|
||||
// serializedDatabase.sync { db in // <-- we're here
|
||||
// }
|
||||
//
|
||||
// 2. A database is invoked in a reentrant way:
|
||||
//
|
||||
// dbQueue.inDatabase { db in
|
||||
// dbQueue.inDatabase { db in // <-- we're here
|
||||
// serializedDatabase.sync { db in
|
||||
// serializedDatabase.sync { db in // <-- we're here
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// 3. A database in invoked from another database:
|
||||
//
|
||||
// dbQueue1.inDatabase { db1 in
|
||||
// dbQueue2.inDatabase { db2 in // <-- we're here
|
||||
// serializedDatabase1.sync { db1 in
|
||||
// serializedDatabase2.sync { db2 in // <-- we're here
|
||||
// }
|
||||
// }
|
||||
|
||||
guard let watchdog = SchedulingWatchdog.current else {
|
||||
// Case 1
|
||||
return try queue.sync {
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
defer { preconditionNoUnsafeTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
@@ -92,7 +92,7 @@ final class SerializedDatabase {
|
||||
// Case 3
|
||||
return try queue.sync {
|
||||
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
defer { preconditionNoUnsafeTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
@@ -107,42 +107,60 @@ final class SerializedDatabase {
|
||||
//
|
||||
// 1. A database is invoked from some queue like the main queue:
|
||||
//
|
||||
// dbQueue.inDatabase { db in // <-- we're here
|
||||
// serializedDatabase.reentrantSync { db in // <-- we're here
|
||||
// }
|
||||
//
|
||||
// 2. A database is invoked in a reentrant way:
|
||||
//
|
||||
// dbQueue.inDatabase { db in
|
||||
// dbQueue.inDatabase { db in // <-- we're here
|
||||
// serializedDatabase.reentrantSync { db in
|
||||
// serializedDatabase.reentrantSync { db in // <-- we're here
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// 3. A database in invoked from another database:
|
||||
//
|
||||
// dbQueue1.inDatabase { db1 in
|
||||
// dbQueue2.inDatabase { db2 in // <-- we're here
|
||||
// serializedDatabase1.reentrantSync { db1 in
|
||||
// serializedDatabase2.reentrantSync { db2 in // <-- we're here
|
||||
// }
|
||||
// }
|
||||
|
||||
guard let watchdog = SchedulingWatchdog.current else {
|
||||
// Case 1
|
||||
return try queue.sync {
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
// Since we are reentrant, a transaction may already be opened.
|
||||
// In this case, don't check for unsafe transaction at the end.
|
||||
if db.isInsideTransaction {
|
||||
return try block(db)
|
||||
} else {
|
||||
defer { preconditionNoUnsafeTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Case 2
|
||||
if watchdog.allows(db) {
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
// Since we are reentrant, a transaction may already be opened.
|
||||
// In this case, don't check for unsafe transaction at the end.
|
||||
if db.isInsideTransaction {
|
||||
return try block(db)
|
||||
} else {
|
||||
defer { preconditionNoUnsafeTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
|
||||
// Case 3
|
||||
return try queue.sync {
|
||||
try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) {
|
||||
defer { preconditionNoTransactionLeft(db) }
|
||||
return try block(db)
|
||||
// Since we are reentrant, a transaction may already be opened.
|
||||
// In this case, don't check for unsafe transaction at the end.
|
||||
if db.isInsideTransaction {
|
||||
return try block(db)
|
||||
} else {
|
||||
defer { preconditionNoUnsafeTransactionLeft(db) }
|
||||
return try block(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,7 +169,7 @@ final class SerializedDatabase {
|
||||
func async(_ block: @escaping (Database) -> Void) {
|
||||
queue.async {
|
||||
block(self.db)
|
||||
self.preconditionNoTransactionLeft(self.db)
|
||||
self.preconditionNoUnsafeTransactionLeft(self.db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -174,7 +192,7 @@ final class SerializedDatabase {
|
||||
}
|
||||
|
||||
/// Fatal error if a transaction has been left opened.
|
||||
func preconditionNoTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #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)
|
||||
}
|
||||
}
|
||||
@@ -222,6 +222,8 @@ protocol AuthorizedStatement {
|
||||
// https://bugs.swift.org/browse/SR-2347
|
||||
//
|
||||
// We work around SR-2347 with this internal protocol.
|
||||
//
|
||||
// TODO: hasn't this bug been fixed in Swift 4.2? https://github.com/apple/swift/blob/master/CHANGELOG.md#swift-42
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
@@ -286,22 +288,14 @@ extension AuthorizedStatement {
|
||||
///
|
||||
/// You create SelectStatement with the Database.makeSelectStatement() method:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
/// }
|
||||
public final class SelectStatement : Statement {
|
||||
/// :nodoc:
|
||||
@available(*, deprecated, renamed:"DatabaseRegion")
|
||||
public typealias SelectionInfo = DatabaseRegion
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, deprecated, renamed:"fetchedRegion")
|
||||
public var selectionInfo: DatabaseRegion { return fetchedRegion }
|
||||
|
||||
public final class SelectStatement : Statement {
|
||||
/// The database region that the statement looks into.
|
||||
public private(set) var fetchedRegion: DatabaseRegion
|
||||
public private(set) var databaseRegion: DatabaseRegion
|
||||
|
||||
/// Creates a prepared statement.
|
||||
///
|
||||
@@ -322,7 +316,7 @@ public final class SelectStatement : Statement {
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
self.fetchedRegion = DatabaseRegion()
|
||||
self.databaseRegion = DatabaseRegion()
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
@@ -332,7 +326,7 @@ public final class SelectStatement : Statement {
|
||||
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.fetchedRegion = authorizer.region
|
||||
self.databaseRegion = authorizer.databaseRegion
|
||||
}
|
||||
|
||||
/// The number of columns in the resulting rows.
|
||||
@@ -380,8 +374,8 @@ extension SelectStatement: AuthorizedStatement { }
|
||||
/// A cursor that iterates a database statement without producing any value.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let statement = db.makeSelectStatement("SELECT * FROM players")
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = db.makeSelectStatement("SELECT * FROM player")
|
||||
/// let cursor: StatementCursor = statement.cursor()
|
||||
/// }
|
||||
public final class StatementCursor: Cursor {
|
||||
@@ -420,7 +414,7 @@ public final class StatementCursor: Cursor {
|
||||
/// You create UpdateStatement with the Database.makeUpdateStatement() method:
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)")
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// return .commit
|
||||
@@ -592,10 +586,10 @@ extension UpdateStatement: AuthorizedStatement { }
|
||||
/// let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
|
||||
/// let row = try Row.fetchOne(db, sql, arguments: [1, 2, "bar"] + ["foo": "foo"])!
|
||||
/// print(row)
|
||||
/// // Prints <Row two:2 foo:"foo" one:1 foo2:"foo" bar:"bar">
|
||||
/// // Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
|
||||
public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral {
|
||||
var values: [DatabaseValue] = []
|
||||
var namedValues: [String: DatabaseValue] = [:]
|
||||
private(set) var values: [DatabaseValue] = []
|
||||
private(set) var namedValues: [String: DatabaseValue] = [:]
|
||||
|
||||
public var isEmpty: Bool {
|
||||
return values.isEmpty && namedValues.isEmpty
|
||||
@@ -911,18 +905,6 @@ extension StatementArguments {
|
||||
}
|
||||
}
|
||||
|
||||
#if !swift(>=4.1)
|
||||
// Equatable
|
||||
extension StatementArguments {
|
||||
/// :nodoc:
|
||||
public static func == (lhs: StatementArguments, rhs: StatementArguments) -> Bool {
|
||||
if lhs.values != rhs.values { return false }
|
||||
if lhs.namedValues != rhs.namedValues { return false }
|
||||
return true
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// A thread-unsafe statement cache
|
||||
struct StatementCache {
|
||||
unowned let db: Database
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
#if os(Linux)
|
||||
import Glibc
|
||||
#endif
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
@@ -18,7 +21,7 @@ protocol StatementAuthorizer : class {
|
||||
/// A class that gathers information about one statement during its compilation.
|
||||
final class StatementCompilationAuthorizer : StatementAuthorizer {
|
||||
/// What this statements reads
|
||||
var region = DatabaseRegion()
|
||||
var databaseRegion = DatabaseRegion()
|
||||
|
||||
/// What this statements writes
|
||||
var databaseEventKinds: [DatabaseEventKind] = []
|
||||
@@ -66,10 +69,10 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
|
||||
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
if columnName.isEmpty {
|
||||
// SELECT COUNT(*) FROM table
|
||||
region.formUnion(DatabaseRegion(table: tableName))
|
||||
databaseRegion.formUnion(DatabaseRegion(table: tableName))
|
||||
} else {
|
||||
// SELECT column FROM table
|
||||
region.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
|
||||
databaseRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
@@ -135,7 +138,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer {
|
||||
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
|
||||
guard let cString2 = cString2 else { return SQLITE_OK }
|
||||
if sqlite3_stricmp(cString2, "COUNT") == 0 {
|
||||
region = .fullDatabase
|
||||
databaseRegion = .fullDatabase
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
|
||||
@@ -74,8 +74,8 @@ extension StatementColumnConvertible {
|
||||
/// A cursor of database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let names: ColumnCursor<String> = try String.fetchCursor(db, "SELECT name FROM players")
|
||||
/// try dbQueue.read { db in
|
||||
/// let names: ColumnCursor<String> = try String.fetchCursor(db, "SELECT name FROM player")
|
||||
/// while let name = names.next() { // String
|
||||
/// print(name)
|
||||
/// }
|
||||
@@ -120,8 +120,8 @@ public final class ColumnCursor<Value: DatabaseValueConvertible & StatementColum
|
||||
/// A cursor of optional database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, "SELECT email FROM players")
|
||||
/// try dbQueue.read { db in
|
||||
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, "SELECT email FROM player")
|
||||
/// while let email = emails.next() { // String?
|
||||
/// print(email ?? "<NULL>")
|
||||
/// }
|
||||
@@ -225,64 +225,6 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From Request
|
||||
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> ColumnCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a fetch request.
|
||||
///
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchOne(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
@@ -307,7 +249,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - 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? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor<Self> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from an SQL query.
|
||||
@@ -322,7 +264,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - 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? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
|
||||
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from an SQL query.
|
||||
@@ -337,10 +279,119 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From FetchRequest
|
||||
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - 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 -> ColumnCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Self] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns a single value fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.filter(key: 1).select(Column("name"))
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> Self? {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchOne(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching Values
|
||||
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
return try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
return try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch cursors
|
||||
/// and arrays of optional DatabaseValueConvertible:
|
||||
@@ -396,48 +447,6 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From Request
|
||||
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - requet: A fetch request.
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableColumnCursor<Wrapped> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
@@ -462,7 +471,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
/// - 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? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor<Wrapped> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
@@ -477,6 +486,86 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
/// - 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? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From FetchRequest
|
||||
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - 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 -> NullableColumnCursor<Wrapped> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Wrapped?] {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchAll(statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchAll(db) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
#if !os(Linux)
|
||||
import CoreGraphics
|
||||
|
||||
/// CGFloat adopts DatabaseValueConvertible
|
||||
@@ -16,3 +17,4 @@ extension CGFloat : DatabaseValueConvertible {
|
||||
return CGFloat(double)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -58,17 +58,11 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn
|
||||
|
||||
/// Creates a DatabaseDateComponents from a DateComponents and a format.
|
||||
///
|
||||
/// The result is nil if and only if *dateComponents* is nil.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - dateComponents: An optional DateComponents.
|
||||
/// - format: The format used for storing the date components in
|
||||
/// the database.
|
||||
/// - returns: An optional DatabaseDateComponents.
|
||||
public init?(_ dateComponents: DateComponents?, format: Format) {
|
||||
guard let dateComponents = dateComponents else {
|
||||
return nil
|
||||
}
|
||||
public init(_ dateComponents: DateComponents, format: Format) {
|
||||
self.format = format
|
||||
self.dateComponents = dateComponents
|
||||
}
|
||||
@@ -81,9 +75,14 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let cString = UnsafePointer<Int8>(OpaquePointer(sqlite3_column_text(sqliteStatement, index)!))
|
||||
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
|
||||
fatalError("could not convert database value \(DatabaseValue(sqliteStatement: sqliteStatement, index: index)) to DatabaseDateComponents")
|
||||
}
|
||||
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
|
||||
guard let components = SQLiteDateParser().components(cString: cString, length: length) else {
|
||||
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 {
|
||||
fatalError("could not convert database value \(String(cString: cString)) to DatabaseDateComponents")
|
||||
}
|
||||
self.dateComponents = components.dateComponents
|
||||
@@ -100,7 +99,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn
|
||||
let year = dateComponents.year ?? 0
|
||||
let month = dateComponents.month ?? 1
|
||||
let day = dateComponents.day ?? 1
|
||||
dateString = NSString(format: "%04d-%02d-%02d", year, month, day) as String
|
||||
dateString = String(format: "%04d-%02d-%02d", year, month, day)
|
||||
default:
|
||||
dateString = nil
|
||||
}
|
||||
@@ -110,18 +109,18 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn
|
||||
case .YMD_HM, .HM:
|
||||
let hour = dateComponents.hour ?? 0
|
||||
let minute = dateComponents.minute ?? 0
|
||||
timeString = NSString(format: "%02d:%02d", hour, minute) as String
|
||||
timeString = String(format: "%02d:%02d", hour, minute)
|
||||
case .YMD_HMS, .HMS:
|
||||
let hour = dateComponents.hour ?? 0
|
||||
let minute = dateComponents.minute ?? 0
|
||||
let second = dateComponents.second ?? 0
|
||||
timeString = NSString(format: "%02d:%02d:%02d", hour, minute, second) as String
|
||||
timeString = String(format: "%02d:%02d:%02d", hour, minute, second)
|
||||
case .YMD_HMSS, .HMSS:
|
||||
let hour = dateComponents.hour ?? 0
|
||||
let minute = dateComponents.minute ?? 0
|
||||
let second = dateComponents.second ?? 0
|
||||
let nanosecond = dateComponents.nanosecond ?? 0
|
||||
timeString = NSString(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) as String
|
||||
timeString = String(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0)))
|
||||
default:
|
||||
timeString = nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import Foundation
|
||||
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 {
|
||||
@@ -31,6 +32,7 @@ extension NSDate : DatabaseValueConvertible {
|
||||
return cast(date)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
@@ -17,3 +18,4 @@ extension NSData : DatabaseValueConvertible {
|
||||
return cast(data)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,3 +1,4 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
private let integerRoundingBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
|
||||
@@ -65,3 +66,4 @@ extension NSNumber : DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,3 +1,4 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSString adopts DatabaseValueConvertible
|
||||
@@ -16,3 +17,4 @@ extension NSString : DatabaseValueConvertible {
|
||||
return self.init(string: string)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -11,7 +11,7 @@ class SQLiteDateParser {
|
||||
var hour: Int32 = 0
|
||||
var minute: Int32 = 0
|
||||
var second: Int32 = 0
|
||||
var nanosecond = ContiguousArray<CChar>.init(repeating: 0, count: 10) // 9 digits, and trailing \0
|
||||
var nanosecond = ContiguousArray<CChar>(repeating: 0, count: 10) // 9 digits, and trailing \0
|
||||
}
|
||||
|
||||
func components(from dateString: String) -> DatabaseDateComponents? {
|
||||
@@ -55,7 +55,7 @@ class SQLiteDateParser {
|
||||
withUnsafeMutablePointer(to: &parserComponents.second) { secondP in
|
||||
parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in
|
||||
withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in
|
||||
vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%10s", pointer)
|
||||
vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%9s", pointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -100,7 +100,7 @@ class SQLiteDateParser {
|
||||
withUnsafeMutablePointer(to: &parserComponents.second) { secondP in
|
||||
parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in
|
||||
withVaList([hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in
|
||||
vsscanf(cString, "%2d:%2d:%2d.%10s", pointer)
|
||||
vsscanf(cString, "%2d:%2d:%2d.%9s", pointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
extension NSURL : DatabaseValueConvertible {
|
||||
|
||||
@@ -17,6 +18,7 @@ extension NSURL : DatabaseValueConvertible {
|
||||
return cast(URL(string: string))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// URL stores its absoluteString in the database.
|
||||
extension URL : DatabaseValueConvertible { }
|
||||
@@ -1,5 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
extension NSUUID : DatabaseValueConvertible {
|
||||
|
||||
@@ -18,8 +19,9 @@ extension NSUUID : DatabaseValueConvertible {
|
||||
return nil
|
||||
}
|
||||
return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self))
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// UUID adopts DatabaseValueConvertible
|
||||
extension UUID : DatabaseValueConvertible { }
|
||||
@@ -29,13 +29,12 @@ extension Database {
|
||||
/// Registers a closure to be executed after the next or current
|
||||
/// transaction completion.
|
||||
///
|
||||
/// dbQueue.inTransaction { db in
|
||||
/// try dbQueue.write { db in
|
||||
/// db.afterNextTransactionCommit { _ in
|
||||
/// print("commit did succeed")
|
||||
/// print("success")
|
||||
/// }
|
||||
/// ...
|
||||
/// return .commit // prints "commit did succeed"
|
||||
/// }
|
||||
/// } // prints "success"
|
||||
///
|
||||
/// If the transaction is rollbacked, the closure is not executed.
|
||||
///
|
||||
@@ -100,11 +99,11 @@ extension Database {
|
||||
///
|
||||
/// Then a statement is executed:
|
||||
///
|
||||
/// try db.execute("INSERT INTO documents ...")
|
||||
/// try db.execute("INSERT INTO document ...")
|
||||
///
|
||||
/// The observation process starts when the statement is *compiled*:
|
||||
/// sqlite3_set_authorizer tells that the statement performs insertion into the
|
||||
/// `documents` table. Generally speaking, statements may have many effects, by
|
||||
/// `document` table. Generally speaking, statements may have many effects, by
|
||||
/// the mean of foreign key actions and SQL triggers. SQLite takes care of
|
||||
/// exposing all those effects to sqlite3_set_authorizer.
|
||||
///
|
||||
@@ -129,7 +128,7 @@ extension Database {
|
||||
///
|
||||
/// Then another statement is executed:
|
||||
///
|
||||
/// try db.execute("INSERT INTO documents ...")
|
||||
/// try db.execute("INSERT INTO document ...")
|
||||
///
|
||||
/// This time, when the statement is *executed* and SQLite tells that a row has
|
||||
/// been inserted, the broker buffers the change event instead of immediately
|
||||
@@ -738,14 +737,14 @@ extension TransactionObserver {
|
||||
/// For example:
|
||||
///
|
||||
/// class PlayerObserver: TransactionObserver {
|
||||
/// var playersTableWasModified = false
|
||||
/// var playerTableWasModified = false
|
||||
///
|
||||
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
/// return eventKind.tableName == "players"
|
||||
/// return eventKind.tableName == "player"
|
||||
/// }
|
||||
///
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// playersTableWasModified = true
|
||||
/// playerTableWasModified = true
|
||||
///
|
||||
/// // It is pointless to keep on tracking further changes:
|
||||
/// stopObservingDatabaseChangesUntilNextTransaction()
|
||||
@@ -874,12 +873,6 @@ public enum DatabaseEventKind {
|
||||
return DatabaseRegion(table: tableName, columns: updatedColumnNames)
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, deprecated, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead")
|
||||
public func impacts(_ region: DatabaseRegion) -> Bool {
|
||||
return region.isModified(byEventsOfKind: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseEventKind {
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
/// FTS3 lets you define "fts3" virtual tables.
|
||||
///
|
||||
/// // CREATE VIRTUAL TABLE documents USING fts3(content)
|
||||
/// try db.create(virtualTable: "documents", using: FTS3()) { t in
|
||||
/// // CREATE VIRTUAL TABLE document USING fts3(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS3()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
public struct FTS3 : VirtualTableModule {
|
||||
/// Creates a FTS3 module suitable for the Database
|
||||
/// `create(virtualTable:using:)` method.
|
||||
///
|
||||
/// // CREATE VIRTUAL TABLE documents USING fts3(content)
|
||||
/// try db.create(virtualTable: "documents", using: FTS3()) { t in
|
||||
/// // CREATE VIRTUAL TABLE document USING fts3(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS3()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
public init() {
|
||||
@@ -54,7 +54,7 @@ public struct FTS3 : VirtualTableModule {
|
||||
/// You don't create instances of this class. Instead, you use the Database
|
||||
/// `create(virtualTable:using:)` method:
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS3()) { t in // t is FTS3TableDefinition
|
||||
/// try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition
|
||||
/// t.column("content")
|
||||
/// }
|
||||
public final class FTS3TableDefinition {
|
||||
@@ -62,7 +62,7 @@ public final class FTS3TableDefinition {
|
||||
|
||||
/// The virtual table tokenizer
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS3()) { t in
|
||||
/// try db.create(virtualTable: "document", using: FTS3()) { t in
|
||||
/// t.tokenizer = .porter
|
||||
/// }
|
||||
/// See https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables
|
||||
@@ -70,7 +70,7 @@ public final class FTS3TableDefinition {
|
||||
|
||||
/// Appends a table column.
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS3()) { t in
|
||||
/// try db.create(virtualTable: "document", using: FTS3()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/// An FTS3 tokenizer, suitable for FTS3 and FTS4 table definitions:
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS4()) { t in
|
||||
/// db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// t.tokenizer = .simple // FTS3TokenizerDescriptor
|
||||
/// }
|
||||
///
|
||||
@@ -16,7 +16,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
|
||||
/// The "simple" tokenizer.
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS4()) { t in
|
||||
/// db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// t.tokenizer = .simple
|
||||
/// }
|
||||
///
|
||||
@@ -25,7 +25,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
|
||||
/// The "porter" tokenizer.
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS4()) { t in
|
||||
/// db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// t.tokenizer = .porter
|
||||
/// }
|
||||
///
|
||||
@@ -35,7 +35,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The "unicode61" tokenizer.
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS4()) { t in
|
||||
/// db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// t.tokenizer = .unicode61()
|
||||
/// }
|
||||
///
|
||||
@@ -54,7 +54,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
#else
|
||||
/// The "unicode61" tokenizer.
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS4()) { t in
|
||||
/// db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// t.tokenizer = .unicode61()
|
||||
/// }
|
||||
///
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/// FTS4 lets you define "fts4" virtual tables.
|
||||
///
|
||||
/// // CREATE VIRTUAL TABLE documents USING fts4(content)
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// // CREATE VIRTUAL TABLE document USING fts4(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
@@ -11,8 +11,8 @@ public struct FTS4 : VirtualTableModule {
|
||||
/// Creates a FTS4 module suitable for the Database
|
||||
/// `create(virtualTable:using:)` method.
|
||||
///
|
||||
/// // CREATE VIRTUAL TABLE documents USING fts4(content)
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// // CREATE VIRTUAL TABLE document USING fts4(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
@@ -137,7 +137,7 @@ public struct FTS4 : VirtualTableModule {
|
||||
/// You don't create instances of this class. Instead, you use the Database
|
||||
/// `create(virtualTable:using:)` method:
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in // t is FTS4TableDefinition
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
@@ -153,7 +153,7 @@ public final class FTS4TableDefinition {
|
||||
|
||||
/// The virtual table tokenizer
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
/// t.tokenizer = .porter
|
||||
/// }
|
||||
///
|
||||
@@ -201,8 +201,8 @@ public final class FTS4TableDefinition {
|
||||
|
||||
/// Support for the FTS5 `prefix` option
|
||||
///
|
||||
/// // CREATE VIRTUAL TABLE documents USING FTS4(content, prefix='2 4');
|
||||
/// db.create(virtualTable: "documents", using:FTS4()) { t in
|
||||
/// // CREATE VIRTUAL TABLE document USING FTS4(content, prefix='2 4');
|
||||
/// db.create(virtualTable: "document", using:FTS4()) { t in
|
||||
/// t.prefixes = [2, 4]
|
||||
/// t.column("content")
|
||||
/// }
|
||||
@@ -212,7 +212,7 @@ public final class FTS4TableDefinition {
|
||||
|
||||
/// Appends a table column.
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
@@ -242,7 +242,7 @@ public final class FTS4TableDefinition {
|
||||
///
|
||||
/// You get instances of this class when you create an FTS4 table:
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
/// t.column("content") // FTS4ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
@@ -261,7 +261,7 @@ public final class FTS4ColumnDefinition {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Excludes the column from the full-text index.
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
@@ -280,7 +280,7 @@ public final class FTS4ColumnDefinition {
|
||||
#else
|
||||
/// Excludes the column from the full-text index.
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
@@ -300,7 +300,7 @@ public final class FTS4ColumnDefinition {
|
||||
|
||||
/// Uses the column as the Int32 language id hidden column.
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("lid").asLanguageId()
|
||||
/// }
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
/// FTS5 lets you define "fts5" virtual tables.
|
||||
///
|
||||
/// // CREATE VIRTUAL TABLE documents USING fts5(content)
|
||||
/// try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
/// // CREATE VIRTUAL TABLE document USING fts5(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
@@ -12,8 +12,8 @@
|
||||
/// Creates a FTS5 module suitable for the Database
|
||||
/// `create(virtualTable:using:)` method.
|
||||
///
|
||||
/// // CREATE VIRTUAL TABLE documents USING fts5(content)
|
||||
/// try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
/// // CREATE VIRTUAL TABLE document USING fts5(content)
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
@@ -156,7 +156,7 @@
|
||||
/// You don't create instances of this class. Instead, you use the Database
|
||||
/// `create(virtualTable:using:)` method:
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS5()) { t in // t is FTS5TableDefinition
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
@@ -172,7 +172,7 @@
|
||||
|
||||
/// The virtual table tokenizer
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.tokenizer = .porter()
|
||||
/// }
|
||||
///
|
||||
@@ -254,7 +254,7 @@
|
||||
|
||||
/// Appends a table column.
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
@@ -284,7 +284,7 @@
|
||||
///
|
||||
/// You get instances of this class when you create an FTS5 table:
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("content") // FTS5ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
@@ -300,7 +300,7 @@
|
||||
|
||||
/// Excludes the column from the full-text index.
|
||||
///
|
||||
/// try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
/// VIRTUAL TABLE statement. In the example below, the arguments will
|
||||
/// be `["arg1", "arg2"]`.
|
||||
///
|
||||
/// CREATE VIRTUAL TABLE documents USING fts5(
|
||||
/// CREATE VIRTUAL TABLE document USING fts5(
|
||||
/// tokenize='custom arg1 arg2'
|
||||
/// )
|
||||
///
|
||||
@@ -26,7 +26,7 @@
|
||||
///
|
||||
/// class MyTokenizer : FTS5CustomTokenizer { ... }
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS5()) { t in
|
||||
/// db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// let tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["unicode61", "remove_diacritics", "0"])
|
||||
/// t.tokenizer = tokenizer
|
||||
/// }
|
||||
@@ -160,7 +160,7 @@
|
||||
/// class MyTokenizer : FTS5CustomTokenizer { ... }
|
||||
/// dbPool.add(tokenizer: MyTokenizer.self)
|
||||
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
|
||||
write { db in
|
||||
writeWithoutTransaction { db in
|
||||
db.add(tokenizer: Tokenizer.self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@
|
||||
// that pattern.
|
||||
do {
|
||||
try DatabaseQueue().inDatabase { db in
|
||||
try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
if allowedColumns.isEmpty {
|
||||
t.column("__grdb__")
|
||||
} else {
|
||||
@@ -74,7 +74,7 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
try db.makeSelectStatement("SELECT * FROM documents WHERE documents MATCH ?")
|
||||
try db.makeSelectStatement("SELECT * FROM document WHERE document MATCH ?")
|
||||
.cursor(arguments: [rawPattern])
|
||||
.next() // error on next() for invalid patterns
|
||||
}
|
||||
@@ -97,8 +97,8 @@
|
||||
///
|
||||
/// The pattern syntax is documented at https://www.sqlite.org/fts5.html#full_text_query_syntax
|
||||
///
|
||||
/// try db.makeFTS5Pattern(rawPattern: "and", forTable: "documents") // OK
|
||||
/// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "documents") // malformed MATCH expression: [AND]
|
||||
/// try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK
|
||||
/// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND]
|
||||
public func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern {
|
||||
return try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map { $0.name })
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
/// An FTS5 tokenizer, suitable for FTS5 table definitions:
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS5()) { t in
|
||||
/// db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor
|
||||
/// }
|
||||
///
|
||||
@@ -33,7 +33,7 @@
|
||||
|
||||
/// Creates an FTS5 tokenizer descriptor.
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS5()) { t in
|
||||
/// db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// let tokenizer = FTS5TokenizerDescriptor(components: ["porter", "unicode61", "remove_diacritics", "0"])
|
||||
/// t.tokenizer = tokenizer
|
||||
/// }
|
||||
@@ -47,7 +47,7 @@
|
||||
|
||||
/// The "ascii" tokenizer
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS5()) { t in
|
||||
/// db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = .ascii()
|
||||
/// }
|
||||
///
|
||||
@@ -66,7 +66,7 @@
|
||||
|
||||
/// The "porter" tokenizer
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS5()) { t in
|
||||
/// db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = .porter()
|
||||
/// }
|
||||
///
|
||||
@@ -85,7 +85,7 @@
|
||||
|
||||
/// An "unicode61" tokenizer
|
||||
///
|
||||
/// db.create(virtualTable: "books", using: FTS5()) { t in
|
||||
/// db.create(virtualTable: "book", using: FTS5()) { t in
|
||||
/// t.tokenizer = .unicode61()
|
||||
/// }
|
||||
///
|
||||
|
||||
@@ -2,7 +2,7 @@ extension Row {
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() }
|
||||
public static func fetch<Request: FetchRequest>(_ db: Database, _ request: Request) -> Any { preconditionFailure() }
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
|
||||
}
|
||||
@@ -11,7 +11,7 @@ extension DatabaseValueConvertible {
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() }
|
||||
public static func fetch<Request: FetchRequest>(_ db: Database, _ request: Request) -> Any { preconditionFailure() }
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
|
||||
}
|
||||
@@ -20,7 +20,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() }
|
||||
public static func fetch<Request: FetchRequest>(_ db: Database, _ request: Request) -> Any { preconditionFailure() }
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
|
||||
}
|
||||
@@ -30,16 +30,16 @@ extension QueryInterfaceRequest {
|
||||
public func fetch(_ db: Database) -> Any { preconditionFailure() }
|
||||
}
|
||||
|
||||
extension RowConvertible {
|
||||
extension FetchableRecord {
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() }
|
||||
public static func fetch<Request: FetchRequest>(_ db: Database, _ request: Request) -> Any { preconditionFailure() }
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
|
||||
}
|
||||
|
||||
extension RowConvertible where Self: TableMapping {
|
||||
extension FetchableRecord where Self: TableRecord {
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
public static func fetch(_ db: Database) -> Any { preconditionFailure() }
|
||||
@available(*, unavailable, renamed:"fetchCursor")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
extension Request {
|
||||
@available(*, unavailable, renamed:"asRequest(of:)")
|
||||
public func bound<T>(to type: T.Type) -> AnyTypedRequest<T> { preconditionFailure() }
|
||||
extension FetchRequest {
|
||||
@available(*, unavailable, message:"Use QueryInterfaceRequest.asRequest(of:), or AnyFetchRequest")
|
||||
public func bound<T>(to type: T.Type) -> AnyFetchRequest<T> { preconditionFailure() }
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed:"FetchRequest")
|
||||
public typealias Request = FetchRequest
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed:"FetchableRecord")
|
||||
public typealias RowConvertible = FetchableRecord
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed:"TableRecord")
|
||||
public typealias TableMapping = TableRecord
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed:"MutablePersistableRecord")
|
||||
public typealias MutablePersistable = MutablePersistableRecord
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed:"PersistableRecord")
|
||||
public typealias Persistable = PersistableRecord
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed:"TableAlias")
|
||||
public typealias SQLTableQualifier = TableAlias
|
||||
|
||||
extension Database {
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, message: "Use db.columns(in: tableName).count instead")
|
||||
public func columnCount(in tableName: String) throws -> Int { preconditionFailure() }
|
||||
}
|
||||
|
||||
extension SelectStatement {
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed:"DatabaseRegion")
|
||||
public typealias SelectionInfo = DatabaseRegion
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed:"databaseRegion")
|
||||
public var selectionInfo: DatabaseRegion { preconditionFailure() }
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed:"databaseRegion")
|
||||
public var fetchedRegion: DatabaseRegion { preconditionFailure() }
|
||||
}
|
||||
|
||||
extension DatabaseEventKind {
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead")
|
||||
public func impacts(_ region: DatabaseRegion) -> Bool { preconditionFailure() }
|
||||
}
|
||||
|
||||
extension Record {
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed: "hasDatabaseChanges")
|
||||
public var hasPersistentChangedValues: Bool { preconditionFailure() }
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed: "databaseChanges")
|
||||
public var persistentChangedValues: [String: DatabaseValue?] { preconditionFailure() }
|
||||
}
|
||||
|
||||
@available(*, unavailable, message: "Use changes methods defined on the MutablePersistableRecord protocol: databaseEquals(_:), databaseChanges(from:), updateChanges(from:)")
|
||||
public final class RecordBox<T: FetchableRecord & MutablePersistableRecord>: Record { }
|
||||
|
||||
extension MutablePersistableRecord {
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed: "databaseEquals")
|
||||
public func databaseEqual(_ record: Self) -> Bool { preconditionFailure() }
|
||||
}
|
||||
|
||||
extension Row {
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, message: "Use row.scopes.names instead")
|
||||
var scopeNames: Set<String> { preconditionFailure() }
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, message: "Use row.scopes[name] instead")
|
||||
public func scoped(on name: String) -> Row? { preconditionFailure() }
|
||||
}
|
||||
|
||||
extension FetchRequest {
|
||||
|
||||
/// :nodoc:
|
||||
@available(*, unavailable, renamed:"databaseRegion(_:)")
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { preconditionFailure() }
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
// Compatibility layer for Swift < 4.1
|
||||
|
||||
#if !swift(>=4.1)
|
||||
extension Sequence {
|
||||
// From future import SE-0187
|
||||
func compactMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] {
|
||||
return try flatMap(transform)
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeMutablePointer {
|
||||
// From future import SE-0184
|
||||
func deallocate() {
|
||||
deallocate(capacity: 0)
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeMutableRawBufferPointer {
|
||||
// From future import SE-0184
|
||||
func copyMemory<C>(from source: C) where C : Collection, C.Element == UInt8 {
|
||||
copyBytes(from: source)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -9,34 +9,37 @@
|
||||
///
|
||||
/// var migrator = DatabaseMigrator()
|
||||
///
|
||||
/// // v1.0 database
|
||||
/// migrator.registerMigration("createAuthors") { db in
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE authors (
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// creationDate TEXT,
|
||||
/// name TEXT NOT NULL
|
||||
/// )
|
||||
/// """)
|
||||
/// // 1st migration
|
||||
/// migrator.registerMigration("createLibrary") { db in
|
||||
/// try db.create(table: "author") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.column("creationDate", .datetime)
|
||||
/// t.column("name", .text).notNull()
|
||||
/// }
|
||||
///
|
||||
/// try db.create(table: "book") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.column("authorId", .integer)
|
||||
/// .notNull()
|
||||
/// .references("author", onDelete: .cascade)
|
||||
/// t.column("title", .text).notNull()
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// migrator.registerMigration("createBooks") { db in
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE books (
|
||||
/// uuid TEXT PRIMARY KEY,
|
||||
/// authorID INTEGER NOT NULL
|
||||
/// REFERENCES authors(id)
|
||||
/// ON DELETE CASCADE ON UPDATE CASCADE,
|
||||
/// title TEXT NOT NULL
|
||||
/// )
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// // v2.0 database
|
||||
/// // 2nd migration
|
||||
/// migrator.registerMigration("AddBirthYearToAuthors") { db in
|
||||
/// try db.execute("ALTER TABLE authors ADD COLUMN birthYear INT")
|
||||
/// try db.alter(table: "author") { t
|
||||
/// t.add(column: "birthYear", .integer)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Migrations for future versions will be inserted here:
|
||||
/// //
|
||||
/// // // 3rd migration
|
||||
/// // migrator.registerMigration("...") { db in
|
||||
/// // ...
|
||||
/// // }
|
||||
///
|
||||
/// try migrator.migrate(dbQueue)
|
||||
public struct DatabaseMigrator {
|
||||
|
||||
@@ -46,14 +49,12 @@ public struct DatabaseMigrator {
|
||||
|
||||
/// Registers a migration.
|
||||
///
|
||||
/// migrator.registerMigration("createPlayers") { db in
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE players (
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// creationDate TEXT,
|
||||
/// name TEXT NOT NULL
|
||||
/// )
|
||||
/// """)
|
||||
/// migrator.registerMigration("createAuthors") { db in
|
||||
/// try db.create(table: "author") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.column("creationDate", .datetime)
|
||||
/// t.column("name", .text).notNull()
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -69,12 +70,13 @@ public struct DatabaseMigrator {
|
||||
///
|
||||
/// // Add a NOT NULL constraint on players.name:
|
||||
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
|
||||
/// INSERT INTO new_players SELECT * FROM players;
|
||||
/// DROP TABLE players;
|
||||
/// ALTER TABLE new_players RENAME TO players;
|
||||
/// """)
|
||||
/// try db.create(table: "new_player") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.column("name", .text).notNull()
|
||||
/// }
|
||||
/// try db.execute("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
|
||||
@@ -96,12 +98,13 @@ public struct DatabaseMigrator {
|
||||
///
|
||||
/// // Add a NOT NULL constraint on players.name:
|
||||
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
|
||||
/// INSERT INTO new_players SELECT * FROM players;
|
||||
/// DROP TABLE players;
|
||||
/// ALTER TABLE new_players RENAME TO players;
|
||||
/// """)
|
||||
/// try db.create(table: "new_player") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.column("name", .text).notNull()
|
||||
/// }
|
||||
/// try db.execute("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
|
||||
@@ -125,7 +128,7 @@ public struct DatabaseMigrator {
|
||||
/// migrations should apply.
|
||||
/// - throws: An eventual error thrown by the registered migration blocks.
|
||||
public func migrate(_ writer: DatabaseWriter) throws {
|
||||
try writer.write { db in
|
||||
try writer.writeWithoutTransaction { db in
|
||||
try setupMigrations(db)
|
||||
try runMigrations(db)
|
||||
}
|
||||
@@ -140,12 +143,17 @@ public struct DatabaseMigrator {
|
||||
/// - targetIdentifier: The identifier of a registered migration.
|
||||
/// - throws: An eventual error thrown by the registered migration blocks.
|
||||
public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws {
|
||||
try writer.write { db in
|
||||
try writer.writeWithoutTransaction { db in
|
||||
try setupMigrations(db)
|
||||
try runMigrations(db, upTo: targetIdentifier)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the set of applied migration identifiers.
|
||||
public func appliedMigrations(in reader: DatabaseReader) throws -> Set<String> {
|
||||
return try reader.read { try appliedIdentifiers($0) }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Non public
|
||||
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The base protocol for all associations that define a connection between two
|
||||
/// record types.
|
||||
public protocol Association: DerivableRequest {
|
||||
associatedtype OriginRowDecoder
|
||||
associatedtype RowDecoder
|
||||
|
||||
/// The association key defines how rows fetched from this association
|
||||
/// should be consumed.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// // The default key of this association is the name of the
|
||||
/// // database table for teams, let's say "team":
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
/// print(Player.team.key) // Prints "team"
|
||||
///
|
||||
/// // Consume rows:
|
||||
/// let request = Player.including(required: Player.team)
|
||||
/// for row in Row.fetchAll(db, request) {
|
||||
/// let team: Team = row["team"] // the association key
|
||||
/// }
|
||||
///
|
||||
/// The key can be redefined with the `forKey` method:
|
||||
///
|
||||
/// let request = Player.including(required: Player.team.forKey("custom"))
|
||||
/// for row in Row.fetchAll(db, request) {
|
||||
/// let team: Team = row["custom"]
|
||||
/// }
|
||||
var key: String { get }
|
||||
|
||||
/// Creates an association with the given key.
|
||||
///
|
||||
/// This new key impacts how rows fetched from the resulting association
|
||||
/// should be consumed:
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // Consume rows:
|
||||
/// let request = Player.including(required: Player.team.forKey("custom"))
|
||||
/// for row in Row.fetchAll(db, request) {
|
||||
/// let team: Team = row["custom"]
|
||||
/// }
|
||||
func forKey(_ key: String) -> Self
|
||||
|
||||
/// :nodoc:
|
||||
var request: AssociationRequest<RowDecoder> { get }
|
||||
|
||||
/// :nodoc:
|
||||
func joinCondition(_ db: Database) throws -> JoinCondition
|
||||
|
||||
/// :nodoc:
|
||||
func mapRequest(_ transform: (AssociationRequest<RowDecoder>) -> AssociationRequest<RowDecoder>) -> Self
|
||||
}
|
||||
|
||||
extension Association {
|
||||
/// Creates an association with a new set of selected columns.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.color
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team.select([Column("color")])
|
||||
/// var request = Player.including(required: association)
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT player.*, team.color
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team
|
||||
/// .select([Column("id")])
|
||||
/// .select([Column("color")])
|
||||
/// var request = Player.including(required: association)
|
||||
public func select(_ selection: [SQLSelectable]) -> Self {
|
||||
return mapRequest { $0.select(selection) }
|
||||
}
|
||||
|
||||
/// Creates an association with the provided *predicate promise* added to
|
||||
/// the eventual set of already applied predicates.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId AND 1
|
||||
/// let association = Player.team.filter { db in true }
|
||||
/// var request = Player.including(required: association)
|
||||
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
|
||||
return mapRequest { $0.filter(predicate) }
|
||||
}
|
||||
|
||||
/// Creates an association with the provided *orderings promise*.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// // ORDER BY team.name
|
||||
/// let association = Player.team.order { _ in [Column("name")] }
|
||||
/// var request = Player.including(required: association)
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// // ORDER BY team.name
|
||||
/// let association = Player.team
|
||||
/// .order{ _ in [Column("color")] }
|
||||
/// .reversed()
|
||||
/// .order{ _ in [Column("name")] }
|
||||
/// var request = Player.including(required: association)
|
||||
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
|
||||
return mapRequest { $0.order(orderings) }
|
||||
}
|
||||
|
||||
/// Creates an association that reverses applied orderings.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// // ORDER BY team.name DESC
|
||||
/// let association = Player.team.order(Column("name")).reversed()
|
||||
/// var request = Player.including(required: association)
|
||||
///
|
||||
/// If no ordering was applied, the returned association is identical.
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team.reversed()
|
||||
/// var request = Player.including(required: association)
|
||||
public func reversed() -> Self {
|
||||
return mapRequest { $0.reversed() }
|
||||
}
|
||||
|
||||
/// Creates an association with the given key.
|
||||
///
|
||||
/// This new key helps Decodable records decode rows fetched from the
|
||||
/// resulting association:
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// struct PlayerInfo: FetchableRecord, Decodable {
|
||||
/// let player: Player
|
||||
/// let team: Team
|
||||
///
|
||||
/// static func all() -> QueryInterfaceRequest<PlayerInfo> {
|
||||
/// return Player
|
||||
/// .including(required: Player.team.forKey(CodingKeys.team))
|
||||
/// .asRequest(of: PlayerInfo.self)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let playerInfos = PlayerInfo.all().fetchAll(db)
|
||||
/// print(playerInfos.first?.team)
|
||||
public func forKey(_ codingKey: CodingKey) -> Self {
|
||||
return forKey(codingKey.stringValue)
|
||||
}
|
||||
|
||||
/// Creates an association that allows you to define expressions that target
|
||||
/// a specific database table.
|
||||
///
|
||||
/// In the example below, the "team.color = 'red'" condition in the where
|
||||
/// clause could be not achieved without table aliases.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // JOIN team ON ...
|
||||
/// // WHERE team.color = 'red'
|
||||
/// let teamAlias = TableAlias()
|
||||
/// let request = Player
|
||||
/// .including(required: Player.team.aliased(teamAlias))
|
||||
/// .filter(teamAlias[Column("color")] == "red")
|
||||
///
|
||||
/// When you give a name to a table alias, you can reliably inject sql
|
||||
/// snippets in your requests:
|
||||
///
|
||||
/// // SELECT player.*, custom.*
|
||||
/// // JOIN team custom ON ...
|
||||
/// // WHERE custom.color = 'red'
|
||||
/// let teamAlias = TableAlias(name: "custom")
|
||||
/// let request = Player
|
||||
/// .including(required: Player.team.aliased(teamAlias))
|
||||
/// .filter(sql: "custom.color = ?", arguments: ["red"])
|
||||
public func aliased(_ alias: TableAlias) -> Self {
|
||||
return mapRequest { $0.aliased(alias) }
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public typealias JoinCondition = (_ leftAlias: TableAlias, _ rightAlias: TableAlias) -> SQLExpression?
|
||||
|
||||
/// Turns a ForeignKeyRequest into a JoinCondition
|
||||
struct ForeignKeyJoinConditionRequest {
|
||||
var foreignKeyRequest: ForeignKeyRequest
|
||||
var originIsLeft: Bool
|
||||
|
||||
func fetch(_ db: Database) throws -> JoinCondition {
|
||||
let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping
|
||||
let columnMapping: [(left: Column, right: Column)]
|
||||
if originIsLeft {
|
||||
columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) }
|
||||
} else {
|
||||
columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) }
|
||||
}
|
||||
return { (leftAlias, rightAlias) in
|
||||
return columnMapping
|
||||
.map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) }
|
||||
.joined(operator: .and)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Association {
|
||||
/// Creates an association that includes another one. The columns of the
|
||||
/// associated record are selected. The returned association does not
|
||||
/// require that the associated database table contains a matching row.
|
||||
public func including<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
|
||||
return mapRequest { $0.joining(.optional, association) }
|
||||
}
|
||||
|
||||
/// Creates an association that includes another one. The columns of the
|
||||
/// associated record are selected. The returned association requires
|
||||
/// that the associated database table contains a matching row.
|
||||
public func including<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder {
|
||||
return mapRequest { $0.joining(.required, association) }
|
||||
}
|
||||
|
||||
/// Creates an association that joins another one. The columns of the
|
||||
/// associated record are not selected. The returned association does not
|
||||
/// require that the associated database table contains a matching row.
|
||||
public func joining<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
|
||||
return mapRequest { $0.joining(.optional, association.select([])) }
|
||||
}
|
||||
|
||||
/// Creates an association that joins another one. The columns of the
|
||||
/// associated record are not selected. The returned association requires
|
||||
/// that the associated database table contains a matching row.
|
||||
public func joining<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder {
|
||||
return mapRequest { $0.joining(.required, association.select([])) }
|
||||
}
|
||||
}
|
||||
|
||||
extension Association where OriginRowDecoder: MutablePersistableRecord {
|
||||
/// Support for MutablePersistableRecord.request(for:).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Team: {
|
||||
/// static let players = hasMany(Player.self)
|
||||
/// var players: QueryInterfaceRequest<Player> {
|
||||
/// return request(for: Team.players)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let team: Team = ...
|
||||
/// let players = try team.players.fetchAll(db) // [Player]
|
||||
func request(from record: OriginRowDecoder) -> QueryInterfaceRequest<RowDecoder> {
|
||||
// Goal: turn `JOIN association ON association.recordId = record.id`
|
||||
// into a regular request `SELECT * FROM association WHERE association.recordId = 123`
|
||||
|
||||
// We need table aliases to build the joining condition
|
||||
let associationAlias = TableAlias()
|
||||
let recordAlias = TableAlias()
|
||||
|
||||
// Turn the association request into a query interface request:
|
||||
// JOIN association -> SELECT FROM association
|
||||
return QueryInterfaceRequest(request)
|
||||
|
||||
// Turn the JOIN condition into a regular WHERE condition
|
||||
.filter { db in
|
||||
// Build a join condition: `association.recordId = record.id`
|
||||
// We still need to replace `record.id` with the actual record id.
|
||||
guard let joinCondition = try self.joinCondition(db)(recordAlias, associationAlias) else {
|
||||
fatalError("Can't request from record without join condition")
|
||||
}
|
||||
|
||||
// Serialize record: ["id": 123, ...]
|
||||
// We do it as late as possible, when request is about to be
|
||||
// executed, in order to support long-lived reference types.
|
||||
let container = PersistenceContainer(record)
|
||||
|
||||
// Replace `record.id` with 123
|
||||
return joinCondition.resolvedExpression(inContext: [recordAlias: container])
|
||||
}
|
||||
|
||||
// We just added a condition qualified with associationAlias. Don't
|
||||
// risk introducing conflicting aliases that would prevent the user
|
||||
// from setting a custom alias name: force the same alias for the
|
||||
// whole request.
|
||||
.aliased(associationAlias)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
struct AssociationQuery {
|
||||
var source: SQLSource
|
||||
var selection: [SQLSelectable]
|
||||
var filterPromise: DatabasePromise<SQLExpression?>
|
||||
var ordering: QueryOrdering
|
||||
var joins: [AssociationJoin]
|
||||
|
||||
var alias: TableAlias? {
|
||||
return source.alias
|
||||
}
|
||||
}
|
||||
|
||||
extension AssociationQuery {
|
||||
init(_ query: QueryInterfaceQuery) {
|
||||
GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries")
|
||||
GRDBPrecondition(query.groupByExpressions.isEmpty, "Can't join aggregated queries")
|
||||
GRDBPrecondition(query.havingExpression == nil, "Can't join aggregated queries")
|
||||
GRDBPrecondition(query.limit == nil, "Can't join limited queries")
|
||||
|
||||
self.init(
|
||||
source: query.source,
|
||||
selection: query.selection,
|
||||
filterPromise: query.filterPromise,
|
||||
ordering: query.ordering,
|
||||
joins: query.joins)
|
||||
}
|
||||
}
|
||||
|
||||
extension AssociationQuery {
|
||||
func select(_ selection: [SQLSelectable]) -> AssociationQuery {
|
||||
var query = self
|
||||
query.selection = selection
|
||||
return query
|
||||
}
|
||||
|
||||
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> AssociationQuery {
|
||||
var query = self
|
||||
query.filterPromise = query.filterPromise.map { (db, filter) in
|
||||
if let filter = filter {
|
||||
return try filter && predicate(db)
|
||||
} else {
|
||||
return try predicate(db).sqlExpression
|
||||
}
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> AssociationQuery {
|
||||
return order(QueryOrdering(orderings: orderings))
|
||||
}
|
||||
|
||||
func reversed() -> AssociationQuery {
|
||||
return order(ordering.reversed)
|
||||
}
|
||||
|
||||
private func order(_ ordering: QueryOrdering) -> AssociationQuery {
|
||||
var query = self
|
||||
query.ordering = ordering
|
||||
return query
|
||||
}
|
||||
|
||||
func joining(_ join: AssociationJoin) -> AssociationQuery {
|
||||
var query = self
|
||||
query.joins.append(join)
|
||||
return query
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> AssociationQuery {
|
||||
var query = self
|
||||
query.source = source.qualified(with: alias)
|
||||
return query
|
||||
}
|
||||
}
|
||||
|
||||
extension AssociationQuery {
|
||||
/// A finalized query is ready for SQL generation
|
||||
var finalizedQuery: AssociationQuery {
|
||||
var query = self
|
||||
|
||||
let alias = TableAlias()
|
||||
query.source = source.qualified(with: alias)
|
||||
query.selection = selection.map { $0.qualifiedSelectable(with: alias) }
|
||||
query.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) }
|
||||
query.ordering = ordering.qualified(with: alias)
|
||||
query.joins = joins.map { $0.finalizedJoin }
|
||||
|
||||
return query
|
||||
}
|
||||
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
var finalizedAliases: [TableAlias] {
|
||||
var aliases: [TableAlias] = []
|
||||
if let alias = alias {
|
||||
aliases.append(alias)
|
||||
}
|
||||
return joins.reduce(into: aliases) {
|
||||
$0.append(contentsOf: $1.finalizedAliases)
|
||||
}
|
||||
}
|
||||
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
var finalizedSelection: [SQLSelectable] {
|
||||
return joins.reduce(into: selection) {
|
||||
$0.append(contentsOf: $1.finalizedSelection)
|
||||
}
|
||||
}
|
||||
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
var finalizedOrdering: QueryOrdering {
|
||||
return joins.reduce(ordering) {
|
||||
$0.appending($1.finalizedOrdering)
|
||||
}
|
||||
}
|
||||
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? {
|
||||
let selectionWidth = try selection
|
||||
.map { try $0.columnCount(db) }
|
||||
.reduce(0, +)
|
||||
|
||||
var endIndex = startIndex + selectionWidth
|
||||
var scopes: [String: RowAdapter] = [:]
|
||||
for join in joins {
|
||||
if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [join.key]) {
|
||||
GRDBPrecondition(scopes[join.key] == nil, "The association key \"\((keyPath + [join.key]).joined(separator: "."))\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.")
|
||||
scopes[join.key] = joinAdapter
|
||||
endIndex = joinEndIndex
|
||||
}
|
||||
}
|
||||
|
||||
if selectionWidth == 0 && scopes.isEmpty {
|
||||
return nil
|
||||
}
|
||||
|
||||
let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth))
|
||||
return (adapter: adapter.addingScopes(scopes), endIndex: endIndex)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// In `SELECT a.*, b.* FROM a JOIN b ON b.aid = a.id AND b.name = 'foo'`,
|
||||
/// the AssociationRequest is (`b.*` + `b.name = 'foo'`).
|
||||
/// :nodoc:
|
||||
public struct AssociationRequest<T> {
|
||||
let query: AssociationQuery
|
||||
|
||||
init(query: AssociationQuery) {
|
||||
self.query = query
|
||||
}
|
||||
|
||||
init(_ request: QueryInterfaceRequest<T>) {
|
||||
self.init(query: AssociationQuery(request.query))
|
||||
}
|
||||
}
|
||||
|
||||
extension AssociationRequest {
|
||||
func select(_ selection: [SQLSelectable]) -> AssociationRequest {
|
||||
return AssociationRequest(query: query.select(selection))
|
||||
}
|
||||
|
||||
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> AssociationRequest {
|
||||
return AssociationRequest(query: query.filter(predicate))
|
||||
}
|
||||
|
||||
func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> AssociationRequest {
|
||||
return AssociationRequest(query: query.order(orderings))
|
||||
}
|
||||
|
||||
func reversed() -> AssociationRequest {
|
||||
return AssociationRequest(query: query.reversed())
|
||||
}
|
||||
|
||||
func aliased(_ alias: TableAlias) -> AssociationRequest {
|
||||
return AssociationRequest(query: query.qualified(with: alias))
|
||||
}
|
||||
|
||||
func joining<A: Association>(_ joinOperator: AssociationJoinOperator, _ association: A)
|
||||
-> AssociationRequest
|
||||
where A.OriginRowDecoder == T
|
||||
{
|
||||
let join = AssociationJoin(
|
||||
joinOperator: joinOperator,
|
||||
query: association.request.query,
|
||||
key: association.key,
|
||||
joinConditionPromise: DatabasePromise(association.joinCondition))
|
||||
return AssociationRequest(query: query.joining(join))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
/// The BelongsTo association sets up a one-to-one connection from a record
|
||||
/// type to another record type, such as each instance of the declaring record
|
||||
/// "belongs to" an instance of the other record.
|
||||
///
|
||||
/// For example, if your application includes authors and books, and each book
|
||||
/// is assigned its author, you'd declare the association this way:
|
||||
///
|
||||
/// struct Author: TableRecord { ... }
|
||||
/// struct Book: TableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// A BelongsTo associations should be supported by an SQLite foreign key.
|
||||
///
|
||||
/// Foreign keys are the recommended way to declare relationships between
|
||||
/// database tables because not only will SQLite guarantee the integrity of your
|
||||
/// data, but GRDB will be able to use those foreign keys to automatically
|
||||
/// configure your association.
|
||||
///
|
||||
/// You define the foreign key when you create database tables. For example:
|
||||
///
|
||||
/// try db.create(table: "author") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id") // (1)
|
||||
/// t.column("name", .text)
|
||||
/// }
|
||||
/// try db.create(table: "book") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.column("authorId", .integer) // (2)
|
||||
/// .notNull() // (3)
|
||||
/// .indexed() // (4)
|
||||
/// .references("author", onDelete: .cascade) // (5)
|
||||
/// t.column("title", .text)
|
||||
/// }
|
||||
///
|
||||
/// 1. The author table has a primary key.
|
||||
/// 2. The book.authorId column is used to link a book to the author it
|
||||
/// belongs to.
|
||||
/// 3. Make the book.authorId column not null if you want SQLite to guarantee
|
||||
/// that all books have an author.
|
||||
/// 4. Create an index on the book.authorId column in order to ease the
|
||||
/// selection of an author's books.
|
||||
/// 5. Create a foreign key from book.authorId column to authors.id, so that
|
||||
/// SQLite guarantees that no book refers to a missing author. The
|
||||
/// `onDelete: .cascade` option has SQLite automatically delete all of an
|
||||
/// author's books when that author is deleted.
|
||||
/// See https://sqlite.org/foreignkeys.html#fk_actions for more information.
|
||||
///
|
||||
/// The example above uses auto-incremented primary keys. But generally
|
||||
/// speaking, all primary keys are supported.
|
||||
///
|
||||
/// If the database schema does not define foreign keys between tables, you can
|
||||
/// still use BelongsTo associations. But your help is needed to define the
|
||||
/// missing foreign key:
|
||||
///
|
||||
/// struct Book: FetchableRecord, TableRecord {
|
||||
/// static let author = belongsTo(Author.self, using: ForeignKey(...))
|
||||
/// }
|
||||
///
|
||||
/// See ForeignKey for more information.
|
||||
public struct BelongsToAssociation<Origin, Destination>: Association {
|
||||
fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest
|
||||
|
||||
/// :nodoc:
|
||||
public typealias OriginRowDecoder = Origin
|
||||
|
||||
/// :nodoc:
|
||||
public typealias RowDecoder = Destination
|
||||
|
||||
public var key: String
|
||||
|
||||
/// :nodoc:
|
||||
public var request: AssociationRequest<Destination>
|
||||
|
||||
public func forKey(_ key: String) -> BelongsToAssociation<Origin, Destination> {
|
||||
var association = self
|
||||
association.key = key
|
||||
return association
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func joinCondition(_ db: Database) throws -> JoinCondition {
|
||||
return try joinConditionRequest.fetch(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func mapRequest(_ transform: (AssociationRequest<Destination>) -> AssociationRequest<Destination>) -> BelongsToAssociation<Origin, Destination> {
|
||||
var association = self
|
||||
association.request = transform(request)
|
||||
return association
|
||||
}
|
||||
}
|
||||
|
||||
// Allow BelongsToAssociation(...).filter(key: ...)
|
||||
extension BelongsToAssociation: TableRequest where Destination: TableRecord {
|
||||
/// :nodoc:
|
||||
public var databaseTableName: String { return Destination.databaseTableName }
|
||||
}
|
||||
|
||||
extension TableRecord {
|
||||
/// Creates a "Belongs To" association between Self and the
|
||||
/// destination type.
|
||||
///
|
||||
/// struct Author: TableRecord { ... }
|
||||
/// struct Book: TableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
///
|
||||
/// The association will let you define requests that load both the source
|
||||
/// and the destination type:
|
||||
///
|
||||
/// // A request for all books with their authors:
|
||||
/// let request = Book.including(optional: Book.author)
|
||||
///
|
||||
/// To consume those requests, define a type that adopts both the
|
||||
/// FetchableRecord and Decodable protocols:
|
||||
///
|
||||
/// struct BookInfo: FetchableRecord, Decodable {
|
||||
/// var book: Book
|
||||
/// var author: Author?
|
||||
/// }
|
||||
///
|
||||
/// let bookInfos = try dbQueue.read { db in
|
||||
/// return try BookInfo.fetchAll(db, request)
|
||||
/// }
|
||||
/// for bookInfo in bookInfos {
|
||||
/// print("\(bookInfo.book.title) by \(bookInfo.author.name)")
|
||||
/// }
|
||||
///
|
||||
/// It is recommended that you define, alongside the association, a property
|
||||
/// with the same name:
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// var author: QueryInterfaceRequest<Author> {
|
||||
/// return request(for: Book.author)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// This property will let you navigate from the source type to the
|
||||
/// destination type:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let book: Book = ...
|
||||
/// let author = try book.author.fetchOne(db) // Author?
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - destination: The record type at the other side of the association.
|
||||
/// - key: An eventual decoding key for the association. By default, it
|
||||
/// is `destination.databaseTableName`.
|
||||
/// - foreignKey: An eventual foreign key. You need to provide an
|
||||
/// explicit foreign key when GRDB can't infer one from the database
|
||||
/// schema. This happens when the schema does not define any foreign
|
||||
/// key to the destination table, or when the schema defines several
|
||||
/// foreign keys to the destination table.
|
||||
public static func belongsTo<Destination>(
|
||||
_ destination: Destination.Type,
|
||||
key: String? = nil,
|
||||
using foreignKey: ForeignKey? = nil)
|
||||
-> BelongsToAssociation<Self, Destination>
|
||||
where Destination: TableRecord
|
||||
{
|
||||
let foreignKeyRequest = ForeignKeyRequest(
|
||||
originTable: databaseTableName,
|
||||
destinationTable: Destination.databaseTableName,
|
||||
foreignKey: foreignKey)
|
||||
|
||||
let joinConditionRequest = ForeignKeyJoinConditionRequest(
|
||||
foreignKeyRequest: foreignKeyRequest,
|
||||
originIsLeft: true)
|
||||
|
||||
return BelongsToAssociation(
|
||||
joinConditionRequest: joinConditionRequest,
|
||||
key: key ?? Destination.databaseTableName,
|
||||
request: AssociationRequest(Destination.all()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
/// A ForeignKey helps building associations when GRDB can't infer a foreign
|
||||
/// key from the database schema.
|
||||
///
|
||||
/// Sometimes the database schema does not define any foreign key between two
|
||||
/// tables. And sometimes, there are several foreign keys from a table
|
||||
/// to another:
|
||||
///
|
||||
/// | Table book | | Table person |
|
||||
/// | ------------ | | ------------ |
|
||||
/// | id | +-->• id |
|
||||
/// | authorId •---+ | name |
|
||||
/// | translatorId •---+
|
||||
/// | title |
|
||||
///
|
||||
/// When this happens, associations can't be automatically inferred from the
|
||||
/// database schema. GRDB will complain with a fatal error such as "Ambiguous
|
||||
/// foreign key from book to person", or "Could not infer foreign key from book
|
||||
/// to person".
|
||||
///
|
||||
/// Your help is needed. You have to instruct GRDB which foreign key to use:
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// // Define foreign keys
|
||||
/// static let authorForeignKey = ForeignKey(["authorId"]))
|
||||
/// static let translatorForeignKey = ForeignKey(["translatorId"]))
|
||||
///
|
||||
/// // Use foreign keys to define associations:
|
||||
/// static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
/// static let translator = belongsTo(Person.self, using: translatorForeignKey)
|
||||
/// }
|
||||
///
|
||||
/// Foreign keys are always defined from the table that contains the columns at
|
||||
/// the origin of the foreign key. Person's symmetric HasMany associations reuse
|
||||
/// Book's foreign keys:
|
||||
///
|
||||
/// struct Person: TableRecord {
|
||||
/// static let writtenBooks = hasMany(Book.self, using: Book.authorForeignKey)
|
||||
/// static let translatedBooks = hasMany(Book.self, using: Book.translatorForeignKey)
|
||||
/// }
|
||||
///
|
||||
/// Foreign keys can also be defined from query interface columns:
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// enum Columns: String, ColumnExpression {
|
||||
/// case id, title, authorId, translatorId
|
||||
/// }
|
||||
///
|
||||
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
|
||||
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
|
||||
/// }
|
||||
///
|
||||
/// When the destination table of a foreign key does not define any primary key,
|
||||
/// you need to provide the full definition of a foreign key:
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// static let authorForeignKey = ForeignKey(["authorId"], to: ["id"]))
|
||||
/// static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
/// }
|
||||
public struct ForeignKey {
|
||||
var originColumns: [String]
|
||||
var destinationColumns: [String]?
|
||||
|
||||
/// Creates a ForeignKey intended to define a record association.
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// // Define foreign keys
|
||||
/// static let authorForeignKey = ForeignKey(["authorId"]))
|
||||
/// static let translatorForeignKey = ForeignKey(["translatorId"]))
|
||||
///
|
||||
/// // Use foreign keys to define associations:
|
||||
/// static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
/// static let translator = belongsTo(Person.self, using: translatorForeignKey)
|
||||
/// }
|
||||
///
|
||||
/// - parameter originColumns: The columns at the origin of the foreign key.
|
||||
/// - parameter destinationColumns: The columns at the destination of the
|
||||
/// foreign key. When nil (the default), GRDB automatically uses the
|
||||
/// primary key.
|
||||
public init(_ originColumns: [String], to destinationColumns: [String]? = nil) {
|
||||
self.originColumns = originColumns
|
||||
self.destinationColumns = destinationColumns
|
||||
}
|
||||
|
||||
/// Creates a ForeignKey intended to define a record association.
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// // Define columns
|
||||
/// enum Columns: String, ColumnExpression {
|
||||
/// case id, title, authorId, translatorId
|
||||
/// }
|
||||
///
|
||||
/// // Define foreign keys
|
||||
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
|
||||
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
|
||||
///
|
||||
/// // Use foreign keys to define associations:
|
||||
/// static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
/// static let translator = belongsTo(Person.self, using: translatorForeignKey)
|
||||
/// }
|
||||
///
|
||||
/// - parameter originColumns: The columns at the origin of the foreign key.
|
||||
/// - parameter destinationColumns: The columns at the destination of the
|
||||
/// foreign key. When nil (the default), GRDB automatically uses the
|
||||
/// primary key.
|
||||
public init(_ originColumns: [ColumnExpression], to destinationColumns: [ColumnExpression]? = nil) {
|
||||
self.init(originColumns.map { $0.name }, to: destinationColumns?.map { $0.name })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/// ForeignKeyRequest looks for the foreign keys associations need to
|
||||
/// join tables.
|
||||
///
|
||||
/// Mappings come from foreign keys, when they exist in the database schema.
|
||||
///
|
||||
/// When the schema does not define any foreign key, we can still infer complete
|
||||
/// mappings from partial information and primary keys.
|
||||
struct ForeignKeyRequest {
|
||||
let originTable: String
|
||||
let destinationTable: String
|
||||
let originColumns: [String]?
|
||||
let destinationColumns: [String]?
|
||||
|
||||
init(originTable: String, destinationTable: String, foreignKey: ForeignKey?) {
|
||||
self.originTable = originTable
|
||||
self.destinationTable = destinationTable
|
||||
|
||||
self.originColumns = foreignKey?.originColumns
|
||||
self.destinationColumns = foreignKey?.destinationColumns
|
||||
}
|
||||
|
||||
func fetch(_ db: Database) throws -> ForeignKeyInfo {
|
||||
if let originColumns = originColumns, let destinationColumns = destinationColumns {
|
||||
// Total information: no need to query the database schema.
|
||||
GRDBPrecondition(originColumns.count == destinationColumns.count, "Number of columns don't match")
|
||||
let mapping = zip(originColumns, destinationColumns).map {
|
||||
(origin: $0, destination: $1)
|
||||
}
|
||||
return ForeignKeyInfo(destinationTable: destinationTable, mapping: mapping)
|
||||
}
|
||||
|
||||
// Incomplete information: let's look for schema foreign keys
|
||||
let foreignKeys = try db.foreignKeys(on: originTable).filter { foreignKey in
|
||||
if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() {
|
||||
return false
|
||||
}
|
||||
if let originColumns = originColumns {
|
||||
let originColumns = Set(originColumns.lazy.map { $0.lowercased() })
|
||||
let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.origin.lowercased() })
|
||||
if originColumns != foreignKeyColumns {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if let destinationColumns = destinationColumns {
|
||||
// TODO: test
|
||||
let destinationColumns = Set(destinationColumns.lazy.map { $0.lowercased() })
|
||||
let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.destination.lowercased() })
|
||||
if destinationColumns != foreignKeyColumns {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Matching foreign key(s) found
|
||||
if let foreignKey = foreignKeys.first {
|
||||
if foreignKeys.count == 1 {
|
||||
// Non-ambiguous
|
||||
return foreignKey
|
||||
} else {
|
||||
// Ambiguous: can't choose
|
||||
fatalError("Ambiguous foreign key from \(originTable) to \(destinationTable)")
|
||||
}
|
||||
}
|
||||
|
||||
// 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) {
|
||||
let mapping = zip(originColumns, destinationColumns).map {
|
||||
(origin: $0, destination: $1)
|
||||
}
|
||||
return ForeignKeyInfo(destinationTable: destinationTable, mapping: mapping)
|
||||
}
|
||||
}
|
||||
|
||||
fatalError("Could not infer foreign key from \(originTable) to \(destinationTable)")
|
||||
}
|
||||
}
|
||||
|
||||
/// The (origin, destination) column pairs that join a left table to a right table.
|
||||
typealias ForeignKeyMapping = [(origin: String, destination: String)]
|
||||
@@ -0,0 +1,178 @@
|
||||
/// The HasMany association indicates a one-to-many connection between two
|
||||
/// record types, such as each instance of the declaring record "has many"
|
||||
/// instances of the other record.
|
||||
///
|
||||
/// For example, if your application includes authors and books, and each author
|
||||
/// is assigned zero or more books, you'd declare the association this way:
|
||||
///
|
||||
/// struct Book: TableRecord { ... }
|
||||
/// struct Author: TableRecord {
|
||||
/// static let books = hasMany(Book.self)
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// HasMany associations should be supported by an SQLite foreign key.
|
||||
///
|
||||
/// Foreign keys are the recommended way to declare relationships between
|
||||
/// database tables because not only will SQLite guarantee the integrity of your
|
||||
/// data, but GRDB will be able to use those foreign keys to automatically
|
||||
/// configure your association.
|
||||
///
|
||||
/// You define the foreign key when you create database tables. For example:
|
||||
///
|
||||
/// try db.create(table: "author") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id") // (1)
|
||||
/// t.column("name", .text)
|
||||
/// }
|
||||
/// try db.create(table: "book") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.column("authorId", .integer) // (2)
|
||||
/// .notNull() // (3)
|
||||
/// .indexed() // (4)
|
||||
/// .references("author", onDelete: .cascade) // (5)
|
||||
/// t.column("title", .text)
|
||||
/// }
|
||||
///
|
||||
/// 1. The author table has a primary key.
|
||||
/// 2. The book.authorId column is used to link a book to the author it
|
||||
/// belongs to.
|
||||
/// 3. Make the book.authorId column not null if you want SQLite to guarantee
|
||||
/// that all books have an author.
|
||||
/// 4. Create an index on the book.authorId column in order to ease the
|
||||
/// selection of an author's books.
|
||||
/// 5. Create a foreign key from book.authorId column to authors.id, so that
|
||||
/// SQLite guarantees that no book refers to a missing author. The
|
||||
/// `onDelete: .cascade` option has SQLite automatically delete all of an
|
||||
/// author's books when that author is deleted.
|
||||
/// See https://sqlite.org/foreignkeys.html#fk_actions for more information.
|
||||
///
|
||||
/// The example above uses auto-incremented primary keys. But generally
|
||||
/// speaking, all primary keys are supported.
|
||||
///
|
||||
/// If the database schema does not define foreign keys between tables, you can
|
||||
/// still use HasMany associations. But your help is needed to define the
|
||||
/// missing foreign key:
|
||||
///
|
||||
/// struct Author: TableRecord {
|
||||
/// static let books = hasMany(Book.self, using: ForeignKey(...))
|
||||
/// }
|
||||
///
|
||||
/// See ForeignKey for more information.
|
||||
public struct HasManyAssociation<Origin, Destination>: Association {
|
||||
fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest
|
||||
|
||||
/// :nodoc:
|
||||
public typealias OriginRowDecoder = Origin
|
||||
|
||||
/// :nodoc:
|
||||
public typealias RowDecoder = Destination
|
||||
|
||||
public var key: String
|
||||
|
||||
/// :nodoc:
|
||||
public var request: AssociationRequest<Destination>
|
||||
|
||||
public func forKey(_ key: String) -> HasManyAssociation<Origin, Destination> {
|
||||
var association = self
|
||||
association.key = key
|
||||
return association
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func joinCondition(_ db: Database) throws -> JoinCondition {
|
||||
return try joinConditionRequest.fetch(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func mapRequest(_ transform: (AssociationRequest<Destination>) -> AssociationRequest<Destination>) -> HasManyAssociation<Origin, Destination> {
|
||||
var association = self
|
||||
association.request = transform(request)
|
||||
return association
|
||||
}
|
||||
}
|
||||
|
||||
// Allow HasManyAssociation(...).filter(key: ...)
|
||||
extension HasManyAssociation: TableRequest where Destination: TableRecord {
|
||||
/// :nodoc:
|
||||
public var databaseTableName: String { return Destination.databaseTableName }
|
||||
}
|
||||
|
||||
extension TableRecord {
|
||||
/// Creates a "Has many" association between Self and the
|
||||
/// destination type.
|
||||
///
|
||||
/// struct Book: TableRecord { ... }
|
||||
/// struct Author: TableRecord {
|
||||
/// static let books = hasMany(Book.self)
|
||||
/// }
|
||||
///
|
||||
/// The association will let you define requests that load both the source
|
||||
/// and the destination type:
|
||||
///
|
||||
/// // A request for all (author, book) pairs:
|
||||
/// let request = Author.including(required: Author.books)
|
||||
///
|
||||
/// To consume those requests, define a type that adopts both the
|
||||
/// FetchableRecord and Decodable protocols:
|
||||
///
|
||||
/// struct Authorship: FetchableRecord, Decodable {
|
||||
/// var author: Author
|
||||
/// var book: Book
|
||||
/// }
|
||||
///
|
||||
/// let authorships = try dbQueue.read { db in
|
||||
/// return try Authorship.fetchAll(db, request)
|
||||
/// }
|
||||
/// for authorship in authorships {
|
||||
/// print("\(authorship.author.name) wrote \(authorship.book.title)")
|
||||
/// }
|
||||
///
|
||||
/// It is recommended that you define, alongside the association, a property
|
||||
/// with the same name:
|
||||
///
|
||||
/// struct Author: TableRecord {
|
||||
/// static let books = hasMany(Book.self)
|
||||
/// var books: QueryInterfaceRequest<Book> {
|
||||
/// return request(for: Author.books)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// This property will let you navigate from the source type to the
|
||||
/// destination type:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let author: Author = ...
|
||||
/// let books = try author.books.fetchAll(db) // [Book]
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - destination: The record type at the other side of the association.
|
||||
/// - key: An eventual decoding key for the association. By default, it
|
||||
/// is `destination.databaseTableName`.
|
||||
/// - foreignKey: An eventual foreign key. You need to provide an
|
||||
/// explicit foreign key when GRDB can't infer one from the database
|
||||
/// schema. This happens when the schema does not define any foreign
|
||||
/// key from the destination table, or when the schema defines several
|
||||
/// foreign keys from the destination table.
|
||||
public static func hasMany<Destination>(
|
||||
_ destination: Destination.Type,
|
||||
key: String? = nil,
|
||||
using foreignKey: ForeignKey? = nil)
|
||||
-> HasManyAssociation<Self, Destination>
|
||||
where Destination: TableRecord
|
||||
{
|
||||
let foreignKeyRequest = ForeignKeyRequest(
|
||||
originTable: Destination.databaseTableName,
|
||||
destinationTable: databaseTableName,
|
||||
foreignKey: foreignKey)
|
||||
|
||||
let joinConditionRequest = ForeignKeyJoinConditionRequest(
|
||||
foreignKeyRequest: foreignKeyRequest,
|
||||
originIsLeft: false)
|
||||
|
||||
return HasManyAssociation(
|
||||
joinConditionRequest: joinConditionRequest,
|
||||
key: key ?? Destination.databaseTableName,
|
||||
request: AssociationRequest(Destination.all()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
/// The HasOne association indicates a one-to-one connection between two
|
||||
/// record types, such as each instance of the declaring record "has one"
|
||||
/// instances of the other record.
|
||||
///
|
||||
/// For example, if your application has one database table for countries, and
|
||||
/// another for their demographic profiles, you'd declare the association
|
||||
/// this way:
|
||||
///
|
||||
/// struct Demographics: TableRecord { ... }
|
||||
/// struct Country: TableRecord {
|
||||
/// static let demographics = hasOne(Demographics.self)
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// HasOne associations should be supported by an SQLite foreign key.
|
||||
///
|
||||
/// Foreign keys are the recommended way to declare relationships between
|
||||
/// database tables because not only will SQLite guarantee the integrity of your
|
||||
/// data, but GRDB will be able to use those foreign keys to automatically
|
||||
/// configure your association.
|
||||
///
|
||||
/// You define the foreign key when you create database tables. For example:
|
||||
///
|
||||
/// try db.create(table: "country") { t in
|
||||
/// t.column("code", .text).primaryKey() // (1)
|
||||
/// t.column("name", .text)
|
||||
/// }
|
||||
/// try db.create(table: "demographics") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.column("countryCode", .text) // (2)
|
||||
/// .notNull() // (3)
|
||||
/// .unique() // (4)
|
||||
/// .references("country", onDelete: .cascade) // (5)
|
||||
/// t.column("population", .integer)
|
||||
/// t.column("density", .double)
|
||||
/// }
|
||||
///
|
||||
/// 1. The country table has a primary key.
|
||||
/// 2. The demographics.countryCode column is used to link a demographic
|
||||
/// profile to the country it belongs to.
|
||||
/// 3. Make the demographics.countryCode column not null if you want SQLite to
|
||||
/// guarantee that all profiles are linked to a country.
|
||||
/// 4. Create a unique index on the demographics.countryCode column in order to
|
||||
/// guarantee the unicity of any country's profile.
|
||||
/// 5. Create a foreign key from demographics.countryCode column to
|
||||
/// country.code, so that SQLite guarantees that no profile refers to a
|
||||
/// missing country. The `onDelete: .cascade` option has SQLite automatically
|
||||
/// delete a profile when its country is deleted.
|
||||
/// See https://sqlite.org/foreignkeys.html#fk_actions for more information.
|
||||
///
|
||||
/// The example above uses a string primary for the country table. But generally
|
||||
/// speaking, all primary keys are supported.
|
||||
///
|
||||
/// If the database schema does not follow this convention, and does not define
|
||||
/// foreign keys between tables, you can still use HasOne associations. But
|
||||
/// your help is needed to define the missing foreign key:
|
||||
///
|
||||
/// struct Country: FetchableRecord, TableRecord {
|
||||
/// static let demographics = hasOne(Demographics.self, using: ForeignKey(...))
|
||||
/// }
|
||||
///
|
||||
/// See ForeignKey for more information.
|
||||
public struct HasOneAssociation<Origin, Destination> : Association {
|
||||
fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest
|
||||
|
||||
/// :nodoc:
|
||||
public typealias OriginRowDecoder = Origin
|
||||
|
||||
/// :nodoc:
|
||||
public typealias RowDecoder = Destination
|
||||
|
||||
public var key: String
|
||||
|
||||
/// :nodoc:
|
||||
public var request: AssociationRequest<Destination>
|
||||
|
||||
public func forKey(_ key: String) -> HasOneAssociation<Origin, Destination> {
|
||||
var association = self
|
||||
association.key = key
|
||||
return association
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func joinCondition(_ db: Database) throws -> JoinCondition {
|
||||
return try joinConditionRequest.fetch(db)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func mapRequest(_ transform: (AssociationRequest<Destination>) -> AssociationRequest<Destination>) -> HasOneAssociation<Origin, Destination> {
|
||||
var association = self
|
||||
association.request = transform(request)
|
||||
return association
|
||||
}
|
||||
}
|
||||
|
||||
// Allow HasOneAssociation(...).filter(key: ...)
|
||||
extension HasOneAssociation: TableRequest where Destination: TableRecord {
|
||||
/// :nodoc:
|
||||
public var databaseTableName: String { return Destination.databaseTableName }
|
||||
}
|
||||
|
||||
extension TableRecord {
|
||||
/// Creates a "Has one" association between Self and the
|
||||
/// destination type.
|
||||
///
|
||||
/// struct Demographics: TableRecord { ... }
|
||||
/// struct Country: TableRecord {
|
||||
/// static let demographics = hasOne(Demographics.self)
|
||||
/// }
|
||||
///
|
||||
/// The association will let you define requests that load both the source
|
||||
/// and the destination type:
|
||||
///
|
||||
/// // A request for all countries with their demographic profile:
|
||||
/// let request = Country.including(optional: Country.demographics)
|
||||
///
|
||||
/// To consume those requests, define a type that adopts both the
|
||||
/// FetchableRecord and Decodable protocols:
|
||||
///
|
||||
/// struct CountryInfo: FetchableRecord, Decodable {
|
||||
/// var country: Country
|
||||
/// var demographics: Demographics?
|
||||
/// }
|
||||
///
|
||||
/// let countryInfos = try dbQueue.read { db in
|
||||
/// return try CountryInfo.fetchAll(db, request)
|
||||
/// }
|
||||
/// for countryInfo in countryInfos {
|
||||
/// print("\(countryInfo.country.name) has \(countryInfo.demographics.population) citizens")
|
||||
/// }
|
||||
///
|
||||
/// It is recommended that you define, alongside the association, a property
|
||||
/// with the same name:
|
||||
///
|
||||
/// struct Country: TableRecord {
|
||||
/// static let demographics = hasOne(Demographics.self)
|
||||
/// var demographics: QueryInterfaceRequest<Demographics> {
|
||||
/// return request(for: Country.demographics)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// This property will let you navigate from the source type to the
|
||||
/// destination type:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let country: Country = ...
|
||||
/// let demographics = try country.demographics.fetchOne(db) // Demographics?
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - destination: The record type at the other side of the association.
|
||||
/// - key: An eventual decoding key for the association. By default, it
|
||||
/// is `destination.databaseTableName`.
|
||||
/// - foreignKey: An eventual foreign key. You need to provide an
|
||||
/// explicit foreign key when GRDB can't infer one from the database
|
||||
/// schema. This happens when the schema does not define any foreign
|
||||
/// key from the destination table, or when the schema defines several
|
||||
/// foreign keys from the destination table.
|
||||
public static func hasOne<Destination>(
|
||||
_ destination: Destination.Type,
|
||||
key: String? = nil,
|
||||
using foreignKey: ForeignKey? = nil)
|
||||
-> HasOneAssociation<Self, Destination>
|
||||
where Destination: TableRecord
|
||||
{
|
||||
let foreignKeyRequest = ForeignKeyRequest(
|
||||
originTable: Destination.databaseTableName,
|
||||
destinationTable: databaseTableName,
|
||||
foreignKey: foreignKey)
|
||||
|
||||
let joinConditionRequest = ForeignKeyJoinConditionRequest(
|
||||
foreignKeyRequest: foreignKeyRequest,
|
||||
originIsLeft: false)
|
||||
|
||||
return HasOneAssociation(
|
||||
joinConditionRequest: joinConditionRequest,
|
||||
key: key ?? Destination.databaseTableName,
|
||||
request: AssociationRequest(Destination.all()))
|
||||
}
|
||||
}
|
||||
@@ -1,40 +1,111 @@
|
||||
/// A column in the database
|
||||
/// Adopt the ColumnExpression protocol when you define a column type.
|
||||
///
|
||||
/// You can, for example, define a String-based column enum:
|
||||
///
|
||||
/// enum Columns: String, ColumnExpression {
|
||||
/// case id, name, score
|
||||
/// }
|
||||
/// let arthur = try Player.filter(Columns.name == "Arthur").fetchOne(db)
|
||||
///
|
||||
/// You can also define a genuine column type:
|
||||
///
|
||||
/// struct MyColumn: ColumnExpression {
|
||||
/// var name: String
|
||||
/// var sqlType: String
|
||||
/// }
|
||||
/// let nameColumn = MyColumn(name: "name", sqlType: "VARCHAR")
|
||||
/// let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
public struct Column : SQLExpression {
|
||||
public protocol ColumnExpression: SQLExpression {
|
||||
/// The unqualified name of a database column.
|
||||
///
|
||||
/// "score" is a valid unqualified name. "player.score" is not.
|
||||
var name: String { get }
|
||||
}
|
||||
|
||||
extension ColumnExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
return name.quotedDatabaseIdentifier
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return QualifiedColumn(name, alias: alias)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
/// A column in a database table.
|
||||
///
|
||||
/// When you need to introduce your own column type, don't wrap a Column.
|
||||
/// Instead, adopt the ColumnExpression protocol.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
public struct Column: ColumnExpression {
|
||||
/// The hidden rowID column
|
||||
public static let rowID = Column("rowid")
|
||||
|
||||
/// The name of the column
|
||||
public let name: String
|
||||
|
||||
private var qualifier: SQLTableQualifier?
|
||||
public var name: String
|
||||
|
||||
/// Creates a column given its name.
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
}
|
||||
}
|
||||
|
||||
/// A qualified column in the database, as in `SELECT t.a FROM t`
|
||||
struct QualifiedColumn: ColumnExpression {
|
||||
var name: String
|
||||
private let alias: TableAlias
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
if let qualifierName = qualifier?.name {
|
||||
return qualifierName.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier
|
||||
/// Creates a column given its name.
|
||||
init(_ name: String, alias: TableAlias) {
|
||||
self.name = name
|
||||
self.alias = alias
|
||||
}
|
||||
|
||||
func expressionSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
if let qualifier = context.qualifier(for: alias) {
|
||||
return qualifier.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier
|
||||
}
|
||||
return name.quotedDatabaseIdentifier
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func qualified(by qualifier: SQLTableQualifier) -> Column {
|
||||
if self.qualifier != nil {
|
||||
// Never requalify
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
// Never requalify
|
||||
return self
|
||||
}
|
||||
|
||||
func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
|
||||
guard
|
||||
let container = context[alias],
|
||||
let value = container.value(forCaseInsensitiveColumn: name) else
|
||||
{
|
||||
return self
|
||||
}
|
||||
var column = self
|
||||
column.qualifier = qualifier
|
||||
return column
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for column enums:
|
||||
///
|
||||
/// struct Player {
|
||||
/// enum Columns: ColumnExpression {
|
||||
/// case id, name, score
|
||||
/// }
|
||||
/// }
|
||||
extension ColumnExpression where Self: RawRepresentable, Self.RawValue == String {
|
||||
public var name: String {
|
||||
return rawValue
|
||||
}
|
||||
}
|
||||
@@ -2,47 +2,47 @@ extension QueryInterfaceRequest {
|
||||
|
||||
// MARK: Full Text Search
|
||||
|
||||
/// Returns a new QueryInterfaceRequest with a matching predicate added
|
||||
/// to the eventual set of already applied predicates.
|
||||
/// Creates a request with a full-text predicate added to the eventual
|
||||
/// set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// // 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.
|
||||
public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<T> {
|
||||
switch query.source {
|
||||
case .table(let name, let alias)?:
|
||||
return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern ?? DatabaseValue.null))
|
||||
default:
|
||||
// Programmer error
|
||||
fatalError("fts3 match requires a table")
|
||||
guard let pattern = pattern else {
|
||||
return none()
|
||||
}
|
||||
let alias = TableAlias()
|
||||
let qualifiedQuery = query.qualified(with: alias)
|
||||
let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue)
|
||||
return QueryInterfaceRequest(query: qualifiedQuery).filter(matchExpression)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
extension TableRecord {
|
||||
|
||||
// MARK: Full Text Search
|
||||
|
||||
/// Returns a QueryInterfaceRequest with a matching predicate.
|
||||
///
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// // 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.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self> {
|
||||
return all().matching(pattern)
|
||||
}
|
||||
}
|
||||
|
||||
extension Column {
|
||||
extension ColumnExpression {
|
||||
/// A matching SQL expression with the `MATCH` SQL operator.
|
||||
///
|
||||
/// // content MATCH '...'
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
|
||||
// MARK: Full Text Search
|
||||
|
||||
/// Returns a new QueryInterfaceRequest with a matching predicate added
|
||||
/// to the eventual set of already applied predicates.
|
||||
/// Creates a request with a full-text predicate added to the eventual
|
||||
/// set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// // SELECT * FROM book WHERE book MATCH '...'
|
||||
/// var request = Book.all()
|
||||
/// request = request.matching(pattern)
|
||||
///
|
||||
@@ -14,30 +14,26 @@
|
||||
/// database row.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<T> {
|
||||
switch query.source {
|
||||
case .table(let name, let alias)?:
|
||||
if let pattern = pattern {
|
||||
return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern))
|
||||
} else {
|
||||
return filter(false)
|
||||
}
|
||||
default:
|
||||
// Programmer error
|
||||
fatalError("fts5 match requires a table")
|
||||
guard let pattern = pattern else {
|
||||
return none()
|
||||
}
|
||||
let alias = TableAlias()
|
||||
let qualifiedQuery = query.qualified(with: alias)
|
||||
let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue)
|
||||
return QueryInterfaceRequest(query: qualifiedQuery).filter(matchExpression)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
extension TableRecord {
|
||||
|
||||
// MARK: Full Text Search
|
||||
|
||||
/// Returns a QueryInterfaceRequest with a matching predicate.
|
||||
///
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// // SELECT * FROM book WHERE book MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
|
||||
@@ -0,0 +1,588 @@
|
||||
struct DatabasePromise<T> {
|
||||
let resolve: (Database) throws -> T
|
||||
|
||||
init(value: T) {
|
||||
self.resolve = { _ in value }
|
||||
}
|
||||
|
||||
init(_ resolve: @escaping (Database) throws -> T) {
|
||||
self.resolve = resolve
|
||||
}
|
||||
|
||||
func map(_ transform: @escaping (Database, T) throws -> T) -> DatabasePromise {
|
||||
return DatabasePromise { db in
|
||||
try transform(db, self.resolve(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct QueryInterfaceQuery {
|
||||
var source: SQLSource
|
||||
var selection: [SQLSelectable]
|
||||
var isDistinct: Bool
|
||||
var filterPromise: DatabasePromise<SQLExpression?>
|
||||
var groupByExpressions: [SQLExpression]
|
||||
var ordering: QueryOrdering
|
||||
var havingExpression: SQLExpression?
|
||||
var limit: SQLLimit?
|
||||
var joins: [AssociationJoin]
|
||||
|
||||
init(
|
||||
source: SQLSource,
|
||||
selection: [SQLSelectable] = [],
|
||||
isDistinct: Bool = false,
|
||||
filterPromise: DatabasePromise<SQLExpression?> = DatabasePromise(value: nil),
|
||||
groupByExpressions: [SQLExpression] = [],
|
||||
ordering: QueryOrdering = QueryOrdering(),
|
||||
havingExpression: SQLExpression? = nil,
|
||||
limit: SQLLimit? = nil,
|
||||
joins: [AssociationJoin] = [])
|
||||
{
|
||||
self.source = source
|
||||
self.selection = selection
|
||||
self.isDistinct = isDistinct
|
||||
self.filterPromise = filterPromise
|
||||
self.groupByExpressions = groupByExpressions
|
||||
self.ordering = ordering
|
||||
self.havingExpression = havingExpression
|
||||
self.limit = limit
|
||||
self.joins = joins
|
||||
}
|
||||
|
||||
init(_ query: AssociationQuery) {
|
||||
self.init(
|
||||
source: query.source,
|
||||
selection: query.selection,
|
||||
filterPromise: query.filterPromise,
|
||||
ordering: query.ordering,
|
||||
joins: query.joins)
|
||||
}
|
||||
|
||||
var alias: TableAlias? {
|
||||
return source.alias
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceQuery {
|
||||
func select(_ selection: [SQLSelectable]) -> QueryInterfaceQuery {
|
||||
var query = self
|
||||
query.selection = selection
|
||||
return query
|
||||
}
|
||||
|
||||
func distinct() -> QueryInterfaceQuery {
|
||||
var query = self
|
||||
query.isDistinct = true
|
||||
return query
|
||||
}
|
||||
|
||||
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceQuery {
|
||||
var query = self
|
||||
query.filterPromise = query.filterPromise.map { (db, filter) in
|
||||
if let filter = filter {
|
||||
return try filter && predicate(db)
|
||||
} else {
|
||||
return try predicate(db).sqlExpression
|
||||
}
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
func group(_ expressions: [SQLExpressible]) -> QueryInterfaceQuery {
|
||||
var query = self
|
||||
query.groupByExpressions = expressions.map { $0.sqlExpression }
|
||||
return query
|
||||
}
|
||||
|
||||
func having(_ predicate: SQLExpressible) -> QueryInterfaceQuery {
|
||||
var query = self
|
||||
if let havingExpression = query.havingExpression {
|
||||
query.havingExpression = (havingExpression && predicate).sqlExpression
|
||||
} else {
|
||||
query.havingExpression = predicate.sqlExpression
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceQuery {
|
||||
return order(QueryOrdering(orderings: orderings))
|
||||
}
|
||||
|
||||
func reversed() -> QueryInterfaceQuery {
|
||||
return order(ordering.reversed)
|
||||
}
|
||||
|
||||
private func order(_ ordering: QueryOrdering) -> QueryInterfaceQuery {
|
||||
var query = self
|
||||
query.ordering = ordering
|
||||
return query
|
||||
}
|
||||
|
||||
func unordered() -> QueryInterfaceQuery {
|
||||
var query = self
|
||||
query.ordering = QueryOrdering()
|
||||
return query
|
||||
}
|
||||
|
||||
func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceQuery {
|
||||
var query = self
|
||||
query.limit = SQLLimit(limit: limit, offset: offset)
|
||||
return query
|
||||
}
|
||||
|
||||
func joining(_ join: AssociationJoin) -> QueryInterfaceQuery {
|
||||
var query = self
|
||||
query.joins.append(join)
|
||||
return query
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> QueryInterfaceQuery {
|
||||
var query = self
|
||||
query.source = source.qualified(with: alias)
|
||||
return query
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceQuery {
|
||||
/// A finalized query is ready for SQL generation
|
||||
var finalizedQuery: QueryInterfaceQuery {
|
||||
var query = self
|
||||
|
||||
let alias = TableAlias()
|
||||
query.source = source.qualified(with: alias)
|
||||
query.selection = query.selection.map { $0.qualifiedSelectable(with: alias) }
|
||||
query.filterPromise = query.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) }
|
||||
query.groupByExpressions = query.groupByExpressions.map { $0.qualifiedExpression(with: alias) }
|
||||
query.ordering = query.ordering.qualified(with: alias)
|
||||
query.havingExpression = query.havingExpression?.qualifiedExpression(with: alias)
|
||||
|
||||
query.joins = query.joins.map { $0.finalizedJoin }
|
||||
|
||||
return query
|
||||
}
|
||||
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
var finalizedAliases: [TableAlias] {
|
||||
var aliases: [TableAlias] = []
|
||||
if let alias = alias {
|
||||
aliases.append(alias)
|
||||
}
|
||||
return joins.reduce(into: aliases) {
|
||||
$0.append(contentsOf: $1.finalizedAliases)
|
||||
}
|
||||
}
|
||||
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
var finalizedSelection: [SQLSelectable] {
|
||||
return joins.reduce(into: selection) {
|
||||
$0.append(contentsOf: $1.finalizedSelection)
|
||||
}
|
||||
}
|
||||
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
var finalizedOrdering: QueryOrdering {
|
||||
return joins.reduce(ordering) {
|
||||
$0.appending($1.finalizedOrdering)
|
||||
}
|
||||
}
|
||||
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
private func finalizedRowAdapter(_ db: Database) throws -> RowAdapter? {
|
||||
if joins.isEmpty {
|
||||
return nil
|
||||
}
|
||||
|
||||
let selectionWidth = try selection
|
||||
.map { try $0.columnCount(db) }
|
||||
.reduce(0, +)
|
||||
|
||||
var endIndex = selectionWidth
|
||||
var scopes: [String: RowAdapter] = [:]
|
||||
for join in joins {
|
||||
if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) {
|
||||
GRDBPrecondition(scopes[join.key] == nil, "The association key \"\(join.key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.")
|
||||
scopes[join.key] = joinAdapter
|
||||
endIndex = joinEndIndex
|
||||
}
|
||||
}
|
||||
|
||||
if selectionWidth == 0 && scopes.isEmpty {
|
||||
return nil
|
||||
}
|
||||
|
||||
let adapter = RangeRowAdapter(0 ..< (0 + selectionWidth))
|
||||
return adapter.addingScopes(scopes)
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceQuery {
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String {
|
||||
var sql = "SELECT"
|
||||
|
||||
if isDistinct {
|
||||
sql += " DISTINCT"
|
||||
}
|
||||
|
||||
let selection = finalizedSelection
|
||||
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
|
||||
sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ")
|
||||
|
||||
sql += try " FROM " + source.sourceSQL(db, &context)
|
||||
|
||||
for join in joins {
|
||||
sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true)
|
||||
}
|
||||
|
||||
if let filter = try filterPromise.resolve(db) {
|
||||
sql += " WHERE " + filter.expressionSQL(&context)
|
||||
}
|
||||
|
||||
if !groupByExpressions.isEmpty {
|
||||
sql += " GROUP BY "
|
||||
sql += groupByExpressions.map { $0.expressionSQL(&context) }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
|
||||
if let havingExpression = havingExpression {
|
||||
sql += " HAVING " + havingExpression.expressionSQL(&context)
|
||||
}
|
||||
|
||||
let orderings = try finalizedOrdering.resolve(db)
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
|
||||
}
|
||||
|
||||
if let limit = limit {
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
|
||||
return sql
|
||||
}
|
||||
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
private func makeSelectStatement(_ db: Database) throws -> SelectStatement {
|
||||
var context = SQLGenerationContext.queryGenerationContext(aliases: finalizedAliases)
|
||||
let sql = try self.sql(db, &context)
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
statement.arguments = context.arguments!
|
||||
return statement
|
||||
}
|
||||
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
|
||||
guard groupByExpressions.isEmpty else {
|
||||
// Programmer error
|
||||
fatalError("Can't delete query with GROUP BY clause")
|
||||
}
|
||||
|
||||
guard havingExpression == nil else {
|
||||
// Programmer error
|
||||
fatalError("Can't delete query with HAVING clause")
|
||||
}
|
||||
|
||||
guard joins.isEmpty else {
|
||||
// Programmer error
|
||||
fatalError("Can't delete query with JOIN clause")
|
||||
}
|
||||
|
||||
guard case .table = source else {
|
||||
// Programmer error
|
||||
fatalError("Can't delete without any database table")
|
||||
}
|
||||
|
||||
var context = SQLGenerationContext.queryGenerationContext(aliases: finalizedAliases)
|
||||
|
||||
var sql = try "DELETE FROM " + source.sourceSQL(db, &context)
|
||||
|
||||
if let filter = try filterPromise.resolve(db) {
|
||||
sql += " WHERE " + filter.expressionSQL(&context)
|
||||
}
|
||||
|
||||
if let limit = limit {
|
||||
let orderings = try finalizedOrdering.resolve(db)
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
|
||||
}
|
||||
|
||||
if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") {
|
||||
sql += " LIMIT " + limit.sql
|
||||
} else {
|
||||
fatalError("Can't delete query with limit")
|
||||
}
|
||||
}
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
statement.arguments = context.arguments!
|
||||
return statement
|
||||
}
|
||||
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try (makeSelectStatement(db), finalizedRowAdapter(db))
|
||||
}
|
||||
|
||||
func fetchCount(_ db: Database) throws -> Int {
|
||||
let (statement, adapter) = try countQuery.prepare(db)
|
||||
return try Int.fetchOne(statement, adapter: adapter)!
|
||||
}
|
||||
|
||||
/// The database region that the request looks into.
|
||||
/// precondition: self is the result of finalizedQuery
|
||||
func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
let statement = try makeSelectStatement(db)
|
||||
let databaseRegion = statement.databaseRegion
|
||||
|
||||
// Can we intersect the region with rowIds?
|
||||
//
|
||||
// Give up unless request feeds from a single database table
|
||||
guard case .table(tableName: let tableName, alias: _) = source else {
|
||||
// TODO: try harder
|
||||
return databaseRegion
|
||||
}
|
||||
|
||||
// Give up unless primary key is rowId
|
||||
let primaryKeyInfo = try db.primaryKey(tableName)
|
||||
guard primaryKeyInfo.isRowID else {
|
||||
return databaseRegion
|
||||
}
|
||||
|
||||
// Give up unless there is a where clause
|
||||
guard let filter = try filterPromise.resolve(db) else {
|
||||
return databaseRegion
|
||||
}
|
||||
|
||||
// The filter knows better
|
||||
guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else {
|
||||
return databaseRegion
|
||||
}
|
||||
|
||||
// Database regions are case-insensitive: use the canonical table name
|
||||
let canonicalTableName = try db.canonicalTableName(tableName)
|
||||
return databaseRegion.tableIntersection(canonicalTableName, rowIds: rowIds)
|
||||
}
|
||||
|
||||
private var countQuery: QueryInterfaceQuery {
|
||||
guard groupByExpressions.isEmpty && limit == nil else {
|
||||
// SELECT ... GROUP BY ...
|
||||
// SELECT ... LIMIT ...
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
guard joins.isEmpty, case .table = source else {
|
||||
// SELECT ... FROM (something which is not a plain table)
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
|
||||
if selection.count == 1 {
|
||||
guard let count = self.selection[0].count(distinct: isDistinct) else {
|
||||
return trivialCountQuery
|
||||
}
|
||||
var countQuery = self.unordered()
|
||||
countQuery.isDistinct = false
|
||||
countQuery.selection = [count.sqlSelectable]
|
||||
return countQuery
|
||||
} else {
|
||||
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
|
||||
|
||||
guard !isDistinct else {
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
// SELECT expr1, expr2, ... FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
var countQuery = self.unordered()
|
||||
countQuery.selection = [SQLExpressionCount(AllColumns())]
|
||||
return countQuery
|
||||
}
|
||||
}
|
||||
|
||||
// SELECT COUNT(*) FROM (self)
|
||||
private var trivialCountQuery: QueryInterfaceQuery {
|
||||
return QueryInterfaceQuery(
|
||||
source: .query(unordered()),
|
||||
selection: [SQLExpressionCount(AllColumns())])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AssociationJoin
|
||||
|
||||
/// Not to be mismatched with SQL join operators (inner join, left join).
|
||||
///
|
||||
/// AssociationJoinOperator is designed to be hierarchically nested, unlike
|
||||
/// SQL join operators.
|
||||
///
|
||||
/// Consider the following request for (A, B, C) tuples:
|
||||
///
|
||||
/// let r = A.including(optional: A.b.including(required: B.c))
|
||||
///
|
||||
/// It chains three associations, the first optional, the second required.
|
||||
///
|
||||
/// It looks like it means: "Give me all As, along with their Bs, granted those
|
||||
/// Bs have their Cs. For As whose B has no C, give me a nil B".
|
||||
///
|
||||
/// It can not be expressed as one left join, and a regular join, as below,
|
||||
/// Because this would not honor the first optional:
|
||||
///
|
||||
/// -- dubious
|
||||
/// SELECT a.*, b.*, c.*
|
||||
/// FROM a
|
||||
/// LEFT JOIN b ON ...
|
||||
/// JOIN c ON ...
|
||||
///
|
||||
/// Instead, it should:
|
||||
/// - allow (A + missing (B + C))
|
||||
/// - prevent (A + (B + missing C)).
|
||||
///
|
||||
/// This can be expressed in SQL with two left joins, and an extra condition:
|
||||
///
|
||||
/// -- likely correct
|
||||
/// SELECT a.*, b.*, c.*
|
||||
/// FROM a
|
||||
/// LEFT JOIN b ON ...
|
||||
/// LEFT JOIN c ON ...
|
||||
/// WHERE NOT((b.id IS NOT NULL) AND (c.id IS NULL)) -- no B without C
|
||||
///
|
||||
/// This is currently not implemented, and requires a little more thought.
|
||||
/// I don't even know if inventing a whole new way to perform joins should even
|
||||
/// be on the table. But we have a hierarchical way to express joined queries,
|
||||
/// and they have a meaning:
|
||||
///
|
||||
/// // what is my meaning?
|
||||
/// A.including(optional: A.b.including(required: B.c))
|
||||
enum AssociationJoinOperator {
|
||||
case required, optional
|
||||
}
|
||||
|
||||
struct AssociationJoin {
|
||||
var joinOperator: AssociationJoinOperator
|
||||
var query: AssociationQuery
|
||||
var key: String
|
||||
var joinConditionPromise: DatabasePromise<JoinCondition>
|
||||
|
||||
var finalizedJoin: AssociationJoin {
|
||||
var join = self
|
||||
join.query = query.finalizedQuery
|
||||
return join
|
||||
}
|
||||
|
||||
var finalizedAliases: [TableAlias] {
|
||||
return query.finalizedAliases
|
||||
}
|
||||
|
||||
var finalizedSelection: [SQLSelectable] {
|
||||
return query.finalizedSelection
|
||||
}
|
||||
|
||||
var finalizedOrdering: QueryOrdering {
|
||||
return query.finalizedOrdering
|
||||
}
|
||||
|
||||
func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? {
|
||||
return try query.finalizedRowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath)
|
||||
}
|
||||
|
||||
/// precondition: query is the result of finalizedQuery
|
||||
func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String {
|
||||
var isRequiredAllowed = isRequiredAllowed
|
||||
var sql = ""
|
||||
switch joinOperator {
|
||||
case .optional:
|
||||
isRequiredAllowed = false
|
||||
sql += "LEFT JOIN"
|
||||
case .required:
|
||||
guard isRequiredAllowed else {
|
||||
// TODO: chainOptionalRequired
|
||||
fatalError("Not implemented: chaining a required association behind an optional association")
|
||||
}
|
||||
sql += "JOIN"
|
||||
}
|
||||
|
||||
sql += try " " + query.source.sourceSQL(db, &context)
|
||||
|
||||
let rightAlias = query.alias!
|
||||
let filters = try [
|
||||
joinConditionPromise.resolve(db)(leftAlias, rightAlias),
|
||||
query.filterPromise.resolve(db)
|
||||
].compactMap { $0 }
|
||||
if !filters.isEmpty {
|
||||
sql += " ON " + filters.joined(operator: .and).expressionSQL(&context)
|
||||
}
|
||||
|
||||
for join in query.joins {
|
||||
sql += try " " + join.joinSQL(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed)
|
||||
}
|
||||
|
||||
return sql
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLSource
|
||||
|
||||
enum SQLSource {
|
||||
case table(tableName: String, alias: TableAlias?)
|
||||
indirect case query(QueryInterfaceQuery)
|
||||
|
||||
var alias: TableAlias? {
|
||||
switch self {
|
||||
case .table(_, let alias):
|
||||
return alias
|
||||
case .query(let query):
|
||||
return query.alias
|
||||
}
|
||||
}
|
||||
|
||||
func sourceSQL(_ db: Database, _ context: inout SQLGenerationContext) throws -> String {
|
||||
switch self {
|
||||
case .table(let tableName, let alias):
|
||||
if let alias = alias, let aliasName = context.aliasName(for: alias) {
|
||||
return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)"
|
||||
} else {
|
||||
return "\(tableName.quotedDatabaseIdentifier)"
|
||||
}
|
||||
case .query(let query):
|
||||
return try "(\(query.sql(db, &context)))"
|
||||
}
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> SQLSource {
|
||||
switch self {
|
||||
case .table(let tableName, let sourceAlias):
|
||||
if let sourceAlias = sourceAlias {
|
||||
alias.becomeProxy(of: sourceAlias)
|
||||
return self
|
||||
} else {
|
||||
alias.setTableName(tableName)
|
||||
return .table(tableName: tableName, alias: alias)
|
||||
}
|
||||
case .query(let query):
|
||||
return .query(query.qualified(with: alias))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SQLLimit {
|
||||
let limit: Int
|
||||
let offset: Int?
|
||||
|
||||
var sql: String {
|
||||
if let offset = offset {
|
||||
return "\(limit) OFFSET \(offset)"
|
||||
} else {
|
||||
return "\(limit)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLCount {
|
||||
var sqlSelectable: SQLSelectable {
|
||||
switch self {
|
||||
case .all:
|
||||
return SQLExpressionCount(AllColumns())
|
||||
case .distinct(let expression):
|
||||
return SQLExpressionCountDistinct(expression)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
extension QueryInterfaceRequest where RowDecoder: TableRecord {
|
||||
func joining<A: Association>(_ joinOperator: AssociationJoinOperator, _ association: A)
|
||||
-> QueryInterfaceRequest<RowDecoder>
|
||||
where A.OriginRowDecoder == RowDecoder
|
||||
{
|
||||
let join = AssociationJoin(
|
||||
joinOperator: joinOperator,
|
||||
query: association.request.query,
|
||||
key: association.key,
|
||||
joinConditionPromise: DatabasePromise(association.joinCondition))
|
||||
return QueryInterfaceRequest(query: query.joining(join))
|
||||
}
|
||||
|
||||
// MARK: - Associations
|
||||
|
||||
/// Creates a request that includes an association. The columns of the
|
||||
/// associated record are selected. The returned association does not
|
||||
/// require that the associated database table contains a matching row.
|
||||
public func including<A: Association>(optional association: A) -> QueryInterfaceRequest<RowDecoder> where A.OriginRowDecoder == RowDecoder {
|
||||
return joining(.optional, association)
|
||||
}
|
||||
|
||||
/// Creates a request that includes an association. The columns of the
|
||||
/// associated record are selected. The returned association requires
|
||||
/// that the associated database table contains a matching row.
|
||||
public func including<A: Association>(required association: A) -> QueryInterfaceRequest<RowDecoder> where A.OriginRowDecoder == RowDecoder {
|
||||
return joining(.required, association)
|
||||
}
|
||||
|
||||
/// Creates a request that includes an association. The columns of the
|
||||
/// associated record are not selected. The returned association does not
|
||||
/// require that the associated database table contains a matching row.
|
||||
public func joining<A: Association>(optional association: A) -> QueryInterfaceRequest<RowDecoder> where A.OriginRowDecoder == RowDecoder {
|
||||
return joining(.optional, association.select([]))
|
||||
}
|
||||
|
||||
/// Creates a request that includes an association. The columns of the
|
||||
/// associated record are not selected. The returned association requires
|
||||
/// that the associated database table contains a matching row.
|
||||
public func joining<A: Association>(required association: A) -> QueryInterfaceRequest<RowDecoder> where A.OriginRowDecoder == RowDecoder {
|
||||
return joining(.required, association.select([]))
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistableRecord {
|
||||
/// Creates a request that fetches the associated record(s).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Team: {
|
||||
/// static let players = hasMany(Player.self)
|
||||
/// var players: QueryInterfaceRequest<Player> {
|
||||
/// return request(for: Team.players)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let team: Team = ...
|
||||
/// let players = try team.players.fetchAll(db) // [Player]
|
||||
public func request<A: Association>(for association: A) -> QueryInterfaceRequest<A.RowDecoder> where A.OriginRowDecoder == Self {
|
||||
return association.request(from: self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableRecord {
|
||||
|
||||
// MARK: - Associations
|
||||
|
||||
/// Creates a request that includes an association. The columns of the
|
||||
/// associated record are selected. The returned association does not
|
||||
/// require that the associated database table contains a matching row.
|
||||
public static func including<A: Association>(optional association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
|
||||
return all().including(optional: association)
|
||||
}
|
||||
|
||||
/// Creates a request that includes an association. The columns of the
|
||||
/// associated record are selected. The returned association requires
|
||||
/// that the associated database table contains a matching row.
|
||||
public static func including<A: Association>(required association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
|
||||
return all().including(required: association)
|
||||
}
|
||||
|
||||
/// Creates a request that includes an association. The columns of the
|
||||
/// associated record are not selected. The returned association does not
|
||||
/// require that the associated database table contains a matching row.
|
||||
public static func joining<A: Association>(optional association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
|
||||
return all().joining(optional: association)
|
||||
}
|
||||
|
||||
/// Creates a request that includes an association. The columns of the
|
||||
/// associated record are not selected. The returned association requires
|
||||
/// that the associated database table contains a matching row.
|
||||
public static func joining<A: Association>(required association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
|
||||
return all().joining(required: association)
|
||||
}
|
||||
}
|
||||
@@ -2,370 +2,197 @@
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
public struct QueryInterfaceRequest<T> {
|
||||
let query: QueryInterfaceSelectQueryDefinition
|
||||
let query: QueryInterfaceQuery
|
||||
|
||||
init(query: QueryInterfaceSelectQueryDefinition) {
|
||||
init(query: QueryInterfaceQuery) {
|
||||
self.query = query
|
||||
}
|
||||
|
||||
init(_ request: AssociationRequest<T>) {
|
||||
self.query = QueryInterfaceQuery(request.query)
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest : TypedRequest {
|
||||
extension QueryInterfaceRequest : FetchRequest {
|
||||
public typealias RowDecoder = T
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// Returns a tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
///
|
||||
/// - returns: A prepared statement and an eventual row adapter.
|
||||
/// :nodoc:
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try query.prepare(db)
|
||||
return try query.finalizedQuery.prepare(db)
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try query.fetchCount(db)
|
||||
}
|
||||
|
||||
/// The database region that the request looks into.
|
||||
/// Returns the database region that the request looks into.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try query.fetchedRegion(db)
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
return try query.finalizedQuery.databaseRegion(db)
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest {
|
||||
|
||||
// MARK: Request Derivation
|
||||
|
||||
/// A new QueryInterfaceRequest with a new net of selected columns.
|
||||
|
||||
/// Creates a request with a new set of selected columns.
|
||||
///
|
||||
/// // SELECT id, email FROM players
|
||||
/// var request = Player.all()
|
||||
/// request = request.select(Column("id"), Column("email"))
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM players
|
||||
/// request
|
||||
/// .select(Column("id"))
|
||||
/// .select(Column("email"))
|
||||
public func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest<T> {
|
||||
return select(selection)
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with a new net of selected columns.
|
||||
///
|
||||
/// // SELECT id, email FROM players
|
||||
/// // SELECT id, email FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.select([Column("id"), Column("email")])
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM players
|
||||
/// // SELECT email FROM player
|
||||
/// request
|
||||
/// .select([Column("id")])
|
||||
/// .select([Column("email")])
|
||||
public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
query.selection = selection
|
||||
return QueryInterfaceRequest(query: query)
|
||||
return QueryInterfaceRequest(query: query.select(selection))
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with a new net of selected columns.
|
||||
/// Creates a request which returns distinct rows.
|
||||
///
|
||||
/// // SELECT id, email FROM players
|
||||
/// var request = Player.all()
|
||||
/// request = request.select(sql: "id, email")
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM players
|
||||
/// request
|
||||
/// .select(sql: "id")
|
||||
/// .select(sql: "email")
|
||||
public func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<T> {
|
||||
return select(SQLExpressionLiteral(sql, arguments: arguments))
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest which returns distinct rows.
|
||||
///
|
||||
/// // SELECT DISTINCT * FROM players
|
||||
/// // SELECT DISTINCT * FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.distinct()
|
||||
///
|
||||
/// // SELECT DISTINCT name FROM players
|
||||
/// // SELECT DISTINCT name FROM player
|
||||
/// var request = Player.select(Column("name"))
|
||||
/// request = request.distinct()
|
||||
public func distinct() -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
query.isDistinct = true
|
||||
return QueryInterfaceRequest(query: query)
|
||||
return QueryInterfaceRequest(query: query.distinct())
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *predicate* added to the
|
||||
/// Creates a request with the provided *predicate promise* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
/// // SELECT * FROM player WHERE 1
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(Column("email") == "arthur@example.com")
|
||||
public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T> {
|
||||
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
|
||||
if let expression = expression {
|
||||
return expression && predicate.sqlExpression
|
||||
} else {
|
||||
return predicate.sqlExpression
|
||||
}
|
||||
})
|
||||
/// request = request.filter { db in true }
|
||||
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest<T> {
|
||||
return QueryInterfaceRequest(query: query.filter(predicate))
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"])
|
||||
public func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<T> {
|
||||
return filter(SQLExpressionLiteral(sql, arguments: arguments))
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest grouped according to *expressions*.
|
||||
public func group(_ expressions: SQLExpressible...) -> QueryInterfaceRequest<T> {
|
||||
return group(expressions)
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest grouped according to *expressions*.
|
||||
/// Creates a request grouped according to *expressions*.
|
||||
public func group(_ expressions: [SQLExpressible]) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
query.groupByExpressions = expressions.map { $0.sqlExpression }
|
||||
return QueryInterfaceRequest(query: query)
|
||||
return QueryInterfaceRequest(query: query.group(expressions))
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with a new grouping.
|
||||
public func group(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<T> {
|
||||
return group(SQLExpressionLiteral(sql, arguments: arguments))
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *predicate* added to the
|
||||
/// Creates a request with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
if let havingExpression = query.havingExpression {
|
||||
query.havingExpression = (havingExpression && predicate).sqlExpression
|
||||
} else {
|
||||
query.havingExpression = predicate.sqlExpression
|
||||
}
|
||||
return QueryInterfaceRequest(query: query)
|
||||
return QueryInterfaceRequest(query: query.having(predicate))
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *sql* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
public func having(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<T> {
|
||||
return having(SQLExpressionLiteral(sql, arguments: arguments))
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *orderings*.
|
||||
/// Creates a request with the provided *orderings promise*.
|
||||
///
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order(Column("name"))
|
||||
/// request = request.order { _ in [Column("name")] }
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// request
|
||||
/// .order(Column("email"))
|
||||
/// .order{ _ in [Column("email")] }
|
||||
/// .reversed()
|
||||
/// .order(Column("name"))
|
||||
public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<T> {
|
||||
return order(orderings)
|
||||
/// .order{ _ in [Column("name")] }
|
||||
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest<T> {
|
||||
return QueryInterfaceRequest(query: query.order(orderings))
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *orderings*.
|
||||
/// Creates a request that reverses applied orderings.
|
||||
///
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order([Column("name")])
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// request
|
||||
/// .order([Column("email")])
|
||||
/// .reversed()
|
||||
/// .order([Column("name")])
|
||||
public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
query.orderings = orderings
|
||||
query.isReversed = false
|
||||
return QueryInterfaceRequest(query: query)
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *sql* used for sorting.
|
||||
///
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order(sql: "name")
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// request
|
||||
/// .order(sql: "email")
|
||||
/// .order(sql: "name")
|
||||
public func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<T> {
|
||||
return order([SQLExpressionLiteral(sql, arguments: arguments)])
|
||||
}
|
||||
|
||||
/// A new QueryInterfaceRequest sorted in reversed order.
|
||||
///
|
||||
/// // SELECT * FROM players ORDER BY name DESC
|
||||
/// // SELECT * FROM player ORDER BY name DESC
|
||||
/// var request = Player.all().order(Column("name"))
|
||||
/// request = request.reversed()
|
||||
///
|
||||
/// If no ordering was applied, the returned request is identical.
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.reversed()
|
||||
public func reversed() -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
query.isReversed = !query.isReversed
|
||||
return QueryInterfaceRequest(query: query)
|
||||
return QueryInterfaceRequest(query: query.reversed())
|
||||
}
|
||||
|
||||
/// A QueryInterfaceRequest which fetches *limit* rows, starting
|
||||
/// at *offset*.
|
||||
/// Creates a request which fetches *limit* rows, starting at *offset*.
|
||||
///
|
||||
/// // SELECT * FROM players LIMIT 1
|
||||
/// // SELECT * FROM player LIMIT 1
|
||||
/// var request = Player.all()
|
||||
/// request = request.limit(1)
|
||||
///
|
||||
/// Any previous limit is replaced.
|
||||
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
query.limit = SQLLimit(limit: limit, offset: offset)
|
||||
return QueryInterfaceRequest(query: query)
|
||||
return QueryInterfaceRequest(query: query.limit(limit, offset: offset))
|
||||
}
|
||||
|
||||
/// Creates a request that allows you to define expressions that target
|
||||
/// a specific database table.
|
||||
///
|
||||
/// In the example below, the "team.avgScore < player.score" condition in
|
||||
/// the ON clause could be not achieved without table aliases.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // JOIN team ON ... AND team.avgScore < player.score
|
||||
/// let playerAlias = TableAlias()
|
||||
/// let request = Player
|
||||
/// .all()
|
||||
/// .aliased(playerAlias)
|
||||
/// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
|
||||
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest {
|
||||
return QueryInterfaceRequest(query: query.qualified(with: alias))
|
||||
}
|
||||
|
||||
/// Creates a request bound to type Target.
|
||||
///
|
||||
/// The returned request can fetch if the type Target is fetchable (Row,
|
||||
/// value, record).
|
||||
///
|
||||
/// // Int?
|
||||
/// let maxScore = try Player
|
||||
/// .select(max(scoreColumn))
|
||||
/// .asRequest(of: Int.self) // <--
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// - parameter type: The fetched type Target
|
||||
/// - returns: A typed request bound to type Target.
|
||||
public func asRequest<Target>(of type: Target.Type) -> QueryInterfaceRequest<Target> {
|
||||
return QueryInterfaceRequest<Target>(query: query)
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest where T: TableMapping {
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id = 1
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(key: 1)
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<T> {
|
||||
guard let key = key else {
|
||||
return T.none()
|
||||
}
|
||||
|
||||
return filter(keys: [key])
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id IN (1, 2, 3)
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(keys: [1, 2, 3])
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<T> where Sequence.Element: DatabaseValueConvertible {
|
||||
let keys = Array(keys)
|
||||
let makePredicate: (Column) -> SQLExpression
|
||||
switch keys.count {
|
||||
case 0:
|
||||
return T.none()
|
||||
case 1:
|
||||
makePredicate = { $0 == keys[0] }
|
||||
default:
|
||||
makePredicate = { keys.contains($0) }
|
||||
}
|
||||
|
||||
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
|
||||
let primaryKey = try db.primaryKey(T.databaseTableName)
|
||||
GRDBPrecondition(primaryKey.columns.count == 1, "Requesting by key requires a single-column primary key in the table \(T.databaseTableName)")
|
||||
let keysPredicate = makePredicate(Column(primaryKey.columns[0]))
|
||||
if let expression = expression {
|
||||
return expression && keysPredicate
|
||||
} else {
|
||||
return keysPredicate
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR'
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(key: ["personId": 1, "countryCode": "FR"])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<T> {
|
||||
guard let key = key else {
|
||||
return T.none()
|
||||
}
|
||||
|
||||
return filter(keys: [key])
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ...
|
||||
/// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<T> {
|
||||
guard !keys.isEmpty else {
|
||||
return T.none()
|
||||
}
|
||||
|
||||
return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in
|
||||
let keyPredicates: [SQLExpression] = try keys.map { key in
|
||||
// Prevent filter(db, keys: [[:]])
|
||||
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
|
||||
|
||||
// Prevent filter(keys: [["foo": 1, "bar": 2]]) where
|
||||
// ("foo", "bar") is not a unique key (primary key or columns of a
|
||||
// unique index)
|
||||
guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: T.databaseTableName) else {
|
||||
fatalError("table \(T.databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))")
|
||||
}
|
||||
|
||||
let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() }
|
||||
let columnPredicates: [SQLExpression] = key
|
||||
// Sort key columns in the same order as the unique index
|
||||
.sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! }
|
||||
.map { (column, value) in Column(column) == value }
|
||||
return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty
|
||||
}
|
||||
|
||||
let keysPredicate = SQLBinaryOperator.or.join(keyPredicates)! // not nil because keyPredicates is not empty
|
||||
|
||||
if let expression = expression {
|
||||
return expression && keysPredicate
|
||||
} else {
|
||||
return keysPredicate
|
||||
}
|
||||
})
|
||||
/// Conditional conformance to TableRequest when RowDecoder conforms
|
||||
/// to TableRecord:
|
||||
///
|
||||
/// let request = Player.all()
|
||||
/// request.filter(key: ...)
|
||||
/// request.filter(keys: ...)
|
||||
extension QueryInterfaceRequest: TableRequest where RowDecoder: TableRecord {
|
||||
/// :nodoc:
|
||||
public var databaseTableName: String {
|
||||
return RowDecoder.databaseTableName
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
|
||||
extension QueryInterfaceRequest where T: MutablePersistableRecord {
|
||||
|
||||
// MARK: Deleting
|
||||
|
||||
@@ -381,177 +208,215 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
extension TableRecord {
|
||||
|
||||
// MARK: Request Derivation
|
||||
|
||||
/// Creates a QueryInterfaceRequest which fetches all records.
|
||||
/// Creates a request which fetches all records.
|
||||
///
|
||||
/// // SELECT * FROM players
|
||||
/// // SELECT * FROM player
|
||||
/// let request = Player.all()
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func all() -> QueryInterfaceRequest<Self> {
|
||||
return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: databaseSelection, from: .table(name: databaseTableName, alias: nil)))
|
||||
let query = QueryInterfaceQuery(
|
||||
source: .table(tableName: databaseTableName, alias: nil),
|
||||
selection: databaseSelection)
|
||||
return QueryInterfaceRequest(query: query)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest which fetches no record.
|
||||
/// Creates a request which fetches no record.
|
||||
public static func none() -> QueryInterfaceRequest<Self> {
|
||||
return filter(false)
|
||||
return all().none() // don't laugh
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest which selects *selection*.
|
||||
/// Creates a request which selects *selection*.
|
||||
///
|
||||
/// // SELECT id, email FROM players
|
||||
/// // SELECT id, email FROM player
|
||||
/// let request = Player.select(Column("id"), Column("email"))
|
||||
public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest<Self> {
|
||||
return all().select(selection)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest which selects *selection*.
|
||||
/// Creates a request which selects *selection*.
|
||||
///
|
||||
/// // SELECT id, email FROM players
|
||||
/// // SELECT id, email FROM player
|
||||
/// let request = Player.select([Column("id"), Column("email")])
|
||||
public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest<Self> {
|
||||
return all().select(selection)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest which selects *sql*.
|
||||
/// Creates a request which selects *sql*.
|
||||
///
|
||||
/// // SELECT id, email FROM players
|
||||
/// // SELECT id, email FROM player
|
||||
/// let request = Player.select(sql: "id, email")
|
||||
public static func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
|
||||
return all().select(sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided *predicate*.
|
||||
/// Creates a request with the provided *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
/// let request = Player.filter(Column("email") == "arthur@example.com")
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(predicate)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
/// Creates a request with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id = 1
|
||||
/// // SELECT * FROM player WHERE id = 1
|
||||
/// let request = Player.filter(key: 1)
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(key: key)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
/// Creates a request with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE id IN (1, 2, 3)
|
||||
/// // SELECT * FROM player WHERE id IN (1, 2, 3)
|
||||
/// let request = Player.filter(keys: [1, 2, 3])
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func filter<Sequence: Swift.Sequence>(keys: Sequence) -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
|
||||
return all().filter(keys: keys)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
/// Creates a request with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR'
|
||||
/// // SELECT * FROM passport WHERE personId = 1 AND countryCode = 'FR'
|
||||
/// let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(key: key)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided primary key *predicate*.
|
||||
/// Creates a request with the provided primary key *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ...
|
||||
/// // SELECT * FROM passport WHERE (personId = 1 AND countryCode = 'FR') OR ...
|
||||
/// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...])
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(keys: keys)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided *predicate*.
|
||||
/// Creates a request with the provided *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
/// let request = Player.filter(sql: "email = ?", arguments: ["arthur@example.com"])
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest sorted according to the
|
||||
/// Creates a request sorted according to the
|
||||
/// provided *orderings*.
|
||||
///
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// let request = Player.order(Column("name"))
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<Self> {
|
||||
return all().order(orderings)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest sorted according to the
|
||||
/// Creates a request sorted according to the
|
||||
/// provided *orderings*.
|
||||
///
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// let request = Player.order([Column("name")])
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<Self> {
|
||||
return all().order(orderings)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest sorted according to *sql*.
|
||||
/// Creates a request sorted by primary key.
|
||||
///
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// // SELECT * FROM player ORDER BY id
|
||||
/// let request = Player.orderByPrimaryKey()
|
||||
///
|
||||
/// // SELECT * FROM country ORDER BY code
|
||||
/// let request = Country.orderByPrimaryKey()
|
||||
///
|
||||
/// 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 static func orderByPrimaryKey() -> QueryInterfaceRequest<Self> {
|
||||
return all().orderByPrimaryKey()
|
||||
}
|
||||
|
||||
/// Creates a request sorted according to *sql*.
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// let request = Player.order(sql: "name")
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
|
||||
return all().order(sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest which fetches *limit* rows, starting at
|
||||
/// Creates a request which fetches *limit* rows, starting at
|
||||
/// *offset*.
|
||||
///
|
||||
/// // SELECT * FROM players LIMIT 1
|
||||
/// // SELECT * FROM player LIMIT 1
|
||||
/// let request = Player.limit(1)
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
/// all requests by the `TableMapping.databaseSelection` property, or
|
||||
/// for individual requests with the `TableMapping.select` method.
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<Self> {
|
||||
return all().limit(limit, offset: offset)
|
||||
}
|
||||
|
||||
/// Creates a request that allows you to define expressions that target
|
||||
/// a specific database table.
|
||||
///
|
||||
/// In the example below, the "team.avgScore < player.score" condition in
|
||||
/// the ON clause could be not achieved without table aliases.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // JOIN team ON ... AND team.avgScore < player.score
|
||||
/// let playerAlias = TableAlias()
|
||||
/// let request = Player
|
||||
/// .aliased(playerAlias)
|
||||
/// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
|
||||
public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<Self> {
|
||||
return all().aliased(alias)
|
||||
}
|
||||
}
|
||||
@@ -1,309 +0,0 @@
|
||||
// MARK: - QueryInterfaceSelectQueryDefinition
|
||||
|
||||
struct DatabasePromise<T> {
|
||||
let resolve: (Database) throws -> T
|
||||
|
||||
init(value: T) {
|
||||
self.resolve = { _ in value }
|
||||
}
|
||||
|
||||
init(_ resolve: @escaping (Database) throws -> T) {
|
||||
self.resolve = resolve
|
||||
}
|
||||
|
||||
func map(_ transform: @escaping (Database, T) throws -> T) -> DatabasePromise {
|
||||
return DatabasePromise { db in
|
||||
try transform(db, self.resolve(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct QueryInterfaceSelectQueryDefinition {
|
||||
var selection: [SQLSelectable]
|
||||
var isDistinct: Bool
|
||||
var source: SQLSource?
|
||||
var wherePromise: DatabasePromise<SQLExpression?>
|
||||
var groupByExpressions: [SQLExpression]
|
||||
var orderings: [SQLOrderingTerm]
|
||||
var isReversed: Bool
|
||||
var havingExpression: SQLExpression?
|
||||
var limit: SQLLimit?
|
||||
|
||||
init(
|
||||
select selection: [SQLSelectable],
|
||||
isDistinct: Bool = false,
|
||||
from source: SQLSource? = nil,
|
||||
filter whereExpression: SQLExpression? = nil,
|
||||
groupBy groupByExpressions: [SQLExpression] = [],
|
||||
orderBy orderings: [SQLOrderingTerm] = [],
|
||||
isReversed: Bool = false,
|
||||
having havingExpression: SQLExpression? = nil,
|
||||
limit: SQLLimit? = nil)
|
||||
{
|
||||
self.selection = selection
|
||||
self.isDistinct = isDistinct
|
||||
self.source = source
|
||||
self.wherePromise = DatabasePromise(value: whereExpression)
|
||||
self.groupByExpressions = groupByExpressions
|
||||
self.orderings = orderings
|
||||
self.isReversed = isReversed
|
||||
self.havingExpression = havingExpression
|
||||
self.limit = limit
|
||||
}
|
||||
|
||||
func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceSelectQueryDefinition {
|
||||
var query = self
|
||||
query.wherePromise = query.wherePromise.map(transform)
|
||||
return query
|
||||
}
|
||||
|
||||
func sql(_ db: Database, _ arguments: inout StatementArguments?) throws -> String {
|
||||
var sql = "SELECT"
|
||||
|
||||
if isDistinct {
|
||||
sql += " DISTINCT"
|
||||
}
|
||||
|
||||
assert(!selection.isEmpty)
|
||||
sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ")
|
||||
|
||||
if let source = source {
|
||||
sql += try " FROM " + source.sourceSQL(db, &arguments)
|
||||
}
|
||||
|
||||
if let whereExpression = try wherePromise.resolve(db) {
|
||||
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
if !groupByExpressions.isEmpty {
|
||||
sql += " GROUP BY " + groupByExpressions.map { $0.expressionSQL(&arguments) }.joined(separator: ", ")
|
||||
}
|
||||
|
||||
if let havingExpression = havingExpression {
|
||||
sql += " HAVING " + havingExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
let orderings = self.queryOrderings
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ")
|
||||
}
|
||||
|
||||
if let limit = limit {
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
|
||||
return sql
|
||||
}
|
||||
|
||||
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
|
||||
guard groupByExpressions.isEmpty else {
|
||||
// Programmer error
|
||||
fatalError("Can't delete query with GROUP BY expression")
|
||||
}
|
||||
|
||||
guard havingExpression == nil else {
|
||||
// Programmer error
|
||||
fatalError("Can't delete query with GROUP BY expression")
|
||||
}
|
||||
|
||||
var sql = "DELETE"
|
||||
var arguments: StatementArguments? = StatementArguments()
|
||||
|
||||
if let source = source {
|
||||
sql += try " FROM " + source.sourceSQL(db, &arguments)
|
||||
}
|
||||
|
||||
if let whereExpression = try wherePromise.resolve(db) {
|
||||
sql += " WHERE " + whereExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
if let limit = limit {
|
||||
let orderings = self.queryOrderings
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ")
|
||||
}
|
||||
|
||||
if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") {
|
||||
sql += " LIMIT " + limit.sql
|
||||
} else {
|
||||
fatalError("Can't delete query with limit")
|
||||
}
|
||||
}
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
statement.arguments = arguments!
|
||||
return statement
|
||||
}
|
||||
|
||||
private var queryOrderings: [SQLOrderingTerm] {
|
||||
if isReversed {
|
||||
if orderings.isEmpty {
|
||||
// https://www.sqlite.org/lang_createtable.html#rowid
|
||||
//
|
||||
// > The rowid value can be accessed using one of the special
|
||||
// > case-independent names "rowid", "oid", or "_rowid_" in
|
||||
// > place of a column name. If a table contains a user defined
|
||||
// > column named "rowid", "oid" or "_rowid_", then that name
|
||||
// > always refers the explicitly declared column and cannot be
|
||||
// > used to retrieve the integer rowid value.
|
||||
//
|
||||
// Here we assume that rowid is not a custom column.
|
||||
// TODO: support for user-defined rowid column.
|
||||
// TODO: support for WITHOUT ROWID tables.
|
||||
return [Column.rowID.desc]
|
||||
} else {
|
||||
return orderings.map { $0.reversed }
|
||||
}
|
||||
} else {
|
||||
return orderings
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove ordering
|
||||
var unorderedQuery: QueryInterfaceSelectQueryDefinition {
|
||||
var query = self
|
||||
query.isReversed = false
|
||||
query.orderings = []
|
||||
return query
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceSelectQueryDefinition : Request {
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
var arguments: StatementArguments? = StatementArguments()
|
||||
let sql = try self.sql(db, &arguments)
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
try statement.setArgumentsWithValidation(arguments!)
|
||||
return (statement, nil)
|
||||
}
|
||||
|
||||
func fetchCount(_ db: Database) throws -> Int {
|
||||
return try Int.fetchOne(db, countQuery)!
|
||||
}
|
||||
|
||||
/// The database region that the request looks into.
|
||||
func fetchedRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
let (statement, _) = try prepare(db)
|
||||
let region = statement.fetchedRegion
|
||||
|
||||
// Can we intersect the region with rowIds?
|
||||
//
|
||||
// Give up unless request feeds from a single database table
|
||||
guard let source = source else {
|
||||
return region
|
||||
}
|
||||
guard case .table(name: let tableName, alias: _) = source else {
|
||||
return region
|
||||
}
|
||||
|
||||
// Give up unless primary key is rowId
|
||||
let primaryKeyInfo = try db.primaryKey(tableName)
|
||||
guard primaryKeyInfo.isRowID else {
|
||||
return region
|
||||
}
|
||||
|
||||
// Give up unless there is a where clause
|
||||
guard let whereExpression = try wherePromise.resolve(db) else {
|
||||
return region
|
||||
}
|
||||
|
||||
// The whereExpression knows better
|
||||
guard let rowIds = whereExpression.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else {
|
||||
return region
|
||||
}
|
||||
|
||||
// Database regions are case-insensitive: use the canonical table name
|
||||
let canonicalTableName = try db.canonicalName(table: tableName)
|
||||
return region.tableIntersection(canonicalTableName, rowIds: rowIds)
|
||||
}
|
||||
|
||||
private var countQuery: QueryInterfaceSelectQueryDefinition {
|
||||
guard groupByExpressions.isEmpty && limit == nil else {
|
||||
// SELECT ... GROUP BY ...
|
||||
// SELECT ... LIMIT ...
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
guard let source = source, case .table = source else {
|
||||
// SELECT ... FROM (something which is not a table)
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
assert(!selection.isEmpty)
|
||||
if selection.count == 1 {
|
||||
guard let count = self.selection[0].count(distinct: isDistinct) else {
|
||||
return trivialCountQuery
|
||||
}
|
||||
var countQuery = unorderedQuery
|
||||
countQuery.isDistinct = false
|
||||
countQuery.selection = [count.sqlSelectable]
|
||||
return countQuery
|
||||
} else {
|
||||
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
|
||||
|
||||
guard !isDistinct else {
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
// SELECT expr1, expr2, ... FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
var countQuery = unorderedQuery
|
||||
countQuery.selection = [SQLExpressionCount(AllColumns())]
|
||||
return countQuery
|
||||
}
|
||||
}
|
||||
|
||||
// SELECT COUNT(*) FROM (self)
|
||||
private var trivialCountQuery: QueryInterfaceSelectQueryDefinition {
|
||||
return QueryInterfaceSelectQueryDefinition(
|
||||
select: [SQLExpressionCount(AllColumns())],
|
||||
from: .query(query: unorderedQuery, alias: nil))
|
||||
}
|
||||
}
|
||||
|
||||
indirect enum SQLSource {
|
||||
case table(name: String, alias: String?)
|
||||
case query(query: QueryInterfaceSelectQueryDefinition, alias: String?)
|
||||
|
||||
func sourceSQL(_ db: Database, _ arguments: inout StatementArguments?) throws -> String {
|
||||
switch self {
|
||||
case .table(let table, let alias):
|
||||
if let alias = alias {
|
||||
return table.quotedDatabaseIdentifier + " AS " + alias.quotedDatabaseIdentifier
|
||||
} else {
|
||||
return table.quotedDatabaseIdentifier
|
||||
}
|
||||
case .query(let query, let alias):
|
||||
if let alias = alias {
|
||||
return try "(" + query.sql(db, &arguments) + ") AS " + alias.quotedDatabaseIdentifier
|
||||
} else {
|
||||
return try "(" + query.sql(db, &arguments) + ")"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SQLLimit {
|
||||
let limit: Int
|
||||
let offset: Int?
|
||||
|
||||
var sql: String {
|
||||
if let offset = offset {
|
||||
return "\(limit) OFFSET \(offset)"
|
||||
} else {
|
||||
return "\(limit)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLCount {
|
||||
var sqlSelectable: SQLSelectable {
|
||||
switch self {
|
||||
case .all:
|
||||
return SQLExpressionCount(AllColumns())
|
||||
case .distinct(let expression):
|
||||
return SQLExpressionCountDistinct(expression)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/// QueryOrdering provides the order clause to QueryInterfaceQuery
|
||||
/// and AssociationQuery.
|
||||
struct QueryOrdering {
|
||||
private var elements: [Element] = []
|
||||
var isReversed: Bool
|
||||
|
||||
private enum Element {
|
||||
case orderingTerms((Database) throws -> [SQLOrderingTerm])
|
||||
case queryOrdering(QueryOrdering)
|
||||
|
||||
var reversed: Element {
|
||||
switch self {
|
||||
case .orderingTerms(let orderings):
|
||||
return .orderingTerms { db in try orderings(db).map { $0.reversed } }
|
||||
case .queryOrdering(let queryOrdering):
|
||||
return .queryOrdering(queryOrdering.reversed)
|
||||
}
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .orderingTerms(let orderings):
|
||||
return .orderingTerms { db in try orderings(db).map { $0.qualifiedOrdering(with: alias) } }
|
||||
case .queryOrdering(let queryOrdering):
|
||||
return .queryOrdering(queryOrdering.qualified(with: alias))
|
||||
}
|
||||
}
|
||||
|
||||
func resolve(_ db: Database) throws -> [SQLOrderingTerm] {
|
||||
switch self {
|
||||
case .orderingTerms(let orderings):
|
||||
return try orderings(db)
|
||||
case .queryOrdering(let queryOrdering):
|
||||
return try queryOrdering.resolve(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private init(elements: [Element], isReversed: Bool) {
|
||||
self.elements = elements
|
||||
self.isReversed = isReversed
|
||||
}
|
||||
|
||||
init() {
|
||||
self.init(
|
||||
elements: [],
|
||||
isReversed: false)
|
||||
}
|
||||
|
||||
init(orderings: @escaping (Database) throws -> [SQLOrderingTerm]) {
|
||||
self.init(
|
||||
elements: [.orderingTerms(orderings)],
|
||||
isReversed: false)
|
||||
}
|
||||
|
||||
var reversed: QueryOrdering {
|
||||
return QueryOrdering(
|
||||
elements: elements,
|
||||
isReversed: !isReversed)
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> QueryOrdering {
|
||||
return QueryOrdering(
|
||||
elements: elements.map { $0.qualified(with: alias) },
|
||||
isReversed: isReversed)
|
||||
}
|
||||
|
||||
func appending(_ ordering: QueryOrdering) -> QueryOrdering {
|
||||
return QueryOrdering(
|
||||
elements: elements + [.queryOrdering(ordering)],
|
||||
isReversed: isReversed)
|
||||
}
|
||||
|
||||
func resolve(_ db: Database) throws -> [SQLOrderingTerm] {
|
||||
if isReversed {
|
||||
return try elements.flatMap { try $0.reversed.resolve(db) }
|
||||
} else {
|
||||
return try elements.flatMap { try $0.resolve(db) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
// MARK: - SelectionRequest
|
||||
|
||||
/// The protocol for all requests that can refine their selection.
|
||||
public protocol SelectionRequest {
|
||||
/// Creates a request with a new set of selected columns.
|
||||
///
|
||||
/// // SELECT id, email FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.select([Column("id"), Column("email")])
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM player
|
||||
/// request
|
||||
/// .select([Column("id")])
|
||||
/// .select([Column("email")])
|
||||
func select(_ selection: [SQLSelectable]) -> Self
|
||||
}
|
||||
|
||||
extension SelectionRequest {
|
||||
/// Creates a request with a new set of selected columns.
|
||||
///
|
||||
/// // SELECT id, email FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.select(Column("id"), Column("email"))
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM player
|
||||
/// request
|
||||
/// .select(Column("id"))
|
||||
/// .select(Column("email"))
|
||||
public func select(_ selection: SQLSelectable...) -> Self {
|
||||
return select(selection)
|
||||
}
|
||||
|
||||
/// Creates a request with a new set of selected columns.
|
||||
///
|
||||
/// // SELECT id, email FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.select(sql: "id, email")
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM player
|
||||
/// request
|
||||
/// .select(sql: "id")
|
||||
/// .select(sql: "email")
|
||||
public func select(sql: String, arguments: StatementArguments? = nil) -> Self {
|
||||
return select(SQLSelectionLiteral(sql, arguments: arguments))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - FilteredRequest
|
||||
|
||||
/// The protocol for all requests that can be filtered.
|
||||
public protocol FilteredRequest {
|
||||
/// Creates a request with the provided *predicate promise* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM player WHERE 1
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter { db in true }
|
||||
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self
|
||||
}
|
||||
|
||||
extension FilteredRequest {
|
||||
/// Creates a request with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(Column("email") == "arthur@example.com")
|
||||
public func filter(_ predicate: SQLExpressible) -> Self {
|
||||
return filter { _ in predicate }
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"])
|
||||
public func filter(sql: String, arguments: StatementArguments? = nil) -> Self {
|
||||
return filter(SQLExpressionLiteral(sql, arguments: arguments))
|
||||
}
|
||||
|
||||
/// Creates a request that matches nothing.
|
||||
///
|
||||
/// // SELECT * FROM player WHERE 0
|
||||
/// var request = Player.all()
|
||||
/// request = request.none()
|
||||
public func none() -> Self {
|
||||
return filter(false)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TableRequest {
|
||||
|
||||
/// The protocol for all requests that feed from a database table
|
||||
public protocol TableRequest {
|
||||
/// The name of the database table
|
||||
var databaseTableName: String { get }
|
||||
|
||||
/// Creates a request that allows you to define expressions that target
|
||||
/// a specific database table.
|
||||
///
|
||||
/// In the example below, the "team.avgScore < player.score" condition in
|
||||
/// the ON clause could be not achieved without table aliases.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // JOIN team ON ... AND team.avgScore < player.score
|
||||
/// let playerAlias = TableAlias()
|
||||
/// let request = Player
|
||||
/// .all()
|
||||
/// .aliased(playerAlias)
|
||||
/// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
|
||||
func aliased(_ alias: TableAlias) -> Self
|
||||
}
|
||||
|
||||
extension TableRequest where Self: FilteredRequest {
|
||||
|
||||
/// Creates a request with the provided primary key *predicate*.
|
||||
public func filter<PrimaryKeyType: DatabaseValueConvertible>(key: PrimaryKeyType?) -> Self {
|
||||
guard let key = key else {
|
||||
return none()
|
||||
}
|
||||
return filter(keys: [key])
|
||||
}
|
||||
|
||||
/// Creates a request with the provided primary key *predicate*.
|
||||
public func filter<Sequence: Swift.Sequence>(keys: Sequence) -> Self where Sequence.Element: DatabaseValueConvertible {
|
||||
let keys = Array(keys)
|
||||
let makePredicate: (Column) -> SQLExpression
|
||||
switch keys.count {
|
||||
case 0:
|
||||
return none()
|
||||
case 1:
|
||||
makePredicate = { $0 == keys[0] }
|
||||
default:
|
||||
makePredicate = { keys.contains($0) }
|
||||
}
|
||||
|
||||
let databaseTableName = self.databaseTableName
|
||||
return filter { db in
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
|
||||
return makePredicate(Column(primaryKey.columns[0]))
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a request with the provided primary key *predicate*.
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
public func filter(key: [String: DatabaseValueConvertible?]?) -> Self {
|
||||
guard let key = key else {
|
||||
return none()
|
||||
}
|
||||
return filter(keys: [key])
|
||||
}
|
||||
|
||||
/// Creates a request with the provided primary key *predicate*.
|
||||
///
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
public func filter(keys: [[String: DatabaseValueConvertible?]]) -> Self {
|
||||
guard !keys.isEmpty else {
|
||||
return none()
|
||||
}
|
||||
|
||||
let databaseTableName = self.databaseTableName
|
||||
return filter { db in
|
||||
try keys
|
||||
.map { key in
|
||||
// Prevent filter(keys: [["foo": 1, "bar": 2]]) where
|
||||
// ("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: ", "))")
|
||||
}
|
||||
|
||||
let lowercaseColumns = columns.map { $0.lowercased() }
|
||||
return key
|
||||
// Preserve ordering of columns in the unique index
|
||||
.sorted { (kv1, kv2) in
|
||||
let index1 = lowercaseColumns.index(of: kv1.key.lowercased())!
|
||||
let index2 = lowercaseColumns.index(of: kv2.key.lowercased())!
|
||||
return index1 < index2
|
||||
}
|
||||
.map { (column, value) in Column(column) == value }
|
||||
.joined(operator: .and)
|
||||
}
|
||||
.joined(operator: .or)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension TableRequest where Self: OrderedRequest {
|
||||
/// Creates a request ordered by primary key.
|
||||
public func orderByPrimaryKey() -> Self {
|
||||
let tableName = self.databaseTableName
|
||||
return order { db in
|
||||
try db.primaryKey(tableName).columns.map { Column($0) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AggregatingRequest
|
||||
|
||||
/// The protocol for all requests that can aggregate.
|
||||
public protocol AggregatingRequest {
|
||||
/// Creates a request grouped according to *expressions*.
|
||||
func group(_ expressions: [SQLExpressible]) -> Self
|
||||
|
||||
/// Creates a request with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
func having(_ predicate: SQLExpressible) -> Self
|
||||
}
|
||||
|
||||
extension AggregatingRequest {
|
||||
/// Creates a request grouped according to *expressions*.
|
||||
public func group(_ expressions: SQLExpressible...) -> Self {
|
||||
return group(expressions)
|
||||
}
|
||||
|
||||
/// Creates a request with a new grouping.
|
||||
public func group(sql: String, arguments: StatementArguments? = nil) -> Self {
|
||||
// This "expression" is not a real expression. We support raw sql which
|
||||
// actually contains several expressions:
|
||||
//
|
||||
// request = Player.group(sql: "teamId, level")
|
||||
//
|
||||
// This is why we use the "unsafe" flag, so that the SQLExpressionLiteral
|
||||
// does not output its safe wrapping parenthesis, and generates
|
||||
// invalid SQL.
|
||||
var expression = SQLExpressionLiteral(sql, arguments: arguments)
|
||||
expression.unsafeRaw = true
|
||||
return group(expression)
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *sql* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
public func having(sql: String, arguments: StatementArguments? = nil) -> Self {
|
||||
return having(SQLExpressionLiteral(sql, arguments: arguments))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - OrderedRequest
|
||||
|
||||
/// The protocol for all requests that be ordered.
|
||||
public protocol OrderedRequest {
|
||||
/// Creates a request with the provided *orderings promise*.
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order { _ in [Column("name")] }
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// request
|
||||
/// .order{ _ in [Column("email")] }
|
||||
/// .reversed()
|
||||
/// .order{ _ in [Column("name")] }
|
||||
func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self
|
||||
|
||||
/// Creates a request that reverses applied orderings.
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name DESC
|
||||
/// var request = Player.all().order(Column("name"))
|
||||
/// request = request.reversed()
|
||||
///
|
||||
/// If no ordering was applied, the returned request is identical.
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.reversed()
|
||||
func reversed() -> Self
|
||||
}
|
||||
|
||||
extension OrderedRequest {
|
||||
/// Creates a request with the provided *orderings*.
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order(Column("name"))
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// request
|
||||
/// .order(Column("email"))
|
||||
/// .reversed()
|
||||
/// .order(Column("name"))
|
||||
public func order(_ orderings: SQLOrderingTerm...) -> Self {
|
||||
return order { _ in orderings }
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *orderings*.
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order(Column("name"))
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// request
|
||||
/// .order(Column("email"))
|
||||
/// .reversed()
|
||||
/// .order(Column("name"))
|
||||
public func order(_ orderings: [SQLOrderingTerm]) -> Self {
|
||||
return order { _ in orderings }
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *sql* used for sorting.
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order(sql: "name")
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
/// request
|
||||
/// .order(sql: "email")
|
||||
/// .order(sql: "name")
|
||||
public func order(sql: String, arguments: StatementArguments? = nil) -> Self {
|
||||
// This "expression" is not a real expression. We support raw sql which
|
||||
// actually contains several expressions:
|
||||
//
|
||||
// request = Player.order(sql: "teamId, level")
|
||||
//
|
||||
// This is why we use the "unsafe" flag, so that the SQLExpressionLiteral
|
||||
// does not output its safe wrapping parenthesis, and generates
|
||||
// invalid SQL.
|
||||
var expression = SQLExpressionLiteral(sql, arguments: arguments)
|
||||
expression.unsafeRaw = true
|
||||
return order([expression])
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DerivableRequest
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The base protocol for all requests that can be refined.
|
||||
public protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest {
|
||||
associatedtype RowDecoder
|
||||
}
|
||||
@@ -5,8 +5,8 @@
|
||||
///
|
||||
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
|
||||
///
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com' COLLATE NOCASE
|
||||
/// Players.filter(email == "arthur@example.com")
|
||||
/// // SELECT * FROM player WHERE email = 'arthur@example.com' COLLATE NOCASE
|
||||
/// Player.filter(email == "arthur@example.com")
|
||||
public struct SQLCollatedExpression {
|
||||
/// The tainted expression
|
||||
public let expression: SQLExpression
|
||||
@@ -18,8 +18,8 @@ public struct SQLCollatedExpression {
|
||||
///
|
||||
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
|
||||
///
|
||||
/// // SELECT * FROM players ORDER BY email COLLATE NOCASE ASC
|
||||
/// Players.order(email.asc)
|
||||
/// // SELECT * FROM player ORDER BY email COLLATE NOCASE ASC
|
||||
/// Player.order(email.asc)
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var asc: SQLOrderingTerm {
|
||||
@@ -30,8 +30,8 @@ public struct SQLCollatedExpression {
|
||||
///
|
||||
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
|
||||
///
|
||||
/// // SELECT * FROM players ORDER BY email COLLATE NOCASE DESC
|
||||
/// Players.order(email.desc)
|
||||
/// // SELECT * FROM player ORDER BY email COLLATE NOCASE DESC
|
||||
/// Player.order(email.desc)
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var desc: SQLOrderingTerm {
|
||||
@@ -51,16 +51,20 @@ public struct SQLCollatedExpression {
|
||||
extension SQLCollatedExpression : SQLOrderingTerm {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public var reversed: SQLOrderingTerm {
|
||||
return desc
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// :nodoc:
|
||||
public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return sqlExpression.orderingTermSQL(&arguments)
|
||||
public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
return sqlExpression.orderingTermSQL(&context)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
|
||||
return SQLCollatedExpression(expression.qualifiedExpression(with: alias), collationName: collationName)
|
||||
}
|
||||
}
|
||||