mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cafbecd8af | ||
|
|
78c36612b7 | ||
|
|
a95385c740 | ||
|
|
a58ebf7c48 | ||
|
|
13623575ff | ||
|
|
87c5f913b8 | ||
|
|
41172d7967 | ||
|
|
820bc87cfe | ||
|
|
2901acfb41 | ||
|
|
681460a415 | ||
|
|
19b067405f | ||
|
|
3b494b5737 | ||
|
|
5f11a19296 | ||
|
|
3ff7675eb7 | ||
|
|
3d06841eba | ||
|
|
188c026c6b | ||
|
|
caf051f19d | ||
|
|
c4a3d934a9 | ||
|
|
b19424aa23 | ||
|
|
bc229fa6fd | ||
|
|
9beb5b553b | ||
|
|
667e6a8e06 | ||
|
|
8f9b667c29 | ||
|
|
a8e0c76a30 | ||
|
|
49609ff08e | ||
|
|
efe201e032 | ||
|
|
28c903f7ea | ||
|
|
a5b45031d2 | ||
|
|
42e178b41d | ||
|
|
c3fe2c13f4 | ||
|
|
af8a6872d9 | ||
|
|
f40a5e68ea | ||
|
|
c4ad98426c | ||
|
|
a0e3d4ad69 | ||
|
|
d64bfe1cec | ||
|
|
8a213af2ab | ||
|
|
f02659e5d7 | ||
|
|
bdf943c3d9 | ||
|
|
9f1d5bc631 | ||
|
|
f2b46679a6 | ||
|
|
c5f38af247 | ||
|
|
2bfef4f02d | ||
|
|
07ae50cbb0 | ||
|
|
7f10bf4005 | ||
|
|
9130fe7b38 | ||
|
|
340dcd1748 | ||
|
|
8919bb5810 | ||
|
|
bea98db813 | ||
|
|
05a0130c1e | ||
|
|
e486437865 | ||
|
|
1043516fb7 | ||
|
|
c9b8b81ffb | ||
|
|
99b143a55c | ||
|
|
8401f42f3e | ||
|
|
f69949edea | ||
|
|
62e33f294e | ||
|
|
2a8e48ba63 | ||
|
|
6372bf663f | ||
|
|
ac7cc09bfe | ||
|
|
c9f0d473cf | ||
|
|
8a7ffdbb67 | ||
|
|
d30baaf16c | ||
|
|
1981adeb22 | ||
|
|
8427b8b668 | ||
|
|
6db590a31b | ||
|
|
22faa03a48 | ||
|
|
d3cd0ae85a | ||
|
|
b624955bf3 | ||
|
|
1b20cd14d1 | ||
|
|
baf2f780c9 | ||
|
|
9d1997b6cd | ||
|
|
313baa0064 | ||
|
|
006eee9f51 | ||
|
|
2720caf945 | ||
|
|
62faa57bf0 | ||
|
|
abbdb995e6 | ||
|
|
fd2ae60a65 | ||
|
|
2c4cf2d06b | ||
|
|
0f5ec15d47 | ||
|
|
1c3dfb346f | ||
|
|
b76013d60b | ||
|
|
e3ed95571c | ||
|
|
c749893858 | ||
|
|
9135be3da6 | ||
|
|
9930fd3938 | ||
|
|
c62c3df00d | ||
|
|
0419d67533 | ||
|
|
32d69c5be0 | ||
|
|
c2fb23c69c | ||
|
|
47611e14f7 | ||
|
|
b90f876b5b | ||
|
|
9037d51bc7 | ||
|
|
fb8c68f5e0 | ||
|
|
4995b5bb8c | ||
|
|
c87ebfd4eb | ||
|
|
b9d0dae5ac | ||
|
|
ab2a74285d | ||
|
|
e37ab72182 | ||
|
|
891dec64a0 | ||
|
|
90086789c6 | ||
|
|
2cdcdb9cd6 | ||
|
|
9c6879bd97 | ||
|
|
fc88acc782 | ||
|
|
1578dfe26b | ||
|
|
eb5e5a7069 | ||
|
|
b58cfefa13 | ||
|
|
de4d395aea | ||
|
|
7072bd9f36 | ||
|
|
8e36bc64fd | ||
|
|
4326a705f3 | ||
|
|
eb99e294ed | ||
|
|
27acb2b967 | ||
|
|
9cf5124a52 | ||
|
|
d00282f077 | ||
|
|
2556bedcda | ||
|
|
a569acd12a | ||
|
|
5e6c462708 | ||
|
|
4e0900dffa | ||
|
|
5c61211522 | ||
|
|
0747dc5cf6 | ||
|
|
85099c8ad6 | ||
|
|
72da91a8c7 | ||
|
|
4aced858a8 | ||
|
|
786ab176c9 | ||
|
|
973af107da | ||
|
|
1911ef0172 | ||
|
|
d2e9b340c9 | ||
|
|
5b487d1722 | ||
|
|
a91da59448 | ||
|
|
2846254304 | ||
|
|
5fe765dd29 | ||
|
|
9815f44134 | ||
|
|
3f8969b88f | ||
|
|
4fc7a44a9d | ||
|
|
e132688e00 | ||
|
|
588df57840 | ||
|
|
4a8ca6fdc1 | ||
|
|
2bb2493731 | ||
|
|
c61949ceaf | ||
|
|
3fce1e00c9 | ||
|
|
2f2add1c49 | ||
|
|
697acb103f | ||
|
|
c830e43e8f | ||
|
|
834ef45ca6 | ||
|
|
279faa13e9 | ||
|
|
0309abca6f | ||
|
|
fedee67bda | ||
|
|
a6c3566aa5 | ||
|
|
52fa24e1c4 | ||
|
|
a7ecf41e3b | ||
|
|
e68e5f6265 | ||
|
|
aad5a9b060 | ||
|
|
aa064029ec | ||
|
|
e84060e01c | ||
|
|
f4f72ebb43 | ||
|
|
da51e81e38 | ||
|
|
247cbdd0d0 | ||
|
|
c528740154 | ||
|
|
37b357b050 | ||
|
|
18c376979d | ||
|
|
9cc4357a70 | ||
|
|
f2d35a052f | ||
|
|
221f378d10 | ||
|
|
06a8c8b940 | ||
|
|
eee80b421a | ||
|
|
f6e22c3636 | ||
|
|
20d77fbba5 | ||
|
|
0393ebe012 | ||
|
|
2beddcf77b | ||
|
|
e784ebbcdd | ||
|
|
30ee538dbd | ||
|
|
7939ba6e05 | ||
|
|
2785e69fc1 | ||
|
|
d472c1696d | ||
|
|
d9cfa71fc7 | ||
|
|
715e12912b | ||
|
|
b182fe27f6 | ||
|
|
5594b33933 | ||
|
|
059b8800f6 | ||
|
|
9f687b1848 | ||
|
|
a4a05b1f0a | ||
|
|
1a7b0b0626 | ||
|
|
4c467e46cf | ||
|
|
fa71edeb07 | ||
|
|
4ff436371d | ||
|
|
9d8fa0bc5a | ||
|
|
1a8ecd7889 | ||
|
|
f6614fdfda | ||
|
|
a6055df756 | ||
|
|
5af91c5eab | ||
|
|
41974c4a46 | ||
|
|
f001b5bd76 | ||
|
|
28cf457853 | ||
|
|
8ccc23333d | ||
|
|
d95954d980 | ||
|
|
3506881c2a | ||
|
|
51d127c378 | ||
|
|
2d5dd7ef63 | ||
|
|
ef23ba55a1 | ||
|
|
ffdbf2f3f1 | ||
|
|
56cad83f55 | ||
|
|
719f33f7a7 | ||
|
|
700ffacdb1 | ||
|
|
a6ef4ed55c | ||
|
|
c5da564fb3 | ||
|
|
a6b04ebb64 | ||
|
|
99ba6db257 | ||
|
|
a3cddb72b9 | ||
|
|
2a9e896095 | ||
|
|
89d522d325 | ||
|
|
3c4ff587ca | ||
|
|
e111529035 | ||
|
|
cae1f97032 | ||
|
|
20419834a6 | ||
|
|
5dabc2a20b | ||
|
|
c700f5fc68 | ||
|
|
0b71cf86f2 | ||
|
|
96159bd09c | ||
|
|
bcff802ccb | ||
|
|
376d295853 | ||
|
|
0030ad1804 | ||
|
|
4ec3e0f7d8 | ||
|
|
e36219e408 | ||
|
|
8f8f53a697 | ||
|
|
567292c72f | ||
|
|
b744f73a76 | ||
|
|
da440a5e16 | ||
|
|
017af1d5c3 | ||
|
|
1f5d75d8e9 | ||
|
|
8b80abc701 | ||
|
|
dc75ca4caf | ||
|
|
d7d4c0a54d | ||
|
|
823b094b60 | ||
|
|
06a6c982aa | ||
|
|
1d15ef01f9 | ||
|
|
f72ffcbb43 | ||
|
|
e0f2305cd9 | ||
|
|
210939d2c1 | ||
|
|
2fd071d90e | ||
|
|
badec62cdd | ||
|
|
895cda4de7 | ||
|
|
21fdc9f350 | ||
|
|
398c0ef687 | ||
|
|
3b0a9aef3c | ||
|
|
48ec0916bf | ||
|
|
10af87a7d0 | ||
|
|
96e7996f37 | ||
|
|
0f7af931a9 | ||
|
|
cfd2d80b78 | ||
|
|
0386c01aa9 | ||
|
|
2c39c91ac6 | ||
|
|
0eb51e3e8b | ||
|
|
bb931e9da7 | ||
|
|
7b2e672496 | ||
|
|
cdc6370ee5 | ||
|
|
cc762e4e1d | ||
|
|
ed525bd1d8 | ||
|
|
2b2e92c810 | ||
|
|
44d31ead76 | ||
|
|
ec163e94eb | ||
|
|
ec2ac33fec | ||
|
|
20bda2af26 | ||
|
|
7a49f6293d | ||
|
|
81b21010f1 | ||
|
|
2526e0a2f7 | ||
|
|
af1e8470c9 | ||
|
|
dfd9da68a7 | ||
|
|
5e702234f4 | ||
|
|
9020dcca9a | ||
|
|
930a4e4c1d | ||
|
|
4db77f96b7 | ||
|
|
cc12c046b9 | ||
|
|
f5c63e0997 | ||
|
|
29a26800b7 | ||
|
|
bc5eeb3b3a | ||
|
|
40d02518b0 | ||
|
|
a2556edc69 | ||
|
|
111970fda9 | ||
|
|
ebeb7bc969 | ||
|
|
6ccac5f69c | ||
|
|
cc41b8b259 | ||
|
|
db1a3456b7 | ||
|
|
1b9305c073 | ||
|
|
a33814ef40 | ||
|
|
581bc9f27c | ||
|
|
40cff0053f | ||
|
|
cc33b12b0d | ||
|
|
2add1c68ea | ||
|
|
380b6676a6 | ||
|
|
f133a36477 | ||
|
|
5f2d6f8e2f |
No files matched your search
+1
-1
@@ -106,7 +106,7 @@ Pods
|
||||
|
||||
# SPM
|
||||
.build
|
||||
Package.pins
|
||||
Package.resolved
|
||||
Tests/SPM/Packages
|
||||
|
||||
# Ruby
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
3.1
|
||||
4.0
|
||||
+50
-44
@@ -1,3 +1,6 @@
|
||||
# The OS X Build Environment
|
||||
# https://docs.travis-ci.com/user/reference/osx/#Xcode-version
|
||||
|
||||
language: objective-c
|
||||
xcode_project: GRDB.xcodeproj
|
||||
|
||||
@@ -12,98 +15,98 @@ jobs:
|
||||
###########################################
|
||||
## Test GRDB
|
||||
|
||||
# Test GRDBOSX (Xcode 8.3)
|
||||
# Test GRDBOSX (Xcode 9.1)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=GRDBOSX (Xcode 8.3, macOS 10.12)
|
||||
- TID=GRDBOSX (Xcode 9.1, macOS)
|
||||
script: make test_framework_GRDBOSX
|
||||
|
||||
# Test GRDBWatchOS (Xcode 8.3)
|
||||
# Test GRDBWatchOS (Xcode 9.1)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=GRDBWatchOS (Xcode 8.3, watchOS)
|
||||
- TID=GRDBWatchOS (Xcode 9.1, watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
# Test GRDBiOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
|
||||
# Test GRDBiOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 8.3, iOS <MAX>)
|
||||
- TID=GRDBiOS (Xcode 9.1, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget
|
||||
|
||||
# Test GRDBiOS (Xcode 8.3, iOS <MINIMUM VERSION>))
|
||||
# Test GRDBiOS (Xcode 9.1, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=GRDBiOS (Xcode 8.3, iOS <MIN>)
|
||||
- TID=GRDBiOS (Xcode 9.1, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
# Test GRDB [SPM] (Xcode 8.3, macOS 10.12)
|
||||
# Test GRDB [SPM] (Xcode 9.1, macOS)
|
||||
- stage: Test GRDB
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=GRDB [SPM] (Xcode 8.3, macOS 10.12)
|
||||
- TID=GRDB [SPM] (Xcode 9.1, macOS)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDB (Custom SQLite)
|
||||
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 8.3)
|
||||
# Test GRDBCustomSQLiteOSX (Xcode 9.1)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 8.3, macOS 10.12)
|
||||
- TID=GRDBCustomSQLiteOSX (Xcode 9.1, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MAX>)
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
|
||||
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MINIMUM VERSION>))
|
||||
# Test GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + Custom SQLite
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 8.3, iOS <MIN>)
|
||||
- TID=GRDBCustomSQLiteiOS (Xcode 9.1, iOS <MIN>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB (SQLCipher)
|
||||
|
||||
# Test GRDBCipherOSX (Xcode 8.3)
|
||||
# Test GRDBCipherOSX (Xcode 9.1)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=GRDBCipherOSX (Xcode 8.3, macOS 10.12)
|
||||
- TID=GRDBCipherOSX (Xcode 9.1, macOS)
|
||||
script: make test_framework_GRDBCipherOSX
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 8.3, iOS <MAXIMUM VERSION>)
|
||||
# Test GRDBCipheriOS (Xcode 9.1, iOS <MAXIMUM VERSION>)
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 8.3, iOS <MAX>)
|
||||
- TID=GRDBCipheriOS (Xcode 9.1, iOS <MAX>)
|
||||
script: make test_framework_GRDBCipheriOS_maxTarget
|
||||
|
||||
# Test GRDBCipheriOS (Xcode 8.3, iOS <MINIMUM VERSION>))
|
||||
# Test GRDBCipheriOS (Xcode 9.1, iOS <MINIMUM VERSION>))
|
||||
- stage: Test GRDB + SQLCipher
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=GRDBCipheriOS (Xcode 8.3, iOS <MIN>)
|
||||
- TID=GRDBCipheriOS (Xcode 9.1, iOS <MIN>)
|
||||
script: make test_framework_GRDBCipheriOS_minTarget
|
||||
|
||||
###########################################
|
||||
@@ -112,7 +115,7 @@ jobs:
|
||||
# Manual Install
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=Manual Install
|
||||
script: make test_install_manual
|
||||
@@ -120,14 +123,14 @@ jobs:
|
||||
# Manual Install (GRDBCipher)
|
||||
- stage: Test Installation
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=Manual Install (GRDBCipher)
|
||||
script: make test_install_GRDBCipher
|
||||
|
||||
# Cocoapods Lint
|
||||
- stage: Test Installation
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
install:
|
||||
- gem install cocoapods # Since Travis is not always on latest version
|
||||
env:
|
||||
@@ -136,16 +139,19 @@ jobs:
|
||||
|
||||
# SPM Install
|
||||
- stage: Test Installation
|
||||
osx_image: xcode8.3
|
||||
osx_image: xcode9.1
|
||||
env:
|
||||
- TID=SPM
|
||||
script: make test_install_SPM
|
||||
|
||||
## The following doesn’t work, as `make test_CarthageBuild` does not yet work.
|
||||
## Carthage Build
|
||||
#- stage: Carthage
|
||||
# osx_image: xcode8.3
|
||||
# before_install:
|
||||
# - brew update
|
||||
# - brew outdated carthage || brew upgrade carthage
|
||||
# script: make test_CarthageBuild
|
||||
## Commented out until `make test_CarthageBuild` performs *reliably*.
|
||||
## See https://github.com/groue/GRDB.swift/pull/262
|
||||
# - stage: Test Installation
|
||||
# osx_image: xcode9.1
|
||||
# before_install:
|
||||
# - brew update
|
||||
# - brew outdated carthage || brew upgrade carthage
|
||||
# env:
|
||||
# - TID=Carthages
|
||||
# script: make test_CarthageBuild
|
||||
+608
-3
@@ -1,9 +1,614 @@
|
||||
Release Notes
|
||||
=============
|
||||
|
||||
## 2.3.1
|
||||
|
||||
Released November 8, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.3.0...v2.3.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- GRDB 2.2.0 has introduced a fix in the way [transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) are notified of empty deferred transactions (`BEGIN; COMMIT;`). That fix was incomplete, and inconsistent.
|
||||
|
||||
Now all transactions are notified, without any exception, including:
|
||||
|
||||
```swift
|
||||
try db.execute("BEGIN; COMMIT;")
|
||||
try db.execute("SAVEPOINT foo; RELEASE SAVEPOINT foo;")
|
||||
```
|
||||
|
||||
[Rationale](https://github.com/groue/GRDB.swift/commit/820bc87cfeee701743da852f3634e2c695e911ee#diff-3e791e9db648cd302590c9b86c70757fR376)
|
||||
|
||||
|
||||
## 2.3.0
|
||||
|
||||
Released November 5, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.2.0...v2.3.0)
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.21.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
|
||||
|
||||
## 2.2.0
|
||||
|
||||
Released October 31, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.1.0...v2.2.0)
|
||||
|
||||
**New**
|
||||
|
||||
- `Database.viewExists(_:)` returns whether a view exists in the database.
|
||||
- `Database.triggerExists(_:)` returns whether a trigger exists in the database.
|
||||
|
||||
**Fixed**
|
||||
|
||||
- `DROP VIEW` statements would not drop views ([#267](https://github.com/groue/GRDB.swift/issues/267))
|
||||
- GRDB used to incorrectly send incomplete transaction notifications to [transaction observers](https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol) in the case of empty deferred transactions. This is no longer the case. Since empty deferred transactions have SQLite consider that no transaction started at all, they are no longer notified to transaction observers:
|
||||
|
||||
```sql
|
||||
-- Nothing happens, and thus no notification is sent
|
||||
BEGIN TRANSACTION
|
||||
COMMIT
|
||||
```
|
||||
|
||||
Those empty deferred transactions still count for the [afterNextTransactionCommit](https://github.com/groue/GRDB.swift/blob/master/README.md#after-commit-hook) database method, and the `.nextTransaction` [observation extent](https://github.com/groue/GRDB.swift/blob/master/README.md#observation-extent).
|
||||
|
||||
|
||||
## 2.1.0
|
||||
|
||||
Released October 24, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.3...v2.1.0)
|
||||
|
||||
### New
|
||||
|
||||
- GRDBCipher can now build from command line ([groue/sqlcipher/pull/1](https://github.com/groue/sqlcipher/pull/1) by [Darren Clark](https://github.com/darrenclark))
|
||||
- Upgrade custom SQLite builds to [v3.20.1](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The new method `Request.asSQLRequest` allows to inspect the sql and arguments of any request:
|
||||
|
||||
```swift
|
||||
let request = Player.all()
|
||||
let sql = try request.asSQLRequest(db).sql
|
||||
print(sql) // Prints "SELECT * FROM players"
|
||||
```
|
||||
|
||||
- StatementArguments adopts Equatable
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
- `DROP TABLE` statements would not drop temporary tables.
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- New FAQ: [How do I create a database in my application?](https://github.com/groue/GRDB.swift/blob/master/README.md#how-do-i-create-a-database-in-my-application)
|
||||
- New FAQ: [How do I print a request as SQL?](https://github.com/groue/GRDB.swift/blob/master/README.md#how-do-i-print-a-request-as-sql)
|
||||
- The [Codable Record](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) chapter has been enhanced with more information and sample code.
|
||||
|
||||
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
extension Request {
|
||||
+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest
|
||||
}
|
||||
struct SQLRequest {
|
||||
+ let sql: String
|
||||
+ let arguments: StatementArguments?
|
||||
+ let adapter: RowAdapter?
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 2.0.3
|
||||
|
||||
Released October 9, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.2...v2.0.3)
|
||||
|
||||
**Fixed**: Record types that conform to Encodable now encode their null columns.
|
||||
|
||||
|
||||
## 2.0.2
|
||||
|
||||
Released October 5, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0.1...v2.0.2)
|
||||
|
||||
**Fixed**: `DROP TABLE` statements would not drop tables when run through a prepared statement.
|
||||
|
||||
|
||||
## 2.0.1
|
||||
|
||||
Released September 17, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v2.0...v2.0.1)
|
||||
|
||||
**Fixed**: restored support for Swift Package Manager
|
||||
|
||||
|
||||
## 2.0
|
||||
|
||||
Released September 16, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.3.0...v2.0)
|
||||
|
||||
**GRDB 2.0 brings support for Swift 4.** Notable changes are:
|
||||
|
||||
- **Use subscript notation when extracting row values** ([documentation](https://github.com/groue/GRDB.swift#column-values)):
|
||||
|
||||
```swift
|
||||
let name: String = row[0] // 0 is the leftmost column
|
||||
let name: String = row["name"] // Leftmost matching column - lookup is case-insensitive
|
||||
let name: String = row[Column("name")] // Using query interface's Column
|
||||
```
|
||||
|
||||
- **Support for the `Codable` protocol** ([documentation](https://github.com/groue/GRDB.swift#codable-records))
|
||||
|
||||
Record types that adopt the standard `Codable` protocol are granted with automatic adoption of GRDB record protocols. This means that you no longer have to write boilerplate code :tada::
|
||||
|
||||
```swift
|
||||
struct Player : RowConvertible, Persistable, Codable {
|
||||
static let databaseTableName = "players"
|
||||
let name: String
|
||||
let score: Int
|
||||
}
|
||||
|
||||
// Automatically derived:
|
||||
//
|
||||
// extension Player {
|
||||
// init(row: Row) {
|
||||
// name = row["name"]
|
||||
// score = row["score"]
|
||||
// }
|
||||
//
|
||||
// func encode(to container: inout PersistenceContainer) {
|
||||
// container["name"] = name
|
||||
// container["score"] = score
|
||||
// }
|
||||
// }
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
let arthur = Player(name: "Arthur", score: 100)
|
||||
try arthur.insert(db)
|
||||
let players = try Player.fetchAll(db) // [Players]
|
||||
}
|
||||
```
|
||||
|
||||
- **Records can now specify the columns they feed from** ([documentation](https://github.com/groue/GRDB.swift#columns-selected-by-a-request)).
|
||||
|
||||
In previous versions of GRDB, `SELECT *` was the norm. GRDB 2.0 introduces `databaseSelection`, which allows any type to define its preferred set of columns:
|
||||
|
||||
```swift
|
||||
struct Player : RowConvertible, TableMapping {
|
||||
let id: Int64
|
||||
let name: String
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
}
|
||||
|
||||
init(row: Row) {
|
||||
id = row[Columns.id]
|
||||
name = row[Columns.name]
|
||||
}
|
||||
|
||||
static let databaseTableName = "players"
|
||||
static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name]
|
||||
}
|
||||
|
||||
// SELECT id, name FROM players
|
||||
let players = Player.fetchAll(db)
|
||||
```
|
||||
|
||||
- **Record protocols have more precise semantics**: RowConvertible *reads database rows*, TableMapping *builds SQL requests*, and Persistable *writes* ([documentation](https://github.com/groue/GRDB.swift#record-protocols-overview)).
|
||||
|
||||
This means that with GRDB 2.0, being able to write `Player.fetchAll(db)` does not imply that `Player.deleteAll(db)` is available: you have a better control on the abilities of your record types.
|
||||
|
||||
|
||||
### Fixed
|
||||
|
||||
- GRDB is now able to store and load zero-length blobs.
|
||||
|
||||
|
||||
### New
|
||||
|
||||
New features have been added in order to plug a few holes and support the [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) and [GRDBObjc](http://github.com/groue/GRDBObjc) companion projects:
|
||||
|
||||
- Persistable records can export themselves as dictionaries:
|
||||
|
||||
```swift
|
||||
let player = try Player.fetchOne(db, key: 1)
|
||||
let dict = player.databaseDictionary // [String: DatabaseValue]
|
||||
print(dict)
|
||||
// Prints {"id": 1, "name": "Arthur", "score": 1000}
|
||||
```
|
||||
|
||||
- Query interface requests learned how to limit the number of deleted rows:
|
||||
|
||||
```swift
|
||||
// Delete the last ten players:
|
||||
// DELETE FROM players ORDER BY score LIMIT 10
|
||||
let request = Player.order(scoreColumn).limit(10)
|
||||
try request.deleteAll(db)
|
||||
```
|
||||
|
||||
- Prepared statements know the index of their columns:
|
||||
|
||||
```swift
|
||||
let statement = try db.makeSelectStatement("SELECT a, b FROM t")
|
||||
statement.index(ofColumn: "b") // 1
|
||||
```
|
||||
|
||||
- Row cursors (of type RowCursor) expose their underlying statement:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
let statement = rows.statement
|
||||
```
|
||||
|
||||
- One can build a Set from a cursor:
|
||||
|
||||
```swift
|
||||
let strings = try Set(String.fetchCursor(...))
|
||||
```
|
||||
|
||||
- The new `AnyDatabaseReader` and `AnyDatabaseWriter` type erasers help dealing with the `DatabaseReader` and `DatabaseWriter` protocols.
|
||||
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- Requirements have changed: Xcode 9+ / Swift 4
|
||||
|
||||
- WatchOS extension targets no longer need `libsqlite3.tbd` to be added to the *Linked Frameworks and Libraries* section of their *General* tab.
|
||||
|
||||
- The `Row.value` method has been replaced with subscript notation:
|
||||
|
||||
```diff
|
||||
-row.value(atIndex: 0)
|
||||
-row.value(named: "id")
|
||||
-row.value(Column("id"))
|
||||
+row[0]
|
||||
+row["id"]
|
||||
+row[Column("id")]
|
||||
```
|
||||
|
||||
- Date and NSDate now interpret numerical database values as timestamps that fuel `Date(timeIntervalSince1970:)`. Previous version of GRDB would interpret numbers as [julian days](https://en.wikipedia.org/wiki/Julian_day) (a date representation supported by SQLite). Support for julian days remains, with the `Date(julianDay:)` initializer.
|
||||
|
||||
- All `TableMapping` methods that would modify the database have moved to `MutablePersistable`, now the only record protocol that is able to write.
|
||||
|
||||
- The `TableMapping.selectsRowID` property has been replaced with `TableMapping.databaseSelection`.
|
||||
|
||||
To upgrade, replace:
|
||||
|
||||
```diff
|
||||
struct Player: TableMapping {
|
||||
- static let selectsRowID = true
|
||||
+ static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
}
|
||||
```
|
||||
|
||||
- The `DatabaseCursor` type has been removed, and replaced with several concrete types that all adopt the `Cursor` protocol. Those new types allow dedicated optimizations depending on the type of the fetched elements.
|
||||
|
||||
If your application has code that depends on `DatabaseCursor`, make it target the new concrete types, or make it generic on the `Cursor` protocol, just like you'd write generic methods on the Swift `Sequence` protocol.
|
||||
|
||||
- `RowConvertible.fetchCursor(_:keys:)` returns a non-optional cursor.
|
||||
|
||||
- `Database.primaryKey(_:)` returns a non-optional PrimaryKeyInfo. When a table has no explicit primary key, the result is the hidden rowid column.
|
||||
|
||||
- The deprecated `TableMapping.primaryKeyRowComparator` method has been removed.
|
||||
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- [WatchOS installation procedure](https://github.com/groue/GRDB.swift#installation) has been updated with new instructions.
|
||||
- The [introduction to multithreading with database pools](https://github.com/groue/GRDB.swift#database-pools) has been enhanced.
|
||||
- The [Rows as Dictionaries](https://github.com/groue/GRDB.swift#rows-as-dictionaries) chapter has been enhanced with instructions for converting a row into a dictionary.
|
||||
- The [description of cursors](https://github.com/groue/GRDB.swift#cursors) better explains how to choose between a cursor and an array.
|
||||
- The [Date and DateComponents](https://github.com/groue/GRDB.swift#date-and-datecomponents) chapter has been updated for the new support for unix timestamps.
|
||||
- The [Fatal Errors](https://github.com/groue/GRDB.swift#fatal-errors) chapter has an enhanced description of value conversion errors and how to handle them.
|
||||
- The [Usage of raw SQLite pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers) chapter has been updated for the new `SQLite3` standard module that comes with Swift4.
|
||||
- A new [Record Protocols Overview](https://github.com/groue/GRDB.swift#record-protocols-overview) chapter has been added.
|
||||
- A new [Codable Records](https://github.com/groue/GRDB.swift#codable-records) chapter has been added.
|
||||
- A new [Columns Selected by a Request](https://github.com/groue/GRDB.swift#columns-selected-by-a-request) chapter describes the new `TableMapping.databaseSelection` property.
|
||||
- The [Exposing the RowID Column](https://github.com/groue/GRDB.swift#exposing-the-rowid-column) chapter has been updated for the new `TableMapping.databaseSelection` property.
|
||||
|
||||
|
||||
### API diff
|
||||
|
||||
```diff
|
||||
class Row {
|
||||
- func value(atIndex index: Int) -> DatabaseValueConvertible?
|
||||
- func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value?
|
||||
- func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value
|
||||
- func value(named columnName: String) -> DatabaseValueConvertible?
|
||||
- func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value?
|
||||
- func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value
|
||||
- func value(_ column: Column) -> DatabaseValueConvertible?
|
||||
- func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value?
|
||||
- func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value
|
||||
+ subscript(_ index: Int) -> DatabaseValueConvertible?
|
||||
+ subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value?
|
||||
+ subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value
|
||||
+ subscript(_ columnName: String) -> DatabaseValueConvertible?
|
||||
+ subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value?
|
||||
+ subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value
|
||||
+ subscript(_ column: Column) -> DatabaseValueConvertible?
|
||||
+ subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value?
|
||||
+ subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value
|
||||
}
|
||||
|
||||
class SelectStatement {
|
||||
+ func index(ofColumn columnName: String) -> Int?
|
||||
}
|
||||
|
||||
+extension MutablePersistable {
|
||||
+ var databaseDictionary: [String: DatabaseValue]
|
||||
+}
|
||||
|
||||
-extension TableMapping {
|
||||
+extension MutablePersistable {
|
||||
@discardableResult static func deleteAll(_ db: Database) throws -> Int
|
||||
@discardableResult static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible
|
||||
@discardableResult static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool
|
||||
@discardableResult static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int
|
||||
@discardableResult static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool
|
||||
}
|
||||
-extension QueryInterfaceRequest {
|
||||
+extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
|
||||
@discardableResult func deleteAll(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
protocol TableMapping {
|
||||
- static var selectsRowID: Bool { get }
|
||||
+ static var databaseSelection: [SQLSelectable] { get }
|
||||
}
|
||||
class Record {
|
||||
- open class var selectsRowID: Bool
|
||||
+ open class var databaseSelection: [SQLSelectable]
|
||||
}
|
||||
+struct AllColumns {
|
||||
+ init()
|
||||
+}
|
||||
|
||||
class Database {
|
||||
- func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo?
|
||||
+ func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo
|
||||
}
|
||||
struct PrimaryKeyInfo {
|
||||
+ var isRowID: Bool { get }
|
||||
}
|
||||
|
||||
+extension Set {
|
||||
+ init<C: Cursor>(_ cursor: C) throws where C.Element == Element
|
||||
+}
|
||||
|
||||
-final class DatabaseCursor { }
|
||||
+final class ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
+ typealias Element = Value
|
||||
+}
|
||||
+final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
|
||||
+ typealias Element = Value
|
||||
+}
|
||||
+final class NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
+ typealias Element = Value?
|
||||
+}
|
||||
+final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
|
||||
+ typealias Element = Value?
|
||||
+}
|
||||
+final class RecordCursor<Record: RowConvertible> : Cursor {
|
||||
+ typealias Element = Record
|
||||
+}
|
||||
+final class RowCursor : Cursor {
|
||||
+ typealias Element = Row
|
||||
+ let statement: SelectStatement
|
||||
+}
|
||||
extension DatabaseValueConvertible {
|
||||
- static func fetchCursor(...) throws -> DatabaseCursor<Self>
|
||||
+ static func fetchCursor(...) throws -> DatabaseValueCursor<Self>
|
||||
}
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
+ static func fetchCursor(...) throws -> ColumnCursor<Self>
|
||||
}
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
- static func fetchCursor(...) throws -> DatabaseCursor<Wrapped?>
|
||||
+ static func fetchCursor(...) throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
}
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
+ static func fetchCursor(...) throws -> NullableColumnCursor<Wrapped>
|
||||
}
|
||||
extension Row {
|
||||
- static func fetchCursor(...) throws -> DatabaseCursor<Row>
|
||||
+ static func fetchCursor(...) throws -> RowCursor
|
||||
}
|
||||
extension RowConvertible where Self: TableMapping {
|
||||
- static func fetchCursor(...) throws -> DatabaseCursor<Self>?
|
||||
+ static func fetchCursor(...) throws -> RecordCursor<Self>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: RowConvertible {
|
||||
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
|
||||
+ func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
|
||||
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
|
||||
+ func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
+ func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
|
||||
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder._Wrapped?>
|
||||
+ func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
+ func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: Row {
|
||||
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<Row>
|
||||
+ func fetchCursor(_ db: Database) throws -> RowCursor
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
- @available(*, deprecated) static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
|
||||
}
|
||||
|
||||
+final class AnyDatabaseReader : DatabaseReader {
|
||||
+ init(_ base: DatabaseReader)
|
||||
+}
|
||||
+final class AnyDatabaseWriter : DatabaseWriter {
|
||||
+ init(_ base: DatabaseWriter)
|
||||
+}
|
||||
```
|
||||
|
||||
### Experimental API diff
|
||||
|
||||
```diff
|
||||
enum SQLCount {
|
||||
- case star
|
||||
+ case all
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 1.3.0
|
||||
|
||||
Released August 18, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.2.2...v1.3.0)
|
||||
|
||||
**New**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.20.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- Complete support for all signed and unsigned integer types: from Int8 toUInt64, all integers can be stored and loaded from the database.
|
||||
|
||||
**API diff**
|
||||
|
||||
```diff
|
||||
+extension Int8: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
+extension Int16: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
+extension UInt8: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
+extension UInt16: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
+extension UInt32: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
+extension UInt64: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
+extension UInt: DatabaseValueConvertible, StatementColumnConvertible { }
|
||||
```
|
||||
|
||||
|
||||
## 1.2.2
|
||||
|
||||
Released July 20, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.2.1...v1.2.2)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- The `Configuration.trace` function no longer leaks memory.
|
||||
|
||||
|
||||
## 1.2.1
|
||||
|
||||
Released July 19, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.2...v1.2.1)
|
||||
|
||||
**Fixed**
|
||||
|
||||
- Upgrade custom SQLite builds to [v3.19.3](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)).
|
||||
- The [Query Interface](https://github.com/groue/GRDB.swift/#the-query-interface) now generates `IS NULL` SQL snippets for comparisons with `DatabaseValue.null`:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM players WHERE email IS NULL
|
||||
Player.filter(Column("email") == DatabaseValue.null)
|
||||
```
|
||||
|
||||
It used to generate `= NULL` which would not behave as expected.
|
||||
|
||||
|
||||
## 1.2
|
||||
|
||||
Released July 13, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.1...v1.2)
|
||||
|
||||
**New**
|
||||
|
||||
- Record types that do not provide values for all table columns in their `encode(to:)` method are now supported.
|
||||
|
||||
- The table creation API has been enhanced:
|
||||
|
||||
- SQLite supports untyped columns:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
// CREATE TABLE t(a, b)
|
||||
try db.create(table: "t") { t in
|
||||
t.column("a")
|
||||
t.column("b")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Untyped columns behave like decimal, boolean, date columns, and generally all columns with [NUMERIC type affinity](https://sqlite.org/datatype3.html#type_affinity).
|
||||
|
||||
This feature addresses [#169](https://github.com/groue/GRDB.swift/issues/169).
|
||||
|
||||
- The `indexed()` methods lets you create a non-unique index on a table column:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
// CREATE TABLE rounds(score INTEGER)
|
||||
// CREATE INDEX rounds_on_score ON rounds(score)
|
||||
try db.create(table: "rounds") { t in
|
||||
t.column("score", .integer).indexed()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- It is now possible to define references to tables without any explicit primary key. The generated SQL then uses the `rowid` hidden primary key column:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
// CREATE TABLE nodes(
|
||||
// name TEXT,
|
||||
// parentId INTEGER REFERENCES nodes(rowid)
|
||||
// )
|
||||
try db.create(table: "nodes") { t in
|
||||
t.column("name", .text)
|
||||
t.column("parentId", .integer).references("nodes")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `DatabaseQueue`, `DatabasePool` and their common protocol `DatabaseReader` can now perform "unsafe reentrant reads" ([documentation](https://github.com/groue/GRDB.swift#unsafe-concurrency-apis)):
|
||||
|
||||
```swift
|
||||
try dbPool.read { db in
|
||||
// This is allowed
|
||||
try dbPool.unsafeReentrantRead { db in
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**Fixed**
|
||||
|
||||
- `DatabasePool.read`, and `DatabasePool.unsafeRead` now raise a fatal error when used in a reentrant way:
|
||||
|
||||
```swift
|
||||
try dbPool.read { db in
|
||||
// fatal error: "Database methods are not reentrant."
|
||||
try dbPool.read { db in
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
While this change may appear as a breaking change, it is really a fix: reentrant reads deadlock as soon as the maximum number of readers has been reached.
|
||||
|
||||
|
||||
**API diff**
|
||||
|
||||
```diff
|
||||
final class ColumnDefinition {
|
||||
+ @discardableResult func indexed() -> Self
|
||||
}
|
||||
|
||||
final class TableDefinition {
|
||||
- func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition
|
||||
+ func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition
|
||||
}
|
||||
|
||||
protocol DatabaseReader {
|
||||
+ func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 1.1
|
||||
|
||||
Released July 1, 2017
|
||||
Released July 1, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/v1.0...v1.1)
|
||||
|
||||
**New**
|
||||
|
||||
@@ -1011,7 +1616,7 @@ Released September 16, 2016
|
||||
|
||||
```diff
|
||||
-let dbValue = row.databaseValue(atIndex: 0)
|
||||
+let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
+let dbValue: DatabaseValue = row[0]
|
||||
```
|
||||
|
||||
|
||||
@@ -1367,7 +1972,7 @@ Released September 16, 2016
|
||||
|
||||
```diff
|
||||
-let dbValue = row.databaseValue(atIndex: 0)
|
||||
+let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
+let dbValue: DatabaseValue = row[0]
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -1,11 +1,3 @@
|
||||
//
|
||||
// ExtensionDelegate.swift
|
||||
// GRDBDemoWatchOS Extension
|
||||
//
|
||||
// Created by Gwendal Roué on 03/04/2017.
|
||||
// Copyright © 2017 Gwendal Roué. All rights reserved.
|
||||
//
|
||||
|
||||
import WatchKit
|
||||
|
||||
class ExtensionDelegate: NSObject, WKExtensionDelegate {
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
//
|
||||
// InterfaceController.swift
|
||||
// GRDBDemoWatchOS Extension
|
||||
//
|
||||
// Created by Gwendal Roué on 03/04/2017.
|
||||
// Copyright © 2017 Gwendal Roué. All rights reserved.
|
||||
//
|
||||
|
||||
import WatchKit
|
||||
import Foundation
|
||||
import GRDB
|
||||
import SQLite3
|
||||
|
||||
class InterfaceController: WKInterfaceController {
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
5657C36E1E926B05008402E8 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 5657C36D1E926B05008402E8 /* libsqlite3.tbd */; };
|
||||
568E5FC31E926430002582E0 /* Interface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC11E926430002582E0 /* Interface.storyboard */; };
|
||||
568E5FC51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC41E926430002582E0 /* Assets.xcassets */; };
|
||||
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
|
||||
@@ -21,7 +20,7 @@
|
||||
56B0360C1E8D9EBE003B6DA4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */; };
|
||||
56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; };
|
||||
56B036111E8D9EBE003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */; };
|
||||
56B0361B1E8D9F38003B6DA4 /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* Database.swift */; };
|
||||
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 */; };
|
||||
@@ -32,6 +31,13 @@
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56439B501F4CA1DC0066043F;
|
||||
remoteInfo = GRDBOSXPerformanceComparisonTests;
|
||||
};
|
||||
568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
|
||||
@@ -243,7 +249,6 @@
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
5657C36D1E926B05008402E8 /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = Platforms/WatchOS.platform/Developer/SDKs/WatchOS3.2.sdk/usr/lib/libsqlite3.tbd; sourceTree = DEVELOPER_DIR; };
|
||||
568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoWatchOS.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
568E5FC21E926430002582E0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Interface.storyboard; sourceTree = "<group>"; };
|
||||
568E5FC41E926430002582E0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
@@ -259,7 +264,7 @@
|
||||
56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
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 /* Database.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Database.swift; 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>"; };
|
||||
@@ -273,7 +278,6 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5657C36E1E926B05008402E8 /* libsqlite3.tbd in Frameworks */,
|
||||
568E5FE41E926547002582E0 /* GRDB.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -289,14 +293,6 @@
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
5657C36C1E926B05008402E8 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5657C36D1E926B05008402E8 /* libsqlite3.tbd */,
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -326,7 +322,6 @@
|
||||
568E5FC01E926430002582E0 /* GRDBDemoWatchOS */,
|
||||
568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */,
|
||||
56B036041E8D9EBE003B6DA4 /* Products */,
|
||||
5657C36C1E926B05008402E8 /* Frameworks */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
@@ -344,7 +339,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
|
||||
56B036191E8D9F38003B6DA4 /* Database.swift */,
|
||||
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
|
||||
56B0361A1E8D9F38003B6DA4 /* Person.swift */,
|
||||
56B0361D1E8D9F3D003B6DA4 /* Controllers */,
|
||||
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
|
||||
@@ -372,6 +367,7 @@
|
||||
56B0363B1E8D9F79003B6DA4 /* GRDB.framework */,
|
||||
56B0363D1E8D9F79003B6DA4 /* GRDBOSXTests.xctest */,
|
||||
56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */,
|
||||
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */,
|
||||
56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */,
|
||||
56B036431E8D9F79003B6DA4 /* GRDBCipher.framework */,
|
||||
56B036451E8D9F79003B6DA4 /* GRDBCipherOSXTests.xctest */,
|
||||
@@ -459,7 +455,7 @@
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 0830;
|
||||
LastUpgradeCheck = 0830;
|
||||
LastUpgradeCheck = 0900;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
568E5FBE1E926430002582E0 = {
|
||||
@@ -506,6 +502,13 @@
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXReferenceProxy section */
|
||||
563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXPerformanceComparisonTests.xctest;
|
||||
remoteRef = 563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B0363B1E8D9F79003B6DA4 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
@@ -672,7 +675,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */,
|
||||
56B0361B1E8D9F38003B6DA4 /* Database.swift in Sources */,
|
||||
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
|
||||
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
|
||||
56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */,
|
||||
56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */,
|
||||
@@ -755,7 +758,6 @@
|
||||
PRODUCT_NAME = "${TARGET_NAME}";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_VERSION = 3.0;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
@@ -772,7 +774,6 @@
|
||||
PRODUCT_NAME = "${TARGET_NAME}";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_VERSION = 3.0;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
@@ -790,7 +791,6 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_VERSION = 3.0;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
@@ -808,7 +808,6 @@
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
SWIFT_VERSION = 3.0;
|
||||
TARGETED_DEVICE_FAMILY = 4;
|
||||
WATCHOS_DEPLOYMENT_TARGET = 3.2;
|
||||
};
|
||||
@@ -824,7 +823,9 @@
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
@@ -832,7 +833,11 @@
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
@@ -855,12 +860,12 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 10.3;
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 4.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -874,7 +879,9 @@
|
||||
CLANG_CXX_LIBRARY = "libc++";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_ARC = YES;
|
||||
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
|
||||
CLANG_WARN_BOOL_CONVERSION = YES;
|
||||
CLANG_WARN_COMMA = YES;
|
||||
CLANG_WARN_CONSTANT_CONVERSION = YES;
|
||||
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
|
||||
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
|
||||
@@ -882,7 +889,11 @@
|
||||
CLANG_WARN_ENUM_CONVERSION = YES;
|
||||
CLANG_WARN_INFINITE_RECURSION = YES;
|
||||
CLANG_WARN_INT_CONVERSION = YES;
|
||||
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
|
||||
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
|
||||
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
|
||||
CLANG_WARN_STRICT_PROTOTYPES = YES;
|
||||
CLANG_WARN_SUSPICIOUS_MOVE = YES;
|
||||
CLANG_WARN_UNREACHABLE_CODE = YES;
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
@@ -899,10 +910,10 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 10.3;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = iphoneos;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
|
||||
SWIFT_VERSION = 4.0;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
};
|
||||
name = Release;
|
||||
@@ -917,7 +928,6 @@
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 3.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
@@ -931,7 +941,6 @@
|
||||
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 3.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import GRDB
|
||||
|
||||
/// A type responsible for initializing the application database.
|
||||
///
|
||||
/// See AppDelegate.setupDatabase()
|
||||
struct AppDatabase {
|
||||
|
||||
/// Creates a fully initialized database at path
|
||||
static func openDatabase(atPath path: String) throws -> DatabaseQueue {
|
||||
// Connect to the database
|
||||
// See https://github.com/groue/GRDB.swift/#database-connections
|
||||
dbQueue = try DatabaseQueue(path: path)
|
||||
|
||||
// Use DatabaseMigrator to define the database schema
|
||||
// See https://github.com/groue/GRDB.swift/#migrations
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
return dbQueue
|
||||
}
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// This migrator is exposed so that migrations can be tested.
|
||||
// See https://github.com/groue/GRDB.swift/#migrations
|
||||
static var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
try db.create(table: "persons") { 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
|
||||
// See https://github.com/groue/GRDB.swift/#unicode
|
||||
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
|
||||
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
migrator.registerMigration("fixtures") { db in
|
||||
// Populate the persons table with random data
|
||||
for _ in 0..<8 {
|
||||
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
// // Migrations for future application versions will be inserted here:
|
||||
// migrator.registerMigration(...) { db in
|
||||
// ...
|
||||
// }
|
||||
|
||||
return migrator
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
// The shared database queue
|
||||
var dbQueue: DatabaseQueue!
|
||||
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
@@ -8,4 +12,15 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
try! setupDatabase(application)
|
||||
return true
|
||||
}
|
||||
|
||||
private func setupDatabase(_ application: UIApplication) throws {
|
||||
let databaseURL = try FileManager.default
|
||||
.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,56 +0,0 @@
|
||||
import GRDB
|
||||
import UIKit
|
||||
|
||||
// The shared database queue
|
||||
var dbQueue: DatabaseQueue!
|
||||
|
||||
func setupDatabase(_ application: UIApplication) throws {
|
||||
|
||||
// Connect to the database
|
||||
// See https://github.com/groue/GRDB.swift/#database-connections
|
||||
|
||||
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
|
||||
let databasePath = documentsPath.appendingPathComponent("db.sqlite")
|
||||
dbQueue = try DatabaseQueue(path: databasePath)
|
||||
|
||||
|
||||
// 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)
|
||||
|
||||
|
||||
// Use DatabaseMigrator to setup the database
|
||||
// See https://github.com/groue/GRDB.swift/#migrations
|
||||
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createPersons") { db in
|
||||
|
||||
// Create a table
|
||||
// See https://github.com/groue/GRDB.swift#create-tables
|
||||
|
||||
try db.create(table: "persons") { 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
|
||||
// See https://github.com/groue/GRDB.swift/#unicode
|
||||
t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare)
|
||||
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
// Populate the persons table with random data
|
||||
for _ in 0..<8 {
|
||||
try Person(name: Person.randomName(), score: Person.randomScore()).insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
// // Migrations for future application versions will be inserted here:
|
||||
// migrator.registerMigration(...) { db in
|
||||
// ...
|
||||
// }
|
||||
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
@@ -18,9 +18,9 @@ class Person: Record {
|
||||
}
|
||||
|
||||
required init(row: Row) {
|
||||
id = row.value(named: "id")
|
||||
name = row.value(named: "name")
|
||||
score = row.value(named: "score")
|
||||
id = row["id"]
|
||||
name = row["name"]
|
||||
score = row["score"]
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
|
||||
@@ -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.19.2](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.21.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).
|
||||
|
||||
@@ -11,11 +11,11 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
**To install GRDB with a custom SQLite build:**
|
||||
|
||||
1. Clone the GRDB.swift git repository, checkout the latest tagged version, and download SQLite sources:
|
||||
1. Clone the GRDB git repository, checkout the latest tagged version, and download SQLite sources:
|
||||
|
||||
```sh
|
||||
cd [GRDB.swift directory]
|
||||
git checkout v1.1
|
||||
cd [GRDB directory]
|
||||
git checkout v2.3.1
|
||||
git submodule update --init SQLiteCustom/src
|
||||
````
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ This guide is a step-by-step tour of GRDB extensibility, around a few topics:
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT name, color FROM clothes")
|
||||
while let row = try rows.next() {
|
||||
let name: String = row.value(named: "name")
|
||||
let color: UIColor = row.value(named: "color") // <-- New! UIColor as value
|
||||
let name: String = row["name"]
|
||||
let color: UIColor = row["color"] // <-- New! UIColor as value
|
||||
}
|
||||
```
|
||||
|
||||
@@ -93,8 +93,8 @@ Well, you will be able to use UIColor like all other [value types](../../../#val
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT * FROM clothes")
|
||||
while let row = try rows.next() {
|
||||
let name: String = row.value(named: "name")
|
||||
let color: UIColor = row.value(named: "color")
|
||||
let name: String = row["name"]
|
||||
let color: UIColor = row["color"]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -112,8 +112,8 @@ Well, you will be able to use UIColor like all other [value types](../../../#val
|
||||
var color: UIColor
|
||||
|
||||
required init(row: Row) {
|
||||
name = row.value(named: "name")
|
||||
color = row.value(named: "color")
|
||||
name = row["name"]
|
||||
color = row["color"]
|
||||
super.init(row: row)
|
||||
}
|
||||
|
||||
@@ -497,7 +497,7 @@ Build a `value BETWEEN min AND max` expression from Swift ranges:
|
||||
|
||||
#### The COUNT Function
|
||||
|
||||
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/1.1/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/1.1/Functions.html) functions:
|
||||
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.3/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.3/Functions.html) functions:
|
||||
|
||||
```swift
|
||||
// SQLExpression: COUNT(email)
|
||||
@@ -588,4 +588,4 @@ You may want to compare it to another protocol, SQLSpecificExpressible, which ha
|
||||
|
||||
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
|
||||
|
||||
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/1.1/Protocols/SQLExpression.html) protocol.
|
||||
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/2.3/Protocols/SQLExpression.html) protocol.
|
||||
@@ -10,7 +10,6 @@ To release a new GRDB version:
|
||||
- Build and run GRDBDemoiOS in Release configuration on a device
|
||||
- Archive GRDBDemoiOS
|
||||
- Check for performance regression with GRDBOSXPerformanceTests
|
||||
- On SDK upgrade, update Support/sqlite3.h
|
||||
- On https://github.com/groue/sqlcipher.git upgrade, update SQLCipher version in README.md
|
||||
- On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in README.md and Documentation/CustomSQLiteBuilds.md
|
||||
- Update GRDB version number and release date in:
|
||||
@@ -25,7 +24,7 @@ To release a new GRDB version:
|
||||
- Commit and tag
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the master branch
|
||||
- Push to the Swift3 branch
|
||||
- Push to the Swift4 branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- `pod trunk push --allow-warnings GRDBCipher.podspec`
|
||||
- `make doc`, and update index.html in the `gh-pages` branch
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
Why Adopt GRDB?
|
||||
===============
|
||||
|
||||
This document aims at exposing why GRDB could become your favorite database library.
|
||||
|
||||
We'll start with a few [core principles](#core-principles), so that you see where this library aims at. Then we'll see how GRDB [solves problems](#solving-problems) that developers often face when they use database libraries such as FMDB, FCModel, SQLite.swift, Core Data, or Realm.
|
||||
|
||||
|
||||
## Core Principles
|
||||
|
||||
### 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?
|
||||
|
||||
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.
|
||||
|
||||
Yet recent ORMs such as Rust's [Diesel] have shown that it is possible to build record types that behave as plain and simple values. GRDB belongs to this family.
|
||||
|
||||
|
||||
### Raw SQL is sometimes the correct tool for the job.
|
||||
|
||||
Complex database queries sometimes need to be prototyped and debugged in an SQL shell. Once perfected, the process of translating this raw SQL query into calls to a query builder can be long and painful, with no guarantee of success. And the resulting code often lacks the legibility of the initial SQL. When this happens, the query builder is no longer useful: whoever wants to write raw SQL should always be welcome.
|
||||
|
||||
|
||||
### The database file is the single source of truth.
|
||||
|
||||
Each Core Data's managed object context has its own version of the database. This can be useful when developing a macOS application full of inspector panels and nested undo stacks. But that's about it.
|
||||
|
||||
In the same vein, each application thread has its own version of a Realm database, with non trivial synchronization points.
|
||||
|
||||
Conversely, GRDB assumes that many apps want to use the database as a reliable and unambiguous storage.
|
||||
|
||||
|
||||
### Applications developers have specific needs.
|
||||
|
||||
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...
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
## Solving Problems
|
||||
|
||||
What is the purpose of the above principles, if not providing solutions to difficulties and limitations of other persistence libraries?
|
||||
|
||||
|
||||
### 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.
|
||||
|
||||
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.
|
||||
|
||||
With GRDB, any type can become a database record. For example, let's start from this `Place` struct:
|
||||
|
||||
```swift
|
||||
struct Place {
|
||||
var id: Int64?
|
||||
let title: String
|
||||
let coordinate: CLLocationCoordinate2D
|
||||
}
|
||||
```
|
||||
|
||||
By adopting the [RowConvertible] protocol, places can be loaded from SQL requests:
|
||||
|
||||
```swift
|
||||
extension Place: RowConvertible { ... }
|
||||
let places = try Place.fetchAll(db, "SELECT * FROM places") // [Place]
|
||||
```
|
||||
|
||||
Add the [TableMapping] protocol, and SQL requests are generated for you:
|
||||
|
||||
```swift
|
||||
extension Place: TableMapping { ... }
|
||||
let place = try Place.fetchOne(db, key: 1) // Place?
|
||||
```
|
||||
|
||||
Add the [Persistable] protocol, and places know how to insert, update and delete themselves:
|
||||
|
||||
```swift
|
||||
extension Place: Persistable { ... }
|
||||
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.
|
||||
|
||||
|
||||
### Allow database records to cross threads
|
||||
|
||||
As soon as records are immutable values, they can safely be used from different threads. You no longer have to pass object ids or references between threads, as in Core Data or Realm:
|
||||
|
||||
```swift
|
||||
if let player = try Player.fetchOne(db, key: 1) {
|
||||
DispatchQueue.main.async {
|
||||
nameField.text = player.name
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### Replace auto-updating records with notifications of database changes
|
||||
|
||||
GRDB records are plain values, like other values in your application. They are not tied to the database. Sometimes you build them from scratch, and sometimes you fetch them:
|
||||
|
||||
```swift
|
||||
let player = Player(name: "arthur", score: 1000)
|
||||
let players = try Player.fetchAll(db)
|
||||
```
|
||||
|
||||
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, by observing database changes and react accordingly, or in any way deemed relevant.
|
||||
|
||||
There are several ways to be notified of database changes. You can build on top of the low-level [TransactionObserver] protocol. Or you can use [FetchedRecordsController], which looks a lot like Core Data's NSFetchedResultsController, and is able to animate table and collection views. And don't forget [RxGRDB], a set of reactive extensions based on [RxSwift]:
|
||||
|
||||
```swift
|
||||
Player.all().rx
|
||||
.fetchAll(in: dbQueue)
|
||||
.subscribe(onNext: { players: [Player] in
|
||||
print("Players have changed")
|
||||
})
|
||||
```
|
||||
|
||||
No matter which observation technique you use, you have common guarantees:
|
||||
|
||||
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rollbacked.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
### 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).
|
||||
|
||||
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).
|
||||
|
||||
|
||||
### Strong and clear multi-threading guarantees
|
||||
|
||||
I'd like to compare GRDB's handling of concurrency with other libraries. To be as clear as possible, we'll identity a few threats, or potential sources of bugs, and wonder if those are handled by the library, or left to the host application.
|
||||
|
||||
The more threats are handled by the application, the more skilled and careful a developer has to be in order to avoid them.
|
||||
|
||||
- **Concurrent writes**: Two threads want to write in the database as the same time. SQLite does not allow that.
|
||||
- **Isolation troubles**: As two database queries run one after the other, a concurrent thread sneaks in and modifies the database in between. The two queries can thus perform inconsistent fetches or updates, unless they are properly isolated. Lack of isolation may display funny values on the screen, trigger a relational constraint error, or silently corrupt the database content.
|
||||
- **Conflicts**: The same piece of data is both edited by the application user, and refreshed from a network operation. What will eventually be stored in the database? Can any conflict be noticed?
|
||||
- **Blocked UI**: Can it happen that the UI is blocked because the main thread has to wait for a background thread to release a lock on the database?
|
||||
|
||||
|
||||
| Library | Concurrent Writes | Isolation Trouble | Conflicts | Blocked UI |
|
||||
| ------- | ----------------- | ----------------- | --------- | ---------- |
|
||||
| FMDB's FMDatabase | Handled by the application | Handled by the application | Handled by the application | Handled by the application |
|
||||
| FMDB's FMDatabaseQueue | :white_check_mark: | :white_check_mark: | Handled by the application | UI is blocked |
|
||||
| SQLite.swift | :white_check_mark: | Handled by the application | Handled by the application | Handled by the application |
|
||||
| Core Data | Handled by the application, because of the constant threat of conflict errors | :white_check_mark: | Handled by the application, and it is very difficult because of the subtleties of Core Data's conflict policies | Handled by the application |
|
||||
| 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.
|
||||
|
||||
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:.
|
||||
|
||||
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.
|
||||
|
||||
For further information about GRDB concurrency, check its detailed [Concurrency Guide].
|
||||
|
||||
|
||||
### Never pay for using raw SQL
|
||||
|
||||
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:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM players ORDER BY score DESC LIMIT 10
|
||||
let bestPlayers: [Player] = try Player
|
||||
.order(scoreColumn.desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
// SELECT MAX(score) FROM players
|
||||
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)
|
||||
```
|
||||
|
||||
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
|
||||
""")
|
||||
|
||||
let maximumScore: Int? = try Int.fetchOne(db, """
|
||||
SELECT MAX(score) FROM players
|
||||
""")
|
||||
|
||||
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]:
|
||||
|
||||
```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")
|
||||
})
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(db, "SELECT * FROM players")
|
||||
while let row = try rows.next() {
|
||||
let id: Int64 = row["id"]
|
||||
let name: String = row["name"]
|
||||
let score: Int = row["score"]
|
||||
}
|
||||
```
|
||||
|
||||
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):
|
||||
|
||||
```swift
|
||||
extension Player {
|
||||
static func customRequest(...) -> AnyTypedRequest<Player> {
|
||||
return SQLRequest("""
|
||||
SELECT ...
|
||||
""", arguments: ...)
|
||||
.asRequestOf(Player.self)
|
||||
}
|
||||
}
|
||||
|
||||
let players = Player.customRequest(...).fetchAll(db)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
If this little tour of GRDB has convinced you, the real trip starts here: [GRDB].
|
||||
|
||||
And if you happen to maintain an Objective-C application that uses FMDB, checkout [GRDBObjc]. It provides FMDB-compatible bindings to GRDB, so that you can inject sweet drops of Swift into your app, at your own pace, and at minimal cost.
|
||||
|
||||
Happy GRDB! :gift:
|
||||
|
||||
[Concurrency Guide]: https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency
|
||||
[Core Data]: https://developer.apple.com/documentation/coredata
|
||||
[DatabasePool]: https://github.com/groue/GRDB.swift/blob/master/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
|
||||
[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
|
||||
[Realm]: http://realm.io
|
||||
[RowConvertible]: https://github.com/groue/GRDB.swift/blob/master/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
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '1.1'
|
||||
s.version = '2.3.1'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
@@ -13,7 +13,7 @@ Pod::Spec.new do |s|
|
||||
s.osx.deployment_target = '10.9'
|
||||
s.watchos.deployment_target = '2.0'
|
||||
|
||||
s.source_files = 'GRDB/**/*.swift', 'Support/*.{c,h}'
|
||||
s.source_files = 'GRDB/**/*.swift', 'Support/*.h'
|
||||
s.module_map = 'Support/module.modulemap'
|
||||
s.framework = 'Foundation'
|
||||
s.library = 'sqlite3'
|
||||
|
||||
+606
-292
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0830"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -26,6 +26,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
@@ -55,6 +56,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0810"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56439B2D1F4CA1DC0066043F"
|
||||
BuildableName = "GRDBOSXPerformanceComparisonTests.xctest"
|
||||
BlueprintName = "GRDBOSXPerformanceComparisonTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0730"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -10,6 +10,7 @@
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
@@ -30,6 +31,7 @@
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
language = ""
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0810"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0810"
|
||||
LastUpgradeVersion = "0900"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
+3
@@ -16,6 +16,9 @@
|
||||
<FileRef
|
||||
location = "group:TransactionObserver.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Issue156.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:MyPlayground.playground">
|
||||
</FileRef>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
|
||||
@@ -11,6 +11,19 @@ extension Array {
|
||||
}
|
||||
}
|
||||
|
||||
extension Set {
|
||||
/// Creates a set containing the elements of a cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'foo'")
|
||||
/// let strings = try Set(cursor) // ["foo"]
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
self.init()
|
||||
while let element = try cursor.next() {
|
||||
insert(element)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that supplies the values of some external resource, one at a time.
|
||||
///
|
||||
/// ## Overview
|
||||
|
||||
@@ -0,0 +1,456 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// Clears the database schema cache.
|
||||
///
|
||||
/// You may need to clear the cache manually if the database schema is
|
||||
/// modified by another connection.
|
||||
public func clearSchemaCache() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
schemaCache.clear()
|
||||
|
||||
// We also clear updateStatementCache and selectStatementCache despite
|
||||
// the automatic statement recompilation (see https://www.sqlite.org/c3ref/prepare.html)
|
||||
// because the automatic statement recompilation only happens a
|
||||
// limited number of times.
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
}
|
||||
|
||||
/// Returns whether a table exists.
|
||||
public func tableExists(_ tableName: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
|
||||
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 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)
|
||||
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 = 'view' AND LOWER(name) = ?", arguments: [viewName.lowercased()]) != nil
|
||||
}
|
||||
|
||||
/// Returns whether a trigger exists.
|
||||
public func triggerExists(_ triggerName: String) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html)
|
||||
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 = 'trigger' AND LOWER(name) = ?", arguments: [triggerName.lowercased()]) != nil
|
||||
}
|
||||
|
||||
/// The primary key for table named `tableName`.
|
||||
///
|
||||
/// All tables have a primary key, even when it is not explicit. When a
|
||||
/// table has no explicit primary key, the result is the hidden
|
||||
/// "rowid" column.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
if let primaryKey = schemaCache.primaryKey(tableName) {
|
||||
return primaryKey
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
//
|
||||
// > PRAGMA database.table_info(table-name);
|
||||
// >
|
||||
// > This pragma returns one row for each column in the named table.
|
||||
// > Columns in the result set include the column name, data type,
|
||||
// > whether or not the column can be NULL, and the default value for
|
||||
// > the column. The "pk" column in the result set is zero for columns
|
||||
// > that are not part of the primary key, and is the index of the
|
||||
// > column in the primary key for columns that are part of the primary
|
||||
// > key.
|
||||
//
|
||||
// CREATE TABLE players (
|
||||
// id INTEGER PRIMARY KEY,
|
||||
// name TEXT,
|
||||
// score INTEGER)
|
||||
//
|
||||
// PRAGMA table_info("players")
|
||||
//
|
||||
// cid | name | type | notnull | dflt_value | pk |
|
||||
// 0 | id | INTEGER | 0 | NULL | 1 |
|
||||
// 1 | name | TEXT | 0 | NULL | 0 |
|
||||
// 2 | score | INTEGER | 0 | NULL | 0 |
|
||||
|
||||
let columns = try self.columns(in: tableName)
|
||||
|
||||
let primaryKey: PrimaryKeyInfo
|
||||
let pkColumns = columns
|
||||
.filter { $0.primaryKeyIndex > 0 }
|
||||
.sorted { $0.primaryKeyIndex < $1.primaryKeyIndex }
|
||||
|
||||
switch pkColumns.count {
|
||||
case 0:
|
||||
// No explicit primary key => primary key is hidden rowID column
|
||||
primaryKey = .hiddenRowID
|
||||
case 1:
|
||||
// Single column
|
||||
let pkColumn = pkColumns.first!
|
||||
|
||||
// https://www.sqlite.org/lang_createtable.html:
|
||||
//
|
||||
// > With one exception noted below, if a rowid table has a primary
|
||||
// > key that consists of a single column and the declared type of
|
||||
// > that column is "INTEGER" in any mixture of upper and lower
|
||||
// > case, then the column becomes an alias for the rowid. Such a
|
||||
// > column is usually referred to as an "integer primary key".
|
||||
// > A PRIMARY KEY column only becomes an integer primary key if the
|
||||
// > declared type name is exactly "INTEGER". Other integer type
|
||||
// > names like "INT" or "BIGINT" or "SHORT INTEGER" or "UNSIGNED
|
||||
// > INTEGER" causes the primary key column to behave as an ordinary
|
||||
// > table column with integer affinity and a unique index, not as
|
||||
// > an alias for the rowid.
|
||||
// >
|
||||
// > The exception mentioned above is that if the declaration of a
|
||||
// > column with declared type "INTEGER" includes an "PRIMARY KEY
|
||||
// > DESC" clause, it does not become an alias for the rowid [...]
|
||||
//
|
||||
// FIXME: We ignore the exception, and consider all INTEGER primary
|
||||
// keys as aliases for the rowid:
|
||||
if pkColumn.type.uppercased() == "INTEGER" {
|
||||
primaryKey = .rowID(pkColumn.name)
|
||||
} else {
|
||||
primaryKey = .regular([pkColumn.name])
|
||||
}
|
||||
default:
|
||||
// Multi-columns primary key
|
||||
primaryKey = .regular(pkColumns.map { $0.name })
|
||||
}
|
||||
|
||||
schemaCache.set(primaryKey: primaryKey, forTable: tableName)
|
||||
return primaryKey
|
||||
}
|
||||
|
||||
/// The number of columns in the table named `tableName`.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
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.
|
||||
///
|
||||
/// Note: SQLite does not define any index for INTEGER PRIMARY KEY columns:
|
||||
/// this method does not return any index that represents this primary key.
|
||||
///
|
||||
/// If you want to know if a set of columns uniquely identify a row, prefer
|
||||
/// table(_:hasUniqueKey:) instead.
|
||||
public func indexes(on tableName: String) throws -> [IndexInfo] {
|
||||
if let indexes = schemaCache.indexes(on: tableName) {
|
||||
return indexes
|
||||
}
|
||||
|
||||
let indexes = try Row.fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))").map { row -> IndexInfo in
|
||||
let indexName: String = row[1]
|
||||
let unique: Bool = row[2]
|
||||
let columns = try Row.fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
|
||||
.map { ($0[0] as Int, $0[2] as String) }
|
||||
.sorted { $0.0 < $1.0 }
|
||||
.map { $0.1 }
|
||||
return IndexInfo(name: indexName, columns: columns, unique: unique)
|
||||
}
|
||||
|
||||
schemaCache.set(indexes: indexes, forTable: tableName)
|
||||
return indexes
|
||||
}
|
||||
|
||||
/// True if a sequence of columns uniquely identifies a row, that is to say
|
||||
/// if the columns are the primary key, or if there is a unique index on them.
|
||||
public func table<T: Sequence>(_ tableName: String, hasUniqueKey columns: T) throws -> Bool where T.Iterator.Element == String {
|
||||
return try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
}
|
||||
|
||||
/// The foreign keys defined on table named `tableName`.
|
||||
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
|
||||
if let foreignKeys = schemaCache.foreignKeys(on: tableName) {
|
||||
return foreignKeys
|
||||
}
|
||||
|
||||
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:"...">
|
||||
let id: Int = row[0]
|
||||
let seq: Int = row[1]
|
||||
let table: String = row[2]
|
||||
let origin: String = row[3]
|
||||
let destination: String? = row[4]
|
||||
|
||||
if previousId == id {
|
||||
rawForeignKeys[rawForeignKeys.count - 1].mapping.append((origin: origin, destination: destination, seq: seq))
|
||||
} else {
|
||||
rawForeignKeys.append((destinationTable: table, mapping: [(origin: origin, destination: destination, seq: seq)]))
|
||||
previousId = id
|
||||
}
|
||||
}
|
||||
|
||||
let foreignKeys = try rawForeignKeys.map { (destinationTable, columnMapping) -> ForeignKeyInfo in
|
||||
let orderedMapping = columnMapping
|
||||
.sorted { $0.seq < $1.seq }
|
||||
.map { (origin: $0.origin, destination: $0 .destination) }
|
||||
|
||||
let completeMapping: [(origin: String, destination: String)]
|
||||
if orderedMapping.contains(where: { (_, destination) in destination == nil }) {
|
||||
let pk = try primaryKey(destinationTable)
|
||||
completeMapping = zip(pk.columns, orderedMapping).map { (pkColumn, arrow) in
|
||||
(origin: arrow.origin, destination: pkColumn)
|
||||
}
|
||||
} else {
|
||||
completeMapping = orderedMapping.map { (origin, destination) in
|
||||
(origin: origin, destination: destination!)
|
||||
}
|
||||
}
|
||||
return ForeignKeyInfo(destinationTable: destinationTable, mapping: completeMapping)
|
||||
}
|
||||
|
||||
schemaCache.set(foreignKeys: foreignKeys, forTable: tableName)
|
||||
return foreignKeys
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
/// The columns in the table named `tableName`.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
func columns(in tableName: String) throws -> [ColumnInfo] {
|
||||
if let columns = schemaCache.columns(in: tableName) {
|
||||
return columns
|
||||
}
|
||||
|
||||
// https://www.sqlite.org/pragma.html
|
||||
//
|
||||
// > PRAGMA database.table_info(table-name);
|
||||
// >
|
||||
// > This pragma returns one row for each column in the named table.
|
||||
// > Columns in the result set include the column name, data type,
|
||||
// > whether or not the column can be NULL, and the default value for
|
||||
// > the column. The "pk" column in the result set is zero for columns
|
||||
// > that are not part of the primary key, and is the index of the
|
||||
// > column in the primary key for columns that are part of the primary
|
||||
// > key.
|
||||
//
|
||||
// CREATE TABLE players (
|
||||
// id INTEGER PRIMARY KEY,
|
||||
// firstName TEXT,
|
||||
// lastName TEXT)
|
||||
//
|
||||
// PRAGMA table_info("players")
|
||||
//
|
||||
// cid | name | type | notnull | dflt_value | pk |
|
||||
// 0 | id | INTEGER | 0 | NULL | 1 |
|
||||
// 1 | name | TEXT | 0 | NULL | 0 |
|
||||
// 2 | score | INTEGER | 0 | NULL | 0 |
|
||||
|
||||
if sqlite3_libversion_number() < 3008005 {
|
||||
// Work around a bug in SQLite where PRAGMA table_info would
|
||||
// return a result even after the table was deleted.
|
||||
if try !tableExists(tableName) {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
}
|
||||
let columns = try ColumnInfo.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
|
||||
guard columns.count > 0 else {
|
||||
throw DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
|
||||
schemaCache.set(columns: columns, forTable: tableName)
|
||||
return columns
|
||||
}
|
||||
|
||||
/// If there exists a unique key on columns, return the columns
|
||||
/// ordered as the matching index (or primay key). Case of returned columns
|
||||
/// is not guaranteed.
|
||||
func columnsForUniqueKey<T: Sequence>(_ columns: T, in tableName: String) throws -> [String]? where T.Iterator.Element == String {
|
||||
let primaryKey = try self.primaryKey(tableName) // first, so that we fail early and consistently should the table not exist
|
||||
let lowercasedColumns = Set(columns.map { $0.lowercased() })
|
||||
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
|
||||
return primaryKey.columns
|
||||
}
|
||||
if let index = try indexes(on: tableName).first(where: { index in index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns }) {
|
||||
// There is an explicit unique index on the columns
|
||||
return index.columns
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// A column of a table
|
||||
struct ColumnInfo : RowConvertible {
|
||||
// CREATE TABLE players (
|
||||
// id INTEGER PRIMARY KEY,
|
||||
// firstName TEXT,
|
||||
// lastName TEXT)
|
||||
//
|
||||
// PRAGMA table_info("players")
|
||||
//
|
||||
// cid | name | type | notnull | dflt_value | pk |
|
||||
// 0 | id | INTEGER | 0 | NULL | 1 |
|
||||
// 1 | name | TEXT | 0 | NULL | 0 |
|
||||
// 2 | score | INTEGER | 0 | NULL | 0 |
|
||||
let name: String
|
||||
let type: String
|
||||
let notNull: Bool
|
||||
let defaultDatabaseValue: DatabaseValue
|
||||
let primaryKeyIndex: Int
|
||||
|
||||
init(row: Row) {
|
||||
name = row["name"]
|
||||
type = row["type"]
|
||||
notNull = row["notnull"]
|
||||
defaultDatabaseValue = row["dflt_value"]
|
||||
primaryKeyIndex = row["pk"]
|
||||
}
|
||||
}
|
||||
|
||||
/// An index on a database table.
|
||||
///
|
||||
/// See `Database.indexes(on:)`
|
||||
public struct IndexInfo {
|
||||
/// The name of the index
|
||||
public let name: String
|
||||
|
||||
/// The indexed columns
|
||||
public let columns: [String]
|
||||
|
||||
/// True if the index is unique
|
||||
public let isUnique: Bool
|
||||
|
||||
init(name: String, columns: [String], unique: Bool) {
|
||||
self.name = name
|
||||
self.columns = columns
|
||||
self.isUnique = unique
|
||||
}
|
||||
}
|
||||
|
||||
/// Primary keys are returned from the Database.primaryKey(_:) method.
|
||||
///
|
||||
/// When the table's primary key is the rowid:
|
||||
///
|
||||
/// // CREATE TABLE items (name TEXT)
|
||||
/// let pk = try db.primaryKey("items")
|
||||
/// pk.columns // ["rowid"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // true
|
||||
///
|
||||
/// // CREATE TABLE citizens (
|
||||
/// // id INTEGER PRIMARY KEY,
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = try db.primaryKey("citizens")!
|
||||
/// pk.columns // ["id"]
|
||||
/// pk.rowIDColumn // "id"
|
||||
/// pk.isRowID // true
|
||||
///
|
||||
/// When the table's primary key is not the rowid:
|
||||
///
|
||||
/// // CREATE TABLE countries (
|
||||
/// // isoCode TEXT NOT NULL PRIMARY KEY
|
||||
/// // name TEXT
|
||||
/// // )
|
||||
/// let pk = db.primaryKey("countries")!
|
||||
/// 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)
|
||||
/// // PRIMARY KEY (citizenID, countryIsoCode)
|
||||
/// // )
|
||||
/// let pk = db.primaryKey("citizenships")!
|
||||
/// pk.columns // ["citizenID", "countryIsoCode"]
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
public struct PrimaryKeyInfo {
|
||||
private enum Impl {
|
||||
/// The hidden rowID.
|
||||
case hiddenRowID
|
||||
|
||||
/// An INTEGER PRIMARY KEY column that aliases the Row ID.
|
||||
/// Associated string is the column name.
|
||||
case rowID(String)
|
||||
|
||||
/// Any primary key, but INTEGER PRIMARY KEY.
|
||||
/// Associated strings are column names.
|
||||
case regular([String])
|
||||
}
|
||||
|
||||
private let impl: Impl
|
||||
|
||||
static func rowID(_ column: String) -> PrimaryKeyInfo {
|
||||
return PrimaryKeyInfo(impl: .rowID(column))
|
||||
}
|
||||
|
||||
static func regular(_ columns: [String]) -> PrimaryKeyInfo {
|
||||
assert(!columns.isEmpty)
|
||||
return PrimaryKeyInfo(impl: .regular(columns))
|
||||
}
|
||||
|
||||
static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID)
|
||||
|
||||
/// The columns in the primary key; this array is never empty.
|
||||
public var columns: [String] {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return [Column.rowID.name]
|
||||
case .rowID(let column):
|
||||
return [column]
|
||||
case .regular(let columns):
|
||||
return columns
|
||||
}
|
||||
}
|
||||
|
||||
/// When not nil, the name of the column that contains the INTEGER PRIMARY KEY.
|
||||
public var rowIDColumn: String? {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return nil
|
||||
case .rowID(let column):
|
||||
return column
|
||||
case .regular:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// When true, the primary key is the rowid:
|
||||
public var isRowID: Bool {
|
||||
switch impl {
|
||||
case .hiddenRowID:
|
||||
return true
|
||||
case .rowID:
|
||||
return true
|
||||
case .regular:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// You get foreign keys from table names, with the
|
||||
/// `foreignKeys(on:)` method.
|
||||
public struct ForeignKeyInfo {
|
||||
/// The name of the destination table
|
||||
public let destinationTable: String
|
||||
|
||||
/// The column to column mapping
|
||||
public let mapping: [(origin: String, destination: String)]
|
||||
|
||||
/// The origin columns
|
||||
public var originColumns: [String] {
|
||||
return mapping.map { $0.origin }
|
||||
}
|
||||
|
||||
/// The destination columns
|
||||
public var destinationColumns: [String] {
|
||||
return mapping.map { $0.destination }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
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 moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A SelectStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeSelectStatement(_ sql: String) throws -> SelectStatement {
|
||||
return try makeStatement(sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?", prepFlags: 0)
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - returns: A SelectStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
|
||||
return try makeStatement(sql, prepFlags: prepFlags)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedSelectStatement(_ sql: String) throws -> SelectStatement {
|
||||
return try publicStatementCache.selectStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedSelectStatement(_ sql: String) throws -> SelectStatement {
|
||||
return try internalStatementCache.selectStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
return try makeStatement(sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)", prepFlags: 0)
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
|
||||
return try makeStatement(sql, prepFlags: prepFlags)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedUpdateStatement("INSERT INTO players (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
return try publicStatementCache.updateStatement(sql)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
return try internalStatementCache.updateStatement(sql)
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// try db.execute(
|
||||
/// "INSERT INTO players (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
///
|
||||
/// try db.execute("""
|
||||
/// INSERT INTO players (name) VALUES (?);
|
||||
/// INSERT INTO players (name) VALUES (?);
|
||||
/// INSERT INTO players (name) VALUES (?);
|
||||
/// """, arguments; ['Arthur', 'Barbara', 'Craig'])
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws {
|
||||
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
|
||||
// It adds support for arguments, and the tricky part is to consume
|
||||
// arguments as statements are executed.
|
||||
//
|
||||
// Here we build two functions:
|
||||
// - consumeArguments returns arguments for a statement
|
||||
// - validateRemainingArguments validates the remaining arguments, after
|
||||
// all statements have been executed, in the same way
|
||||
// as Statement.validate(arguments:)
|
||||
|
||||
var arguments = arguments ?? StatementArguments()
|
||||
let initialValuesCount = arguments.values.count
|
||||
let consumeArguments = { (statement: UpdateStatement) throws -> StatementArguments in
|
||||
let bindings = try arguments.consume(statement, allowingRemainingValues: true)
|
||||
return StatementArguments(bindings)
|
||||
}
|
||||
let validateRemainingArguments = {
|
||||
if !arguments.values.isEmpty {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)")
|
||||
}
|
||||
}
|
||||
|
||||
// Iterate SQL statements
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
let sqlEnd = sqlStart + sqlCodeUnits.count
|
||||
var statementStart = sqlStart
|
||||
while statementStart < sqlEnd - 1 {
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
do {
|
||||
let statement: UpdateStatement
|
||||
// Compile
|
||||
do {
|
||||
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
|
||||
authorizer = statementCompilationAuthorizer
|
||||
defer { authorizer = nil }
|
||||
|
||||
statement = try UpdateStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: 0,
|
||||
authorizer: statementCompilationAuthorizer)
|
||||
}
|
||||
|
||||
// Execute
|
||||
let arguments = try consumeArguments(statement)
|
||||
statement.unsafeSetArguments(arguments)
|
||||
try statement.execute()
|
||||
|
||||
// Next
|
||||
statementStart = statementEnd!
|
||||
} catch is EmptyStatementError {
|
||||
// End
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
try! validateRemainingArguments() // throws if there are remaining arguments.
|
||||
}
|
||||
|
||||
private func makeStatement<Statement: AuthorizedStatement>(_ sql: String, prepFlags: Int32) throws -> Statement {
|
||||
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
|
||||
authorizer = statementCompilationAuthorizer
|
||||
defer { authorizer = nil }
|
||||
|
||||
var statement: Statement? = nil
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
var remainingSQL = ""
|
||||
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let statementStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
do {
|
||||
statement = try Statement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: statementCompilationAuthorizer)
|
||||
} catch is EmptyStatementError {
|
||||
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "empty statement", sql: sql, arguments: nil)
|
||||
}
|
||||
let remainingData = Data(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: statementEnd!),
|
||||
count: statementStart + sqlCodeUnits.count - statementEnd! - 1,
|
||||
deallocator: .none)
|
||||
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
|
||||
guard remainingSQL.isEmpty else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
|
||||
}
|
||||
|
||||
return statement!
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) {
|
||||
observationBroker.updateStatementWillExecute(statement)
|
||||
}
|
||||
|
||||
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
try observationBroker.updateStatementDidExecute(statement)
|
||||
}
|
||||
|
||||
func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
//
|
||||
// So make sure we clear this statement from the cache.
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
|
||||
try observationBroker.updateStatementDidFail(statement)
|
||||
}
|
||||
|
||||
func selectStatementDidFail(_ statement: SelectStatement) {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
//
|
||||
// So make sure we clear this statement from the cache.
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
}
|
||||
}
|
||||
+775
-2515
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,51 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A Collation is a string comparison function used by SQLite.
|
||||
public final class DatabaseCollation {
|
||||
public let name: String
|
||||
let function: (Int32, UnsafeRawPointer?, Int32, UnsafeRawPointer?) -> ComparisonResult
|
||||
|
||||
/// Creates a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - function: A function that compares two strings.
|
||||
public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) {
|
||||
self.name = name
|
||||
self.function = { (length1, buffer1, length2, buffer2) in
|
||||
// Buffers are not C strings: they do not end with \0.
|
||||
let string1 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped), length: Int(length1), encoding: .utf8, freeWhenDone: false)!
|
||||
let string2 = String(bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped), length: Int(length2), encoding: .utf8, freeWhenDone: false)!
|
||||
return function(string1, string2)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseCollation : Hashable {
|
||||
public var hashValue: Int {
|
||||
// Collation equality is based on the sqlite3_strnicmp SQLite function.
|
||||
// (see https://www.sqlite.org/c3ref/create_collation.html). Computing
|
||||
// a hash value that honors the Swift Hashable contract (value equality
|
||||
// implies hash equality) is thus non trivial. But it's not that
|
||||
// important, since this hashValue is only used when one adds
|
||||
// or removes a collation from a database connection.
|
||||
return 0
|
||||
}
|
||||
|
||||
/// Two collations are equal if they share the same name (case insensitive)
|
||||
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
|
||||
// See https://www.sqlite.org/c3ref/create_collation.html
|
||||
return sqlite3_stricmp(lhs.name, lhs.name) == 0
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
|
||||
public struct ResultCode : RawRepresentable {
|
||||
public let rawValue: Int32
|
||||
|
||||
public init(rawValue: Int32) {
|
||||
@@ -24,24 +25,6 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
|
||||
return self == primaryResultCode
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
|
||||
return lhs.rawValue == rhs.rawValue
|
||||
}
|
||||
|
||||
/// Returns true if the code on the left matches the code on the right.
|
||||
///
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
@@ -154,7 +137,28 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible
|
||||
public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8)))
|
||||
public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8)))
|
||||
public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8)))
|
||||
}
|
||||
|
||||
extension ResultCode : Equatable {
|
||||
public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool {
|
||||
return lhs.rawValue == rhs.rawValue
|
||||
}
|
||||
}
|
||||
|
||||
extension ResultCode : CustomStringConvertible {
|
||||
public var description: String {
|
||||
// sqlite3_errstr was added in SQLite 3.7.15 http://www.sqlite.org/changes.html#version_3_7_15
|
||||
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
#else
|
||||
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
|
||||
return "\(rawValue) (\(String(cString: sqlite3_errstr(rawValue))))"
|
||||
} else {
|
||||
return "\(rawValue)"
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
@@ -220,9 +224,8 @@ public struct DatabaseError : Error {
|
||||
}
|
||||
|
||||
extension DatabaseError: CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
var description = "SQLite error \(extendedResultCode.rawValue)"
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let sql = sql {
|
||||
description += " with statement `\(sql)`"
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// An SQL function or aggregate.
|
||||
@@ -8,8 +10,8 @@ public final class DatabaseFunction {
|
||||
let argumentCount: Int32?
|
||||
let pure: Bool
|
||||
private let kind: Kind
|
||||
fileprivate var nArg: Int32 { return argumentCount ?? -1 }
|
||||
fileprivate var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
private var nArg: Int32 { return argumentCount ?? -1 }
|
||||
private var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
|
||||
/// Returns an SQL function.
|
||||
///
|
||||
@@ -356,10 +358,10 @@ public protocol DatabaseAggregate {
|
||||
/// aggregate function.
|
||||
///
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM persons
|
||||
/// SELECT maxLength(name) FROM players
|
||||
///
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM persons
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM players
|
||||
///
|
||||
/// This method is never called after the finalize() method has been called.
|
||||
mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
|
||||
+158
-95
@@ -1,17 +1,34 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
#if os(iOS)
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// A DatabasePool grants concurrent accesses to an SQLite database.
|
||||
public final class DatabasePool {
|
||||
private let writer: SerializedDatabase
|
||||
private var readerConfig: Configuration
|
||||
private var readerPool: Pool<SerializedDatabase>!
|
||||
|
||||
// MARK: - Initializers
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
|
||||
#if os(iOS)
|
||||
private weak var application: UIApplication?
|
||||
#endif
|
||||
|
||||
// MARK: - Database Information
|
||||
|
||||
/// The path to the database.
|
||||
public var path: String {
|
||||
return writer.path
|
||||
}
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
/// Opens the SQLite database at path *path*.
|
||||
///
|
||||
@@ -62,10 +79,8 @@ public final class DatabasePool {
|
||||
// Readers
|
||||
readerConfig = configuration
|
||||
readerConfig.readonly = true
|
||||
readerConfig.defaultTransactionKind = .deferred // Make it the default. Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
|
||||
readerPool = Pool<SerializedDatabase>(maximumCount: configuration.maximumReaderCount)
|
||||
readerPool.makeElement = { [unowned self] in
|
||||
readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
|
||||
let reader = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: self.readerConfig,
|
||||
@@ -81,7 +96,7 @@ public final class DatabasePool {
|
||||
}
|
||||
|
||||
return reader
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
@@ -93,18 +108,12 @@ public final class DatabasePool {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The path to the database.
|
||||
public var path: String {
|
||||
return writer.path
|
||||
}
|
||||
|
||||
|
||||
// MARK: - WAL Management
|
||||
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - WAL Checkpoints
|
||||
|
||||
/// Runs a WAL checkpoint
|
||||
///
|
||||
/// See https://www.sqlite.org/wal.html and
|
||||
@@ -123,10 +132,12 @@ public final class DatabasePool {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
|
||||
/// Free as much memory as possible.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses are completed.
|
||||
@@ -157,8 +168,6 @@ public final class DatabasePool {
|
||||
center.addObserver(self, selector: #selector(DatabasePool.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
|
||||
}
|
||||
|
||||
private var application: UIApplication!
|
||||
|
||||
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = application else {
|
||||
return
|
||||
@@ -185,24 +194,12 @@ public final class DatabasePool {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
fileprivate let writer: SerializedDatabase
|
||||
fileprivate var readerConfig: Configuration
|
||||
fileprivate let readerPool: Pool<SerializedDatabase>
|
||||
|
||||
fileprivate var functions = Set<DatabaseFunction>()
|
||||
fileprivate var collations = Set<DatabaseCollation>()
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Encryption
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
@@ -214,19 +211,15 @@ public final class DatabasePool {
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseReader
|
||||
|
||||
extension DatabasePool : DatabaseReader {
|
||||
|
||||
// MARK: - Read From Database
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result. The block is wrapped in a deferred transaction.
|
||||
///
|
||||
/// let persons = try dbPool.read { db in
|
||||
/// try Person.fetchAll(...)
|
||||
/// let players = try dbPool.read { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// The block is completely isolated. Eventual concurrent database updates
|
||||
@@ -250,11 +243,12 @@ extension DatabasePool : DatabaseReader {
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync { db in
|
||||
var result: T? = nil
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
|
||||
try db.inTransaction(.deferred) {
|
||||
result = try block(db)
|
||||
return .commit
|
||||
@@ -291,11 +285,70 @@ extension DatabasePool : DatabaseReader {
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync(block)
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// The block argument is not isolated: eventual concurrent database updates
|
||||
/// are visible inside the block:
|
||||
///
|
||||
/// 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")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iteration is safe, though:
|
||||
///
|
||||
/// try dbPool.unsafeReentrantRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided 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
|
||||
/// happen while establishing the read access to the database.
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync(block)
|
||||
} else {
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync(block)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -328,7 +381,6 @@ extension DatabasePool : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
@@ -358,10 +410,6 @@ extension DatabasePool : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseWriter
|
||||
|
||||
extension DatabasePool : DatabaseWriter {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
@@ -451,7 +499,6 @@ extension DatabasePool : DatabaseWriter {
|
||||
return try writer.reentrantSync(block)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
/// Asynchronously executes a read-only block in a protected dispatch queue,
|
||||
@@ -464,12 +511,12 @@ extension DatabasePool : DatabaseWriter {
|
||||
/// database updates are *not visible* inside the block.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("DELETE FROM persons")
|
||||
/// try db.execute("DELETE FROM players")
|
||||
/// try dbPool.readFromCurrentState { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
|
||||
/// }
|
||||
/// try db.execute("INSERT INTO persons ...")
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// }
|
||||
///
|
||||
/// This method blocks the current thread until the isolation guarantee has
|
||||
@@ -479,48 +526,64 @@ extension DatabasePool : DatabaseWriter {
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > In WAL mode, SQLite exhibits "snapshot isolation". When a read
|
||||
// > transaction starts, that reader continues to see an unchanging
|
||||
// > "snapshot" of the database file as it existed at the moment in time
|
||||
// > when the read transaction started. Any write transactions that
|
||||
// > commit while the read transaction is active are still invisible to
|
||||
// > the read transaction, because the reader is seeing a snapshot of
|
||||
// > database file from a prior moment in time.
|
||||
//
|
||||
// That's exactly what we need. But what does "when read transaction
|
||||
// starts" mean?
|
||||
//
|
||||
// http://www.sqlite.org/lang_transaction.html
|
||||
//
|
||||
// > Deferred [transaction] means that no locks are acquired on the
|
||||
// > database until the database is first accessed. [...] Locks are not
|
||||
// > acquired until the first read or write operation. [...] Because the
|
||||
// > acquisition of locks is deferred until they are needed, it is
|
||||
// > possible that another thread or process could create a separate
|
||||
// > transaction and write to the database after the BEGIN on the
|
||||
// > current thread has executed.
|
||||
//
|
||||
// Now that's precise enough: SQLite defers "snapshot isolation" until
|
||||
// the first SELECT:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// UPDATE ... (1)
|
||||
// Here the change (1) is visible
|
||||
// SELECT ...
|
||||
// UPDATE ... (2)
|
||||
// Here the change (2) is not visible
|
||||
//
|
||||
// The readFromCurrentState method says that no change should be visible
|
||||
// at all. We thus have to perform a select that establishes the
|
||||
// snapshot isolation before we release the writer queue:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// SELECT anything
|
||||
// UPDATE ...
|
||||
// Here the change is not visible by GRDB user
|
||||
|
||||
// This method must be called from the writing dispatch queue:
|
||||
writer.preconditionValidQueue()
|
||||
|
||||
// The semaphore that blocks the writing dispatch queue until snapshot
|
||||
// isolation has been established:
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
var readError: Error? = nil
|
||||
try readerPool.get { reader in
|
||||
reader.async { db in
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > In WAL mode, SQLite exhibits "snapshot isolation". When a
|
||||
// > read transaction starts, that reader continues to see an
|
||||
// > unchanging "snapshot" of the database file as it existed at
|
||||
// > the moment in time when the read transaction started.
|
||||
// > Any write transactions that commit while the read
|
||||
// > transaction is active are still invisible to the read
|
||||
// > transaction, because the reader is seeing a snapshot of
|
||||
// > database file from a prior moment in time.
|
||||
//
|
||||
// This documentation is NOT accurate. SQLite actually defers
|
||||
// isolation until the first SELECT:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// UPDATE ... (1)
|
||||
// Here the change (1) is visible
|
||||
// SELECT ...
|
||||
// UPDATE ... (2)
|
||||
// Here the change (2) is not visible
|
||||
//
|
||||
// This is not the guarantee expected by this method: no change
|
||||
// at all should be visible.
|
||||
//
|
||||
// Workaround: perform an initial read before releasing the
|
||||
// writer queue:
|
||||
//
|
||||
// Reader Writer
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// SELECT anything -- the work around
|
||||
// UPDATE ...
|
||||
// Here the change is not visible by GRDB user
|
||||
do {
|
||||
try db.beginTransaction(.deferred)
|
||||
assert(db.isInsideTransaction)
|
||||
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next() // doesn't work with cached statement
|
||||
try db.makeSelectStatement("SELECT rootpage FROM sqlite_master").cursor().next()
|
||||
} catch {
|
||||
readError = error
|
||||
semaphore.signal() // Release the writer queue and rethrow error
|
||||
|
||||
@@ -6,6 +6,22 @@ import UIKit
|
||||
|
||||
/// A DatabaseQueue serializes access to an SQLite database.
|
||||
public final class DatabaseQueue {
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
#if os(iOS)
|
||||
private weak var application: UIApplication?
|
||||
#endif
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
public var path: String {
|
||||
return serializedDatabase.path
|
||||
}
|
||||
|
||||
// MARK: - Initializers
|
||||
|
||||
@@ -50,28 +66,17 @@ public final class DatabaseQueue {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
return serializedDatabase.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
public var path: String {
|
||||
return serializedDatabase.path
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Database access
|
||||
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Database Access
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let persons = try dbQueue.inDatabase { db in
|
||||
/// try Person.fetchAll(...)
|
||||
/// let players = try dbQueue.inDatabase { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
@@ -111,10 +116,12 @@ public final class DatabaseQueue {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
|
||||
/// Free as much memory as possible.
|
||||
///
|
||||
/// This method blocks the current thread until all database accesses are completed.
|
||||
@@ -124,7 +131,6 @@ public final class DatabaseQueue {
|
||||
inDatabase { $0.releaseMemory() }
|
||||
}
|
||||
|
||||
|
||||
#if os(iOS)
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
@@ -140,8 +146,6 @@ public final class DatabaseQueue {
|
||||
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
|
||||
}
|
||||
|
||||
private var application: UIApplication?
|
||||
|
||||
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = application else {
|
||||
return
|
||||
@@ -168,37 +172,13 @@ public final class DatabaseQueue {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
// https://www.sqlite.org/isolation.html
|
||||
//
|
||||
// > Within a single database connection X, a SELECT statement always
|
||||
// > sees all changes to the database that are completed prior to the
|
||||
// > start of the SELECT statement, whether committed or uncommitted.
|
||||
// > And the SELECT statement obviously does not see any changes that
|
||||
// > occur after the SELECT statement completes. But what about changes
|
||||
// > that occur while the SELECT statement is running? What if a SELECT
|
||||
// > statement is started and the sqlite3_step() interface steps through
|
||||
// > roughly half of its output, then some UPDATE statements are run by
|
||||
// > the application that modify the table that the SELECT statement is
|
||||
// > reading, then more calls to sqlite3_step() are made to finish out
|
||||
// > the SELECT statement? Will the later steps of the SELECT statement
|
||||
// > see the changes made by the UPDATE or not? The answer is that this
|
||||
// > behavior is undefined.
|
||||
//
|
||||
// This is why we use a serialized database:
|
||||
fileprivate var serializedDatabase: SerializedDatabase
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - Encryption
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabaseQueue {
|
||||
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Changes the passphrase of an encrypted database
|
||||
public func change(passphrase: String) throws {
|
||||
try inDatabase { try $0.change(passphrase: passphrase) }
|
||||
@@ -206,19 +186,15 @@ public final class DatabaseQueue {
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseReader
|
||||
|
||||
extension DatabaseQueue : DatabaseReader {
|
||||
|
||||
// MARK: - DatabaseReader Protocol Adoption
|
||||
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// let persons = try dbQueue.read { db in
|
||||
/// try Person.fetchAll(...)
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// try Player.fetchAll(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
@@ -248,6 +224,18 @@ extension DatabaseQueue : DatabaseReader {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// try dbQueue.unsafeReentrantRead { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
@@ -272,7 +260,6 @@ extension DatabaseQueue : DatabaseReader {
|
||||
inDatabase { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
@@ -294,14 +281,10 @@ extension DatabaseQueue : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseWriter
|
||||
|
||||
extension DatabaseQueue : DatabaseWriter {
|
||||
|
||||
// MARK: - DatabaseWriter Protocol Adoption
|
||||
|
||||
|
||||
/// Alias for `inDatabase`. See `DatabaseWriter.write`.
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try inDatabase(block)
|
||||
@@ -332,7 +315,7 @@ extension DatabaseQueue : DatabaseWriter {
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let persons = try dbQueue.unsafeReentrantWrite { db in
|
||||
/// try dbQueue.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
@@ -343,19 +326,13 @@ extension DatabaseQueue : DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
// Wraps the block between two `PRAGMA query_only` statements.
|
||||
//
|
||||
// This method is unsafe because the two calls to `PRAGMA query_only` are
|
||||
// not guaranteed to be serialized (some other thread could mess with this).
|
||||
private func readOnly<T>(_ db: Database, _ block: (Database) throws -> T) rethrows -> T {
|
||||
if db.configuration.readonly {
|
||||
guard !db.configuration.readonly else {
|
||||
return try block(db)
|
||||
} else {
|
||||
try! db.execute("PRAGMA query_only = 1") // Assume can't fail
|
||||
let result = try block(db)
|
||||
try! db.execute("PRAGMA query_only = 0") // Assume can't fail
|
||||
return result
|
||||
}
|
||||
|
||||
// Assume those pragmas never fail
|
||||
try! db.execute("PRAGMA query_only = 1")
|
||||
defer { try! db.execute("PRAGMA query_only = 0") }
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// The protocol for all types that can fetch values from a database.
|
||||
@@ -79,6 +81,40 @@ public protocol DatabaseReader : class {
|
||||
/// happen while establishing the read access to the database.
|
||||
func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// The two guarantees of the safe `read` method are lifted:
|
||||
///
|
||||
/// The block argument is not isolated: eventual concurrent database updates
|
||||
/// are visible inside the block:
|
||||
///
|
||||
/// 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")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iterations are isolated, though:
|
||||
///
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// The block argument is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `unsafeReentrantRead`).
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
@@ -172,3 +208,50 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased DatabaseReader
|
||||
///
|
||||
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
|
||||
/// underlying database reader.
|
||||
public final class AnyDatabaseReader : DatabaseReader {
|
||||
private let base: DatabaseReader
|
||||
|
||||
/// Creates a database reader that wraps a base database reader.
|
||||
public init(_ base: DatabaseReader) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.read(block)
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeRead(block)
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
}
|
||||
|
||||
public func remove(function: DatabaseFunction) {
|
||||
base.remove(function: function)
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
public func add(collation: DatabaseCollation) {
|
||||
base.add(collation: collation)
|
||||
}
|
||||
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@
|
||||
protocol DatabaseSchemaCache {
|
||||
mutating func clear()
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo??
|
||||
mutating func set(primaryKey: PrimaryKeyInfo?, forTable table: String)
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?
|
||||
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String)
|
||||
|
||||
func columns(in table: String) -> [ColumnInfo]?
|
||||
mutating func set(columns: [ColumnInfo], forTable table: String)
|
||||
@@ -22,7 +22,7 @@ protocol DatabaseSchemaCache {
|
||||
|
||||
/// A thread-unsafe database schema cache
|
||||
final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
private var primaryKeys: [String: PrimaryKeyInfo?] = [:]
|
||||
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
|
||||
private var columns: [String: [ColumnInfo]] = [:]
|
||||
private var indexes: [String: [IndexInfo]] = [:]
|
||||
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
|
||||
@@ -34,11 +34,11 @@ final class SimpleDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
foreignKeys = [:]
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?? {
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
return primaryKeys[table]
|
||||
}
|
||||
|
||||
func set(primaryKey: PrimaryKeyInfo?, forTable table: String) {
|
||||
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
|
||||
primaryKeys[table] = primaryKey
|
||||
}
|
||||
|
||||
@@ -75,11 +75,11 @@ final class SharedDatabaseSchemaCache: DatabaseSchemaCache {
|
||||
cache.write { $0.clear() }
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo?? {
|
||||
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
|
||||
return cache.read { $0.primaryKey(table) }
|
||||
}
|
||||
|
||||
func set(primaryKey: PrimaryKeyInfo?, forTable table: String) {
|
||||
func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
|
||||
cache.write { $0.set(primaryKey: primaryKey, forTable: table) }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValue
|
||||
@@ -10,6 +11,11 @@ import Foundation
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html
|
||||
public struct DatabaseValue {
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
/// The NULL DatabaseValue.
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
|
||||
public enum Storage : Equatable {
|
||||
@@ -61,12 +67,6 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
/// The NULL DatabaseValue.
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// Creates a DatabaseValue from Any.
|
||||
///
|
||||
/// The result is nil unless object adopts DatabaseValueConvertible.
|
||||
@@ -77,7 +77,6 @@ public struct DatabaseValue {
|
||||
self = convertible.databaseValue
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Extracting Value
|
||||
|
||||
/// Returns true if databaseValue is NULL.
|
||||
@@ -90,13 +89,9 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
init(storage: Storage) {
|
||||
// This initializer is not public because Storage is not a safe type:
|
||||
// one can create a Storage of zero-length Data, which is invalid
|
||||
// because SQLite can't store zero-length blobs.
|
||||
self.storage = storage
|
||||
}
|
||||
|
||||
@@ -112,9 +107,12 @@ public struct DatabaseValue {
|
||||
case SQLITE_TEXT:
|
||||
storage = .string(String(cString: sqlite3_value_text(sqliteValue)!))
|
||||
case SQLITE_BLOB:
|
||||
let bytes = unsafeBitCast(sqlite3_value_blob(sqliteValue), to: UnsafePointer<UInt8>.self)
|
||||
let count = Int(sqlite3_value_bytes(sqliteValue))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
if let bytes = sqlite3_value_blob(sqliteValue) {
|
||||
let count = Int(sqlite3_value_bytes(sqliteValue))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
} else {
|
||||
storage = .blob(Data())
|
||||
}
|
||||
case let type:
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError("Unexpected SQLite value type: \(type)")
|
||||
@@ -133,9 +131,12 @@ public struct DatabaseValue {
|
||||
case SQLITE_TEXT:
|
||||
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, Int32(index))))
|
||||
case SQLITE_BLOB:
|
||||
let bytes = unsafeBitCast(sqlite3_column_blob(sqliteStatement, Int32(index)), to: UnsafePointer<UInt8>.self)
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
storage = .blob(Data(bytes: bytes, count: count)) // copy bytes
|
||||
} else {
|
||||
storage = .blob(Data())
|
||||
}
|
||||
case let type:
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError("Unexpected SQLite column type: \(type)")
|
||||
@@ -143,10 +144,8 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Hashable & Equatable
|
||||
|
||||
/// DatabaseValue adopts Hashable.
|
||||
extension DatabaseValue : Hashable {
|
||||
|
||||
/// The hash value
|
||||
@@ -190,9 +189,9 @@ extension DatabaseValue : Hashable {
|
||||
case (.double(let lhs), .double(let rhs)):
|
||||
return lhs == rhs
|
||||
case (.int64(let lhs), .double(let rhs)):
|
||||
return int64EqualDouble(lhs, rhs)
|
||||
return Int64(exactly: rhs) == lhs
|
||||
case (.double(let lhs), .int64(let rhs)):
|
||||
return int64EqualDouble(rhs, lhs)
|
||||
return rhs == Int64(exactly: lhs)
|
||||
case (.string(let lhs), .string(let rhs)):
|
||||
return lhs == rhs
|
||||
case (.blob(let lhs), .blob(let rhs)):
|
||||
@@ -203,17 +202,6 @@ extension DatabaseValue : Hashable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if i and d hold exactly the same value, and if converting one
|
||||
/// type to the other does not lose any information.
|
||||
private func int64EqualDouble(_ i: Int64, _ d: Double) -> Bool {
|
||||
// See http://stackoverflow.com/questions/33719132/how-to-test-for-lossless-double-integer-conversion/33784296#33784296
|
||||
return (d >= Double(Int64.min))
|
||||
&& (d < Double(Int64.max))
|
||||
&& (round(d) == d)
|
||||
&& (i == Int64(d))
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Lossless conversions
|
||||
|
||||
extension DatabaseValue {
|
||||
@@ -292,10 +280,6 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DatabaseValueConvertible & SQLExpressible & SQLExpression
|
||||
|
||||
/// DatabaseValue adopts DatabaseValueConvertible.
|
||||
extension DatabaseValue : DatabaseValueConvertible {
|
||||
/// Returns self
|
||||
public var databaseValue: DatabaseValue {
|
||||
@@ -309,14 +293,12 @@ extension DatabaseValue : DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
extension DatabaseValue : SQLExpressible {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var sqlExpression: SQLExpression {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValue adopts SQLExpression.
|
||||
extension DatabaseValue : SQLExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
@@ -361,11 +343,7 @@ extension DatabaseValue : SQLExpression {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CustomStringConvertible
|
||||
|
||||
/// DatabaseValue adopts CustomStringConvertible.
|
||||
extension DatabaseValue : CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
switch storage {
|
||||
case .null:
|
||||
|
||||
@@ -1,3 +1,9 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - DatabaseValueConvertible
|
||||
|
||||
/// Types that adopt DatabaseValueConvertible can be initialized from
|
||||
@@ -6,12 +12,12 @@
|
||||
/// The protocol comes with built-in methods that allow to fetch cursors,
|
||||
/// arrays, or single values:
|
||||
///
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String>
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // DatabaseCursor<String>
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String?
|
||||
///
|
||||
@@ -24,38 +30,112 @@ public protocol DatabaseValueConvertible : SQLExpressible {
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
|
||||
}
|
||||
|
||||
// SQLExpressible adoption
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public var sqlExpression: SQLExpression {
|
||||
return databaseValue
|
||||
}
|
||||
}
|
||||
|
||||
/// 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")
|
||||
/// while let url = urls.next() { // URL
|
||||
/// print(url)
|
||||
/// }
|
||||
/// }
|
||||
public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
public func next() throws -> Value? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
return dbValue.losslessConvert() as Value
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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")
|
||||
/// while let url = urls.next() { // URL?
|
||||
/// print(url)
|
||||
/// }
|
||||
/// }
|
||||
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
public func next() throws -> Value?? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
return dbValue.losslessConvert() as Value?
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
|
||||
/// cursors, arrays, or single values:
|
||||
///
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String>
|
||||
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // DatabaseCursor<String>
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // DatabaseCursor<String>
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -71,13 +151,8 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.cursor(arguments: arguments, next: {
|
||||
let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Self
|
||||
})
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
|
||||
return try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
@@ -110,12 +185,8 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
let cursor: DatabaseCursor<Self?> = statement.cursor(arguments: arguments, next: {
|
||||
let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Self?
|
||||
})
|
||||
// fetchOne returns nil if there is no row, or if there is a row with a null value
|
||||
let cursor = try NullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
|
||||
return try cursor.next() ?? nil
|
||||
}
|
||||
}
|
||||
@@ -127,8 +198,8 @@ extension DatabaseValueConvertible {
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // DatabaseCursor<String>
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// for let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -143,7 +214,7 @@ extension DatabaseValueConvertible {
|
||||
/// - 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 -> DatabaseCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseValueCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
@@ -151,7 +222,7 @@ extension DatabaseValueConvertible {
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -167,7 +238,7 @@ extension DatabaseValueConvertible {
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -184,7 +255,7 @@ extension DatabaseValueConvertible {
|
||||
|
||||
/// Returns a cursor over values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String>
|
||||
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
|
||||
/// while let name = try name.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -201,7 +272,7 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -243,11 +314,11 @@ extension DatabaseValueConvertible {
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch cursors
|
||||
/// and arrays of optional DatabaseValueConvertible:
|
||||
///
|
||||
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // DatabaseCursor<String?>
|
||||
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // DatabaseCursor<String?>
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
@@ -258,7 +329,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // DatabaseCursor<String?>
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
@@ -274,13 +345,8 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.cursor(arguments: arguments, next: {
|
||||
let dbValue: DatabaseValue = row.value(atIndex: 0)
|
||||
return dbValue.losslessConvert(sql: statement.sql, arguments: arguments) as Wrapped?
|
||||
})
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
return try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
@@ -306,8 +372,8 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // DatabaseCursor<String?>
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
@@ -322,7 +388,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - 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 -> DatabaseCursor<Wrapped?> {
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableDatabaseValueCursor<Wrapped> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
@@ -330,7 +396,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -347,7 +413,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a cursor over optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String?>
|
||||
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
@@ -364,7 +430,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Wrapped?> {
|
||||
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))
|
||||
}
|
||||
|
||||
|
||||
@@ -53,12 +53,12 @@ public protocol DatabaseWriter : DatabaseReader {
|
||||
/// state is the last committed state.
|
||||
///
|
||||
/// try writer.write { db in
|
||||
/// try db.execute("DELETE FROM persons")
|
||||
/// try db.execute("DELETE FROM players")
|
||||
/// try writer.readFromCurrentState { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
|
||||
/// }
|
||||
/// try db.execute("INSERT INTO persons ...")
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// }
|
||||
///
|
||||
/// - When this method is called inside an uncommitted transation, the
|
||||
@@ -71,12 +71,12 @@ public protocol DatabaseWriter : DatabaseReader {
|
||||
/// the database in its last committed state.
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.execute("DELETE FROM persons")
|
||||
/// try db.execute("DELETE FROM players")
|
||||
/// db.inTransaction {
|
||||
/// try db.execute("INSERT INTO persons ...")
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// try dbPool.readFromCurrentState { db in
|
||||
/// // Zero
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
|
||||
/// }
|
||||
/// return .commit
|
||||
/// }
|
||||
@@ -88,12 +88,12 @@ public protocol DatabaseWriter : DatabaseReader {
|
||||
/// is run after the select.
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute("DELETE FROM persons")
|
||||
/// try db.execute("DELETE FROM players")
|
||||
/// db.inTransaction {
|
||||
/// try db.execute("INSERT INTO persons ...")
|
||||
/// try db.execute("INSERT INTO players ...")
|
||||
/// try dbQueue.readFromCurrentState { db in
|
||||
/// // One
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
|
||||
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")!
|
||||
/// }
|
||||
/// return .commit
|
||||
/// }
|
||||
@@ -123,3 +123,64 @@ extension DatabaseWriter {
|
||||
write { $0.remove(transactionObserver: transactionObserver) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased DatabaseWriter
|
||||
///
|
||||
/// Instances of AnyDatabaseWriter forward their methods to an arbitrary
|
||||
/// underlying database writer.
|
||||
public final class AnyDatabaseWriter : DatabaseWriter {
|
||||
private let base: DatabaseWriter
|
||||
|
||||
/// Creates a database writer that wraps a base database writer.
|
||||
public init(_ base: DatabaseWriter) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.read(block)
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeRead(block)
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
|
||||
try base.readFromCurrentState(block)
|
||||
}
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try base.write(block)
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try base.unsafeReentrantWrite(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
}
|
||||
|
||||
public func remove(function: DatabaseFunction) {
|
||||
base.remove(function: function)
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
public func add(collation: DatabaseCollation) {
|
||||
base.add(collation: collation)
|
||||
}
|
||||
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
}
|
||||
+107
-43
@@ -4,9 +4,9 @@
|
||||
/// value, record):
|
||||
///
|
||||
/// let request: Request = ...
|
||||
/// try Row.fetchCursor(db, request) // DatabaseCursor<Row>
|
||||
/// try Row.fetchCursor(db, request) // RowCursor
|
||||
/// try String.fetchAll(db, request) // [String]
|
||||
/// try Person.fetchOne(db, request) // Person?
|
||||
/// 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.
|
||||
@@ -36,6 +36,18 @@ extension Request {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
extension Request {
|
||||
@@ -44,10 +56,10 @@ extension Request {
|
||||
/// The returned request can fetch if the type T is fetchable (Row,
|
||||
/// value, record).
|
||||
///
|
||||
/// // minHeight in Double?
|
||||
/// let minHeight = Person
|
||||
/// .select(min(heightColumn))
|
||||
/// .asRequest(of: Double.self) // <--
|
||||
/// // Int?
|
||||
/// let maxScore = Player
|
||||
/// .select(max(scoreColumn))
|
||||
/// .asRequest(of: Int.self) // <--
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// - parameter type: The fetched type T
|
||||
@@ -126,11 +138,16 @@ public struct AnyRequest : Request {
|
||||
|
||||
/// 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 persons")
|
||||
/// let request = SQLRequest("SELECT * FROM persons WHERE id = ?", arguments: [1])
|
||||
/// let request = SQLRequest("SELECT * FROM players")
|
||||
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
@@ -140,14 +157,14 @@ public struct SQLRequest : Request {
|
||||
/// 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 ? .user : nil)
|
||||
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 persons")
|
||||
/// let request = SQLRequest("SELECT * FROM persons WHERE id = ?", arguments: [1])
|
||||
/// let request = SQLRequest("SELECT * FROM players")
|
||||
/// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
@@ -155,11 +172,11 @@ public struct SQLRequest : Request {
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - statementCacheName: Optional statement cache name.
|
||||
/// - returns: A SQLRequest
|
||||
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache statementCacheName: Database.StatementCacheName?) {
|
||||
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
|
||||
self.sql = sql
|
||||
self.arguments = arguments
|
||||
self.adapter = adapter
|
||||
self.statementCacheName = statementCacheName
|
||||
self.cache = cache
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
@@ -168,10 +185,13 @@ public struct SQLRequest : Request {
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let statement: SelectStatement
|
||||
if let statementCacheName = statementCacheName {
|
||||
statement = try db.selectStatement(sql, fromCache: statementCacheName)
|
||||
} else {
|
||||
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)
|
||||
@@ -179,10 +199,17 @@ public struct SQLRequest : Request {
|
||||
return (statement, adapter)
|
||||
}
|
||||
|
||||
private let sql: String
|
||||
private let arguments: StatementArguments?
|
||||
private let adapter: RowAdapter?
|
||||
private let statementCacheName: Database.StatementCacheName?
|
||||
/// 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.
|
||||
@@ -190,11 +217,11 @@ public struct SQLRequest : Request {
|
||||
/// Typed requests can fetch if their associated type RowDecoder is able to
|
||||
/// decode rows (Row, value, record)
|
||||
///
|
||||
/// struct Person: RowConvertible { ... }
|
||||
/// let request: ... // Some TypedRequest that fetches Person
|
||||
/// try request.fetchCursor(db) // DatabaseCursor<Person>
|
||||
/// try request.fetchAll(db) // [Person]
|
||||
/// try request.fetchOne(db) // Person?
|
||||
/// 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
|
||||
@@ -276,9 +303,9 @@ extension TypedRequest where RowDecoder: RowConvertible {
|
||||
|
||||
/// A cursor over fetched records.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Person
|
||||
/// let persons = try request.fetchCursor(db) // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() { // Person
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// let players = try request.fetchCursor(db) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
@@ -290,14 +317,14 @@ extension TypedRequest where RowDecoder: RowConvertible {
|
||||
/// - 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 -> DatabaseCursor<RowDecoder> {
|
||||
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 Person
|
||||
/// let persons = try request.fetchAll(db) // [Person]
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// let players = try request.fetchAll(db) // [Player]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of records.
|
||||
@@ -308,8 +335,8 @@ extension TypedRequest where RowDecoder: RowConvertible {
|
||||
|
||||
/// The first fetched record.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Person
|
||||
/// let person = try request.fetchOne(db) // Person?
|
||||
/// let request: ... // Some TypedRequest that fetches Player
|
||||
/// let player = try request.fetchOne(db) // Player?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional record.
|
||||
@@ -326,7 +353,7 @@ extension TypedRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // DatabaseCursor<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -339,7 +366,7 @@ extension TypedRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// - 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 -> DatabaseCursor<RowDecoder> {
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
@@ -378,7 +405,7 @@ extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches String
|
||||
/// let strings = try request.fetchCursor(db) // DatabaseCursor<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -391,7 +418,7 @@ extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// - 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 -> DatabaseCursor<RowDecoder> {
|
||||
public func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder> {
|
||||
return try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
@@ -430,7 +457,7 @@ extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // DatabaseCursor<String?>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
@@ -443,7 +470,7 @@ extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
|
||||
/// - 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 -> DatabaseCursor<RowDecoder._Wrapped?> {
|
||||
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped> {
|
||||
return try Optional<RowDecoder._Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
@@ -460,6 +487,43 @@ extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
@@ -467,10 +531,10 @@ extension TypedRequest where RowDecoder: Row {
|
||||
/// A cursor over fetched rows.
|
||||
///
|
||||
/// let request: ... // Some TypedRequest that fetches Row
|
||||
/// let rows = try request.fetchCursor(db) // DatabaseCursor<Row>
|
||||
/// let rows = try request.fetchCursor(db) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row.value(atIndex: 0)
|
||||
/// let name: String = row.value(atIndex: 1)
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
@@ -489,7 +553,7 @@ extension TypedRequest where RowDecoder: Row {
|
||||
/// - 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 -> DatabaseCursor<Row> {
|
||||
public func fetchCursor(_ db: Database) throws -> RowCursor {
|
||||
return try Row.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
|
||||
+121
-95
@@ -1,12 +1,30 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A database row.
|
||||
public final class Row {
|
||||
let impl: RowImpl
|
||||
|
||||
/// Unless we are producing a row array, we use a single row when iterating
|
||||
/// a statement:
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// let players = try Player.fetchAll(db, "SELECT ...")
|
||||
///
|
||||
/// This row keeps an unmanaged reference to the statement, and a handle to
|
||||
/// the sqlite statement, so that we avoid many retain/release invocations.
|
||||
///
|
||||
/// The statementRef is released in deinit.
|
||||
let statementRef: Unmanaged<SelectStatement>?
|
||||
let sqliteStatement: SQLiteStatement?
|
||||
|
||||
/// The number of columns in the row.
|
||||
public let count: Int
|
||||
|
||||
// MARK: - Building rows
|
||||
|
||||
/// Creates an empty row.
|
||||
@@ -48,26 +66,11 @@ public final class Row {
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
let impl: RowImpl
|
||||
|
||||
/// Returns true if and only if the row was fetched from a database.
|
||||
var isFetched: Bool {
|
||||
return impl.isFetched
|
||||
}
|
||||
|
||||
/// Unless we are producing a row array, we use a single row when iterating
|
||||
/// a statement:
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// let persons = try Person.fetchAll(db, "SELECT ...")
|
||||
///
|
||||
/// This row keeps an unmanaged reference to the statement, and a handle to
|
||||
/// the sqlite statement, so that we avoid many retain/release invocations.
|
||||
///
|
||||
/// The statementRef is released in deinit.
|
||||
let statementRef: Unmanaged<SelectStatement>?
|
||||
let sqliteStatement: SQLiteStatement?
|
||||
|
||||
deinit {
|
||||
statementRef?.release()
|
||||
}
|
||||
@@ -83,6 +86,7 @@ public final class Row {
|
||||
self.statementRef = statementRef
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statementRef: statementRef)
|
||||
self.count = Int(sqlite3_column_count(sqliteStatement))
|
||||
}
|
||||
|
||||
/// Creates a row that contain a copy of the current state of the
|
||||
@@ -95,17 +99,9 @@ public final class Row {
|
||||
self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: statementRef.takeUnretainedValue().columnNames))
|
||||
}
|
||||
|
||||
/// Creates a row from the *current state* of the SQLite statement.
|
||||
///
|
||||
/// The row is implemented on top of StatementCopyRowImpl, which *copies*
|
||||
/// the values from the SQLite statement so that further iteration of the
|
||||
/// statement does not modify the row.
|
||||
convenience init(copiedFromSQLiteStatement sqliteStatement: SQLiteStatement, columnNames: [String]) {
|
||||
self.init(impl: StatementCopyRowImpl(sqliteStatement: sqliteStatement, columnNames: columnNames))
|
||||
}
|
||||
|
||||
init(impl: RowImpl) {
|
||||
self.impl = impl
|
||||
self.count = impl.count
|
||||
self.statementRef = nil
|
||||
self.sqliteStatement = nil
|
||||
}
|
||||
@@ -140,7 +136,7 @@ extension Row {
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
public func value(atIndex index: Int) -> DatabaseValueConvertible? {
|
||||
public subscript(_ index: Int) -> DatabaseValueConvertible? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.databaseValue(atUncheckedIndex: index).storage.value
|
||||
}
|
||||
@@ -153,7 +149,7 @@ extension Row {
|
||||
/// 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 func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value? {
|
||||
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
@@ -170,12 +166,12 @@ 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 func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(atIndex index: Int) -> Value? {
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value? {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
guard let sqliteStatement = sqliteStatement else {
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
if let sqliteStatement = sqliteStatement { // fast path
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
|
||||
}
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
@@ -185,7 +181,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 func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value {
|
||||
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
@@ -201,12 +197,12 @@ 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 func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(atIndex index: Int) -> Value {
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
|
||||
GRDBPrecondition(index >= 0 && index < count, "row index out of range")
|
||||
guard let sqliteStatement = sqliteStatement else {
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
if let sqliteStatement = sqliteStatement { // fast path
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
|
||||
}
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil, depending on the value
|
||||
@@ -216,12 +212,12 @@ extension Row {
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// The result is nil if the row does not contain the column.
|
||||
public func value(named columnName: String) -> DatabaseValueConvertible? {
|
||||
public subscript(_ columnName: String) -> DatabaseValueConvertible? {
|
||||
// IMPLEMENTATION NOTE
|
||||
// This method has a single know use case: checking if the value is nil,
|
||||
// as in:
|
||||
//
|
||||
// if row.value(named: "foo") != nil { ... }
|
||||
// if row["foo"] != nil { ... }
|
||||
//
|
||||
// Without this method, the code above would not compile.
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
@@ -238,7 +234,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 func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value? {
|
||||
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value? {
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
@@ -257,14 +253,14 @@ 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 func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(named columnName: String) -> Value? {
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value? {
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
guard let sqliteStatement = sqliteStatement else {
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
if let sqliteStatement = sqliteStatement { // fast path
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
|
||||
}
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -276,7 +272,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 func value<Value: DatabaseValueConvertible>(named columnName: String) -> Value {
|
||||
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
// Programmer error
|
||||
fatalError("no such column: \(columnName)")
|
||||
@@ -297,15 +293,15 @@ 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 func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(named columnName: String) -> Value {
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
|
||||
guard let index = impl.index(ofColumn: columnName) else {
|
||||
// Programmer error
|
||||
// Programmer error
|
||||
fatalError("no such column: \(columnName)")
|
||||
}
|
||||
guard let sqliteStatement = sqliteStatement else {
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
if let sqliteStatement = sqliteStatement { // fast path
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: Int32(index), in: sqliteStatement)
|
||||
}
|
||||
return Row.statementColumnConvertible(atUncheckedIndex: index, in: sqliteStatement)
|
||||
return impl.databaseValue(atUncheckedIndex: index).losslessConvert()
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, NSData or nil, depending on the value
|
||||
@@ -315,8 +311,8 @@ extension Row {
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// The result is nil if the row does not contain the column.
|
||||
public func value(_ column: Column) -> DatabaseValueConvertible? {
|
||||
return value(named: column.name)
|
||||
public subscript(_ column: Column) -> DatabaseValueConvertible? {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -327,8 +323,8 @@ 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 func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value? {
|
||||
return value(named: column.name)
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value? {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -343,8 +339,8 @@ 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 func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value? {
|
||||
return value(named: column.name)
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value? {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -356,8 +352,8 @@ extension Row {
|
||||
///
|
||||
/// This method crashes if the fetched SQLite value is NULL, or if the
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value {
|
||||
return value(named: column.name)
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: Column) -> Value {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -373,8 +369,8 @@ 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 func value<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value {
|
||||
return value(named: column.name)
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: Column) -> Value {
|
||||
return self[column.name]
|
||||
}
|
||||
|
||||
/// Returns the optional Data at given index.
|
||||
@@ -442,20 +438,21 @@ extension Row {
|
||||
extension Row {
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
fileprivate static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int, in sqliteStatement: SQLiteStatement) -> Value? {
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
@inline(__always)
|
||||
private static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int32, in sqliteStatement: SQLiteStatement) -> Value? {
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
|
||||
return nil
|
||||
}
|
||||
return Value.init(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
return Value.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
|
||||
fileprivate static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int, in sqliteStatement: SQLiteStatement) -> Value {
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
@inline(__always)
|
||||
private static func statementColumnConvertible<Value: StatementColumnConvertible>(atUncheckedIndex index: Int32, in sqliteStatement: SQLiteStatement) -> Value {
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
|
||||
// Programmer error
|
||||
fatalError("could not convert database value NULL to \(Value.self)")
|
||||
}
|
||||
return Value.init(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
return Value.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -481,16 +478,49 @@ extension Row {
|
||||
///
|
||||
/// // Scoped rows:
|
||||
/// if let fooRow = row.scoped(on: "foo") {
|
||||
/// fooRow.value(named: "value") // "foo"
|
||||
/// fooRow["value"] // "foo"
|
||||
/// }
|
||||
/// if let barRow = row.scopeed(on: "bar") {
|
||||
/// barRow.value(named: "value") // "bar"
|
||||
/// barRow["value"] // "bar"
|
||||
/// }
|
||||
public func scoped(on name: String) -> Row? {
|
||||
return impl.scoped(on: name)
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of database rows. For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM players")
|
||||
/// }
|
||||
public final class RowCursor : Cursor {
|
||||
public let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let row: Row // Reused for performance
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
self.row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
public func next() throws -> Row? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return row
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Fetching From SelectStatement
|
||||
@@ -498,10 +528,10 @@ extension Row {
|
||||
/// Returns a cursor over rows fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT ...")
|
||||
/// let rows = try Row.fetchCursor(statement) // DatabaseCursor<Row>
|
||||
/// let rows = try Row.fetchCursor(statement) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row.value(atIndex: 0)
|
||||
/// let name: String = row.value(atIndex: 1)
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
@@ -524,10 +554,8 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Row> {
|
||||
// Reuse a single mutable row for performance
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.cursor(arguments: arguments, next: { row })
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor {
|
||||
return try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of rows fetched from a prepared statement.
|
||||
@@ -571,11 +599,11 @@ extension Row {
|
||||
///
|
||||
/// let idColumn = Column("id")
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(idColumn, nameColumn)
|
||||
/// let rows = try Row.fetchCursor(db) // DatabaseCursor<Row>
|
||||
/// let request = Player.select(idColumn, nameColumn)
|
||||
/// let rows = try Row.fetchCursor(db) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row.value(atIndex: 0)
|
||||
/// let name: String = row.value(atIndex: 1)
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
@@ -596,7 +624,7 @@ extension Row {
|
||||
/// - 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 -> DatabaseCursor<Row> {
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> RowCursor {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
@@ -605,7 +633,7 @@ extension Row {
|
||||
///
|
||||
/// let idColumn = Column("id")
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(idColumn, nameColumn)
|
||||
/// let request = Player.select(idColumn, nameColumn)
|
||||
/// let rows = try Row.fetchAll(db, request)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -619,7 +647,7 @@ extension Row {
|
||||
///
|
||||
/// let idColumn = Column("id")
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(idColumn, nameColumn)
|
||||
/// let request = Player.select(idColumn, nameColumn)
|
||||
/// let row = try Row.fetchOne(db, request)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -636,10 +664,10 @@ extension Row {
|
||||
|
||||
/// Returns a cursor over rows fetched from an SQL query.
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT id, name FROM persons") // DatabaseCursor<Row>
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT id, name FROM players") // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row.value(atIndex: 0)
|
||||
/// let name: String = row.value(atIndex: 1)
|
||||
/// let id: Int64 = row[0]
|
||||
/// let name: String = row[1]
|
||||
/// }
|
||||
///
|
||||
/// Fetched rows are reused during the cursor iteration: don't turn a row
|
||||
@@ -662,7 +690,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Row> {
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -714,11 +742,6 @@ extension Row : Collection {
|
||||
|
||||
// MARK: - Row as a Collection of (ColumnName, DatabaseValue) Pairs
|
||||
|
||||
/// The number of columns in the row.
|
||||
public var count: Int {
|
||||
return impl.count
|
||||
}
|
||||
|
||||
/// The index of the first (ColumnName, DatabaseValue) pair.
|
||||
public var startIndex: RowIndex {
|
||||
return Index(0)
|
||||
@@ -807,7 +830,6 @@ extension Row : Hashable {
|
||||
|
||||
/// Row adopts CustomStringConvertible.
|
||||
extension Row: CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
return "<Row"
|
||||
+ map { (column, dbValue) in
|
||||
@@ -969,9 +991,13 @@ private struct StatementRowImpl : RowImpl {
|
||||
init(sqliteStatement: SQLiteStatement, statementRef: Unmanaged<SelectStatement>) {
|
||||
self.statementRef = statementRef
|
||||
self.sqliteStatement = sqliteStatement
|
||||
// Optimize row.value(named: "...")
|
||||
// Optimize row["..."]
|
||||
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement)).map { String(cString: sqlite3_column_name(sqliteStatement, Int32($0))).lowercased() }
|
||||
self.lowercaseColumnIndexes = Dictionary(keyValueSequence: lowercaseColumnNames.enumerated().map { ($1, $0) }.reversed())
|
||||
self.lowercaseColumnIndexes = Dictionary(
|
||||
lowercaseColumnNames
|
||||
.enumerated()
|
||||
.map { ($0.element, $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}
|
||||
|
||||
var count: Int {
|
||||
@@ -987,7 +1013,7 @@ private struct StatementRowImpl : RowImpl {
|
||||
return nil
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
return nil
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
|
||||
@@ -39,10 +39,11 @@ public struct LayoutedColumnMapping {
|
||||
/// 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)
|
||||
self.lowercaseColumnIndexes = Dictionary(keyValueSequence: layoutColumns
|
||||
.enumerated()
|
||||
.map { ($1.1.lowercased(), $0) }
|
||||
.reversed()) // reversed() so that the the dictionary caches leftmost indexes
|
||||
self.lowercaseColumnIndexes = Dictionary(
|
||||
layoutColumns
|
||||
.enumerated()
|
||||
.map { ($0.element.1.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}
|
||||
|
||||
func baseColumnIndex(atMappingIndex index: Int) -> Int {
|
||||
@@ -300,10 +301,10 @@ public struct RangeRowAdapter : RowAdapter {
|
||||
///
|
||||
/// // Scoped rows:
|
||||
/// if let fooRow = row.scoped(on: "foo") {
|
||||
/// fooRow.value(named: "value") // "foo"
|
||||
/// fooRow["value"] // "foo"
|
||||
/// }
|
||||
/// if let barRow = row.scopeed(on: "bar") {
|
||||
/// barRow.value(named: "value") // "bar"
|
||||
/// barRow["value"] // "bar"
|
||||
/// }
|
||||
public struct ScopeAdapter : RowAdapter {
|
||||
|
||||
@@ -390,7 +391,7 @@ struct AdapterRowImpl : RowImpl {
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
return base.value(atIndex: mapping.baseColumnIndex(atMappingIndex: index))
|
||||
return base[mapping.baseColumnIndex(atMappingIndex: index)]
|
||||
}
|
||||
|
||||
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import Dispatch
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// SchedulingWatchdog makes sure that databases connections are used on correct
|
||||
/// dispatch queues, and warns the user with a fatal error whenever she misuses
|
||||
/// a database connection.
|
||||
|
||||
@@ -149,14 +149,10 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an optional database connection. If not nil, the caller is
|
||||
/// executing on the serialized dispatch queue.
|
||||
var availableDatabaseConnection: Database? {
|
||||
guard let watchdog = SchedulingWatchdog.current else { return nil }
|
||||
guard watchdog.allows(db) else { return nil }
|
||||
return db
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
return SchedulingWatchdog.allows(db)
|
||||
}
|
||||
|
||||
|
||||
/// Executes the block in the current queue.
|
||||
///
|
||||
|
||||
+284
-187
@@ -1,12 +1,27 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A raw SQLite statement, suitable for the SQLite C API.
|
||||
public typealias SQLiteStatement = OpaquePointer
|
||||
|
||||
/// An error emitted when one tries to compile an empty statement.
|
||||
struct EmptyStatementError : Error {
|
||||
}
|
||||
|
||||
/// A common protocol for UpdateStatement and SelectStatement
|
||||
protocol AuthorizedStatement {
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
}
|
||||
|
||||
/// A statement represents an SQL query.
|
||||
///
|
||||
/// It is the base class of UpdateStatement that executes *update statements*,
|
||||
@@ -18,47 +33,60 @@ public class Statement {
|
||||
|
||||
/// The SQL query
|
||||
public var sql: String {
|
||||
// trim white space and semicolumn for homogeneous output
|
||||
return String(cString: sqlite3_sql(sqliteStatement))
|
||||
.trimmingCharacters(in: CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines))
|
||||
}
|
||||
|
||||
/// The database
|
||||
unowned let database: Database
|
||||
|
||||
init(database: Database, sqliteStatement: SQLiteStatement) {
|
||||
self.database = database
|
||||
self.sqliteStatement = sqliteStatement
|
||||
}
|
||||
|
||||
fileprivate init(database: Database, sql: String, observer: StatementCompilationObserver) throws {
|
||||
/// Creates a prepared statement.
|
||||
///
|
||||
/// - parameter database: A database connection.
|
||||
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
|
||||
/// containing SQL.
|
||||
/// - parameter statementEnd: Upon success, the pointer to the next
|
||||
/// statement in the C string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - throws: DatabaseError in case of compilation error, and
|
||||
/// EmptyStatementError if the compiled string is blank or empty.
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32) throws
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
observer.start()
|
||||
defer { observer.stop() }
|
||||
|
||||
let sqlCodeUnits = sql.utf8CString
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
var code: Int32 = 0
|
||||
var remainingSQL = ""
|
||||
sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
|
||||
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
|
||||
var sqlEnd: UnsafePointer<Int8>? = nil
|
||||
code = sqlite3_prepare_v2(database.sqliteConnection, sqlStart, -1, &sqliteStatement, &sqlEnd)
|
||||
let remainingData = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: sqlEnd!), count: sqlStart + sqlCodeUnits.count - sqlEnd! - 1, deallocator: .none)
|
||||
remainingSQL = String(data: remainingData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE
|
||||
let code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd)
|
||||
#else
|
||||
let code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
|
||||
#endif
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql)
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: String(cString: statementStart))
|
||||
}
|
||||
|
||||
guard remainingSQL.isEmpty else {
|
||||
sqlite3_finalize(sqliteStatement)
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.", sql: sql, arguments: nil)
|
||||
guard let statement = sqliteStatement else {
|
||||
// Sanity check: verify that the string contains only whitespace
|
||||
assert(String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: statementStart), count: statementEnd.pointee! - statementStart, deallocator: .none), encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
|
||||
// I wish we could simply return nil, and make this initializer failable.
|
||||
//
|
||||
// Unfortunately, there is a Swift bug with failable+throwing initializers:
|
||||
// https://bugs.swift.org/browse/SR-6067
|
||||
//
|
||||
// We thus use sentinel error for empty statements.
|
||||
throw EmptyStatementError()
|
||||
}
|
||||
|
||||
self.database = database
|
||||
self.sqliteStatement = sqliteStatement!
|
||||
|
||||
self.sqliteStatement = statement
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -92,7 +120,7 @@ public class Statement {
|
||||
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, Int32($0 + 1)) else {
|
||||
return nil
|
||||
}
|
||||
return String(String(cString: cString).characters.dropFirst()) // Drop initial ":", "@", "$"
|
||||
return String(String(cString: cString).dropFirst()) // Drop initial ":", "@", "$"
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -122,7 +150,7 @@ public class Statement {
|
||||
clearBindings()
|
||||
|
||||
var valuesIterator = arguments.values.makeIterator()
|
||||
for (index, argumentName) in sqliteArgumentNames.enumerated() {
|
||||
for (index, argumentName) in zip(Int32(1)..., sqliteArgumentNames) {
|
||||
if let argumentName = argumentName, let value = arguments.namedValues[argumentName] {
|
||||
bind(value, at: index)
|
||||
} else if let value = valuesIterator.next() {
|
||||
@@ -143,26 +171,26 @@ public class Statement {
|
||||
// Apply
|
||||
reset()
|
||||
clearBindings()
|
||||
for (index, dbValue) in bindings.enumerated() {
|
||||
for (index, dbValue) in zip(Int32(1)..., bindings) {
|
||||
bind(dbValue, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
// 0-based index
|
||||
private func bind(_ dbValue: DatabaseValue, at index: Int) {
|
||||
// 1-based index
|
||||
private func bind(_ dbValue: DatabaseValue, at index: Int32) {
|
||||
let code: Int32
|
||||
switch dbValue.storage {
|
||||
case .null:
|
||||
code = sqlite3_bind_null(sqliteStatement, Int32(index + 1))
|
||||
code = sqlite3_bind_null(sqliteStatement, index)
|
||||
case .int64(let int64):
|
||||
code = sqlite3_bind_int64(sqliteStatement, Int32(index + 1), int64)
|
||||
code = sqlite3_bind_int64(sqliteStatement, index, int64)
|
||||
case .double(let double):
|
||||
code = sqlite3_bind_double(sqliteStatement, Int32(index + 1), double)
|
||||
code = sqlite3_bind_double(sqliteStatement, index, double)
|
||||
case .string(let string):
|
||||
code = sqlite3_bind_text(sqliteStatement, Int32(index + 1), string, -1, SQLITE_TRANSIENT)
|
||||
code = sqlite3_bind_text(sqliteStatement, index, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
code = data.withUnsafeBytes { bytes in
|
||||
sqlite3_bind_blob(sqliteStatement, Int32(index + 1), bytes, Int32(data.count), SQLITE_TRANSIENT)
|
||||
sqlite3_bind_blob(sqliteStatement, index, bytes, Int32(data.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,11 +212,13 @@ public class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func prepare(withArguments arguments: StatementArguments?) throws {
|
||||
fileprivate func prepare(withArguments arguments: StatementArguments?) {
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
if let arguments = arguments {
|
||||
try setArgumentsWithValidation(arguments)
|
||||
try! setArgumentsWithValidation(arguments)
|
||||
} else if argumentsNeedValidation {
|
||||
try validate(arguments: self.arguments)
|
||||
try! validate(arguments: self.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -201,86 +231,118 @@ public class Statement {
|
||||
/// You create SelectStatement with the Database.makeSelectStatement() method:
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM persons WHERE age > ?")
|
||||
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
/// }
|
||||
public final class SelectStatement : Statement {
|
||||
public final class SelectStatement : Statement, AuthorizedStatement {
|
||||
/// Information about the table and columns read by a SelectStatement
|
||||
public private(set) var selectionInfo: SelectionInfo
|
||||
|
||||
init(database: Database, sql: String) throws {
|
||||
/// Creates a prepared statement.
|
||||
///
|
||||
/// - parameter database: A database connection.
|
||||
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
|
||||
/// containing SQL.
|
||||
/// - parameter statementEnd: Upon success, the pointer to the next
|
||||
/// statement in the C string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - authorizer: A StatementCompilationAuthorizer
|
||||
/// - throws: DatabaseError in case of compilation error, and
|
||||
/// EmptyStatementError if the compiled string is blank or empty.
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
self.selectionInfo = SelectionInfo()
|
||||
let observer = StatementCompilationObserver(database)
|
||||
try super.init(database: database, sql: sql, observer: observer)
|
||||
Database.preconditionValidSelectStatement(sql: sql, observer: observer)
|
||||
self.selectionInfo = observer.selectionInfo
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags)
|
||||
|
||||
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.selectionInfo = authorizer.selectionInfo
|
||||
}
|
||||
|
||||
/// The number of columns in the resulting rows.
|
||||
public lazy var columnCount: Int = {
|
||||
Int(sqlite3_column_count(self.sqliteStatement))
|
||||
}()
|
||||
public var columnCount: Int {
|
||||
return Int(sqlite3_column_count(self.sqliteStatement))
|
||||
}
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public lazy var columnNames: [String] = {
|
||||
let sqliteStatement = self.sqliteStatement
|
||||
return (0..<self.columnCount).map { (index: Int) -> String in String(cString: sqlite3_column_name(sqliteStatement, Int32(index))) }
|
||||
return (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
|
||||
/// Cache for indexOfColumn(). Keys are lowercase.
|
||||
/// Cache for index(ofColumn:). Keys are lowercase.
|
||||
private lazy var columnIndexes: [String: Int] = {
|
||||
return Dictionary(keyValueSequence: self.columnNames.enumerated().map { ($1.lowercased(), $0) }.reversed())
|
||||
return Dictionary(
|
||||
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}()
|
||||
|
||||
/// Returns the index of the leftmost column named `name`, in a
|
||||
/// case-insensitive way.
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
public func index(ofColumn name: String) -> Int? {
|
||||
return columnIndexes[name.lowercased()]
|
||||
}
|
||||
|
||||
/// Creates a DatabaseCursor
|
||||
func cursor<Element>(arguments: StatementArguments? = nil, next element: @escaping () throws -> Element) -> DatabaseCursor<Element> {
|
||||
// Check that cursor is built on a valid queue.
|
||||
SchedulingWatchdog.preconditionValidQueue(database, "Database was not used on the correct thread.")
|
||||
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
try! prepare(withArguments: arguments)
|
||||
|
||||
reset()
|
||||
return DatabaseCursor(statement: self, element: element)
|
||||
/// Creates a cursor over the statement. This cursor does not produce any
|
||||
/// value, and is only intended to give access to the sqlite3_step()
|
||||
/// low-level function.
|
||||
func cursor(arguments: StatementArguments? = nil) -> StatementCursor {
|
||||
return StatementCursor(statement: self, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Creates a cursor whose results are ignored
|
||||
func cursor(arguments: StatementArguments? = nil) -> DatabaseCursor<Void> {
|
||||
return cursor(arguments: arguments) { }
|
||||
/// Utility function for cursors
|
||||
func cursorReset(arguments: StatementArguments? = nil) {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
prepare(withArguments: arguments)
|
||||
reset()
|
||||
}
|
||||
|
||||
|
||||
/// Information about the table and columns read by a SelectStatement
|
||||
public struct SelectionInfo : CustomStringConvertible {
|
||||
mutating func insert(table: String) {
|
||||
/// Selection is unknown when a statement uses the COUNT function,
|
||||
/// and SQLite version < 3.19:
|
||||
///
|
||||
/// `SELECT COUNT(*) FROM t1` -> unknown selection
|
||||
private let isUnknown: Bool
|
||||
|
||||
/// `SELECT a, b FROM t1` -> ["t1": ["a", "b"]]
|
||||
private var columns: [String: Set<String>] = [:]
|
||||
|
||||
/// `SELECT COUNT(*) FROM t1` -> ["t1"]
|
||||
private var tables: Set<String> = []
|
||||
|
||||
/// The unknown selection
|
||||
static let unknown = SelectionInfo(isUnknown: true)
|
||||
|
||||
mutating func insert(allColumnsOfTable table: String) {
|
||||
tables.insert(table)
|
||||
}
|
||||
|
||||
mutating func insert(column: String, ofTable table: String) {
|
||||
if columns[table] != nil {
|
||||
columns[table]!.insert(column)
|
||||
} else {
|
||||
columns[table] = [column]
|
||||
}
|
||||
columns[table, default: []].insert(column)
|
||||
}
|
||||
|
||||
/// If true, selection is unknown
|
||||
let isUnknown: Bool
|
||||
|
||||
/// Relevant iff isUnknown is false
|
||||
/// Returns true if isUnknown is true
|
||||
func contains(anyColumnFrom table: String) -> Bool {
|
||||
if isUnknown { return true }
|
||||
return tables.contains(table) || columns.index(forKey: table) != nil
|
||||
}
|
||||
|
||||
/// Relevant iff isUnknown is false
|
||||
/// Returns true if isUnknown is true
|
||||
func contains(anyColumnIn columns: Set<String>, from table: String) -> Bool {
|
||||
if isUnknown { return true }
|
||||
return tables.contains(table) || !(self.columns[table]?.isDisjoint(with: columns) ?? true)
|
||||
}
|
||||
|
||||
@@ -288,64 +350,55 @@ public final class SelectStatement : Statement {
|
||||
self.init(isUnknown: false)
|
||||
}
|
||||
|
||||
static func unknown() -> SelectionInfo {
|
||||
return self.init(isUnknown: true)
|
||||
}
|
||||
|
||||
// `SELECT a, b FROM t1` -> ["t1": ["a", "b"]]
|
||||
private var columns: [String: Set<String>] = [:]
|
||||
|
||||
// `SELECT COUNT(*) FROM t1` -> ["t1"]
|
||||
private var tables: Set<String> = []
|
||||
|
||||
private init(isUnknown: Bool) {
|
||||
self.isUnknown = isUnknown
|
||||
}
|
||||
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
// TODO: include tables in the description
|
||||
return columns
|
||||
.sorted { $0.key < $1.key }
|
||||
.map { (table, columns) in "\(table)(\(columns.sorted().joined(separator: ", ")))" }
|
||||
.joined(separator: ", ")
|
||||
if isUnknown {
|
||||
return "unknown"
|
||||
}
|
||||
return tables.union(columns.keys)
|
||||
.sorted()
|
||||
.map { table -> String in
|
||||
if let columns = columns[table] {
|
||||
return "\(table)(\(columns.sorted().joined(separator: ",")))"
|
||||
} else {
|
||||
return "\(table)(*)"
|
||||
}
|
||||
}
|
||||
.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor on a statement
|
||||
public final class DatabaseCursor<Element> : Cursor {
|
||||
fileprivate let statement: SelectStatement
|
||||
/// 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")
|
||||
/// let cursor: StatementCursor = statement.cursor()
|
||||
/// }
|
||||
public final class StatementCursor: Cursor {
|
||||
public let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let element: () throws -> Element?
|
||||
private var done = false
|
||||
|
||||
// Fileprivate so that only SelectStatement can instantiate a database cursor
|
||||
fileprivate init(statement: SelectStatement, element: @escaping () throws -> Element?) {
|
||||
// Use SelectStatement.cursor() instead
|
||||
fileprivate init(statement: SelectStatement, arguments: StatementArguments? = nil) {
|
||||
self.statement = statement
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
self.element = element
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or `nil` if no next element
|
||||
/// exists. Once nil has been returned, all subsequent calls return nil.
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...") // DatabaseCursor<Row>
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row.value(atIndex: 0)
|
||||
/// let name: String = row.value(atIndex: 1)
|
||||
/// }
|
||||
public func next() throws -> Element? {
|
||||
if done {
|
||||
return nil
|
||||
}
|
||||
|
||||
public func next() throws -> Void? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return try element()
|
||||
return .some(())
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
@@ -361,51 +414,63 @@ public final class DatabaseCursor<Element> : Cursor {
|
||||
/// You create UpdateStatement with the Database.makeUpdateStatement() method:
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO persons (name) VALUES (?)")
|
||||
/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// return .commit
|
||||
/// }
|
||||
public final class UpdateStatement : Statement {
|
||||
enum TransactionStatementInfo {
|
||||
enum SavepointAction : String {
|
||||
case begin = "BEGIN"
|
||||
case release = "RELEASE"
|
||||
case rollback = "ROLLBACK"
|
||||
}
|
||||
|
||||
enum TransactionAction : String {
|
||||
case begin = "BEGIN"
|
||||
case commit = "COMMIT"
|
||||
case rollback = "ROLLBACK"
|
||||
}
|
||||
|
||||
case transaction(action: TransactionAction)
|
||||
case savepoint(name: String, action: SavepointAction)
|
||||
public final class UpdateStatement : Statement, AuthorizedStatement {
|
||||
enum TransactionEffect {
|
||||
case beginTransaction
|
||||
case commitTransaction
|
||||
case rollbackTransaction
|
||||
case beginSavepoint(String)
|
||||
case releaseSavepoint(String)
|
||||
case rollbackSavepoint(String)
|
||||
}
|
||||
|
||||
/// If true, the database schema cache gets invalidated after this statement
|
||||
/// is executed.
|
||||
private(set) var invalidatesDatabaseSchemaCache: Bool
|
||||
private(set) var transactionStatementInfo: TransactionStatementInfo?
|
||||
|
||||
/// If true, the statement needs support from TruncateOptimizationBlocker
|
||||
/// when executed
|
||||
private(set) var needsTruncateOptimizationPreventionDuringExecution: Bool
|
||||
|
||||
private(set) var transactionEffect: TransactionEffect?
|
||||
private(set) var databaseEventKinds: [DatabaseEventKind]
|
||||
|
||||
init(database: Database, sqliteStatement: SQLiteStatement, invalidatesDatabaseSchemaCache: Bool, transactionStatementInfo: TransactionStatementInfo?, databaseEventKinds: [DatabaseEventKind]) {
|
||||
self.invalidatesDatabaseSchemaCache = invalidatesDatabaseSchemaCache
|
||||
self.transactionStatementInfo = transactionStatementInfo
|
||||
self.databaseEventKinds = databaseEventKinds
|
||||
super.init(database: database, sqliteStatement: sqliteStatement)
|
||||
}
|
||||
|
||||
init(database: Database, sql: String) throws {
|
||||
/// Creates a prepared statement.
|
||||
///
|
||||
/// - parameter database: A database connection.
|
||||
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
|
||||
/// containing SQL.
|
||||
/// - parameter statementEnd: Upon success, the pointer to the next
|
||||
/// statement in the C string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - authorizer: A StatementCompilationAuthorizer
|
||||
/// - throws: DatabaseError in case of compilation error, and
|
||||
/// EmptyStatementError if the compiled string is blank or empty.
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
self.invalidatesDatabaseSchemaCache = false
|
||||
self.needsTruncateOptimizationPreventionDuringExecution = false
|
||||
self.databaseEventKinds = []
|
||||
|
||||
let observer = StatementCompilationObserver(database)
|
||||
try super.init(database: database, sql: sql, observer: observer)
|
||||
self.invalidatesDatabaseSchemaCache = observer.invalidatesDatabaseSchemaCache
|
||||
self.transactionStatementInfo = observer.transactionStatementInfo
|
||||
self.databaseEventKinds = observer.databaseEventKinds
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags)
|
||||
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
|
||||
self.needsTruncateOptimizationPreventionDuringExecution = authorizer.needsTruncateOptimizationPreventionDuringExecution
|
||||
self.transactionEffect = authorizer.transactionEffect
|
||||
self.databaseEventKinds = authorizer.databaseEventKinds
|
||||
}
|
||||
|
||||
/// Executes the SQL query.
|
||||
@@ -414,14 +479,14 @@ public final class UpdateStatement : Statement {
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(arguments: StatementArguments? = nil) throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
// Force arguments validity: it is a programmer error to provide
|
||||
// arguments that do not match the statement.
|
||||
try! prepare(withArguments: arguments)
|
||||
|
||||
prepare(withArguments: arguments)
|
||||
reset()
|
||||
database.updateStatementWillExecute(self)
|
||||
|
||||
if needsTruncateOptimizationPreventionDuringExecution {
|
||||
database.authorizer = TruncateOptimizationBlocker()
|
||||
}
|
||||
|
||||
while true {
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_ROW:
|
||||
@@ -444,15 +509,13 @@ public final class UpdateStatement : Statement {
|
||||
continue
|
||||
|
||||
case SQLITE_DONE:
|
||||
database.updateStatementDidExecute(self)
|
||||
database.authorizer = nil
|
||||
try database.updateStatementDidExecute(self)
|
||||
return
|
||||
|
||||
case let code:
|
||||
// Failure
|
||||
//
|
||||
// Let database rethrow eventual transaction observer error:
|
||||
database.authorizer = nil
|
||||
try database.updateStatementDidFail(self)
|
||||
|
||||
throw DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql, arguments: self.arguments) // Error uses self.arguments, not the optional arguments parameter.
|
||||
}
|
||||
}
|
||||
@@ -493,13 +556,13 @@ public final class UpdateStatement : Statement {
|
||||
/// To fill named arguments, feed StatementArguments with a dictionary:
|
||||
///
|
||||
/// db.execute(
|
||||
/// "INSERT ... (:name, :age)",
|
||||
/// arguments: StatementArguments(["name": "Arthur", "age": 41]))
|
||||
/// "INSERT ... (:name, :score)",
|
||||
/// arguments: StatementArguments(["name": "Arthur", "score": 41]))
|
||||
///
|
||||
/// // Dictionary literals are automatically converted:
|
||||
/// db.execute(
|
||||
/// "INSERT ... (:name, :age)",
|
||||
/// arguments: ["name": "Arthur", "age": 41])
|
||||
/// "INSERT ... (:name, :score)",
|
||||
/// arguments: ["name": "Arthur", "score": 41])
|
||||
///
|
||||
/// ## Concatenating Arguments
|
||||
///
|
||||
@@ -534,39 +597,46 @@ public final class UpdateStatement : Statement {
|
||||
/// print(row)
|
||||
/// // Prints <Row two:2 foo:"foo" one:1 foo2:"foo" bar:"bar">
|
||||
public struct StatementArguments {
|
||||
var values: [DatabaseValue] = []
|
||||
var namedValues: [String: DatabaseValue] = [:]
|
||||
|
||||
public var isEmpty: Bool {
|
||||
return values.isEmpty && namedValues.isEmpty
|
||||
}
|
||||
|
||||
|
||||
// MARK: Empty Arguments
|
||||
|
||||
/// Creates empty StatementArguments.
|
||||
init() {
|
||||
}
|
||||
|
||||
// MARK: Positional Arguments
|
||||
|
||||
/// Initializes arguments from a sequence of optional values.
|
||||
/// Creates statement arguments from a sequence of optional values.
|
||||
///
|
||||
/// let values: [DatabaseValueConvertible?] = ["foo", 1, nil]
|
||||
/// db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values))
|
||||
///
|
||||
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Iterator.Element == DatabaseValueConvertible? {
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element == DatabaseValueConvertible? {
|
||||
values = sequence.map { $0?.databaseValue ?? .null }
|
||||
}
|
||||
|
||||
/// Initializes arguments from a sequence of optional values.
|
||||
/// Creates statement arguments from a sequence of optional values.
|
||||
///
|
||||
/// let values: [String] = ["foo", "bar"]
|
||||
/// db.execute("INSERT ... (?,?)", arguments: StatementArguments(values))
|
||||
///
|
||||
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element: DatabaseValueConvertible {
|
||||
values = sequence.map { $0.databaseValue }
|
||||
}
|
||||
|
||||
/// Initializes arguments from [Any].
|
||||
///
|
||||
/// The result is nil unless all objects adopt DatabaseValueConvertible.
|
||||
/// Creates statement arguments from any array. The result is nil unless all
|
||||
/// array elements adopt DatabaseValueConvertible.
|
||||
///
|
||||
/// - parameter array: An array
|
||||
/// - returns: A StatementArguments.
|
||||
@@ -584,8 +654,8 @@ public struct StatementArguments {
|
||||
|
||||
// MARK: Named Arguments
|
||||
|
||||
/// Initializes arguments from a sequence of (key, value) dictionary, such as
|
||||
/// a dictionary.
|
||||
/// Creates statement arguments from a sequence of (key, value) dictionary,
|
||||
/// such as a dictionary.
|
||||
///
|
||||
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
|
||||
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
|
||||
@@ -593,22 +663,22 @@ public struct StatementArguments {
|
||||
/// - parameter sequence: A sequence of (key, value) pairs
|
||||
/// - returns: A StatementArguments.
|
||||
public init(_ dictionary: [String: DatabaseValueConvertible?]) {
|
||||
namedValues = Dictionary(keys: dictionary.keys) { dictionary[$0]!?.databaseValue ?? .null }
|
||||
namedValues = dictionary.mapValues { $0?.databaseValue ?? .null }
|
||||
}
|
||||
|
||||
/// Initializes arguments from a sequence of (key, value) pairs, such as
|
||||
/// a dictionary.
|
||||
/// Creates statement arguments from a sequence of (key, value) pairs, such
|
||||
/// as a dictionary.
|
||||
///
|
||||
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
|
||||
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
|
||||
///
|
||||
/// - parameter sequence: A sequence of (key, value) pairs
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Iterator.Element == (String, DatabaseValueConvertible?) {
|
||||
namedValues = Dictionary(keyValueSequence: sequence.map { ($0, $1?.databaseValue ?? .null) })
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element == (String, DatabaseValueConvertible?) {
|
||||
namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) })
|
||||
}
|
||||
|
||||
/// Initializes arguments from [AnyHashable: Any].
|
||||
/// Creates statement arguments from [AnyHashable: Any].
|
||||
///
|
||||
/// The result is nil unless all dictionary keys are strings, and values
|
||||
/// adopt DatabaseValueConvertible.
|
||||
@@ -786,12 +856,6 @@ public struct StatementArguments {
|
||||
|
||||
// MARK: Not Public
|
||||
|
||||
var values: [DatabaseValue] = []
|
||||
var namedValues: [String: DatabaseValue] = [:]
|
||||
|
||||
init() {
|
||||
}
|
||||
|
||||
mutating func consume(_ statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] {
|
||||
let initialValuesCount = values.count
|
||||
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
|
||||
@@ -830,14 +894,13 @@ extension StatementArguments : ExpressibleByArrayLiteral {
|
||||
extension StatementArguments : ExpressibleByDictionaryLiteral {
|
||||
/// Returns a StatementArguments from a dictionary literal:
|
||||
///
|
||||
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "age": 41])
|
||||
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "score": 41])
|
||||
public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) {
|
||||
self.init(elements)
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments : CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
let valuesDescriptions = values.map { $0.description }
|
||||
let namedValuesDescriptions = namedValues.map { (key, value) -> String in
|
||||
@@ -847,6 +910,14 @@ extension StatementArguments : CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments : Equatable {
|
||||
public static func == (lhs: StatementArguments, rhs: StatementArguments) -> Bool {
|
||||
if lhs.values != rhs.values { return false }
|
||||
if lhs.namedValues != rhs.namedValues { return false }
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-unsafe statement cache
|
||||
struct StatementCache {
|
||||
unowned let db: Database
|
||||
@@ -862,7 +933,20 @@ struct StatementCache {
|
||||
return statement
|
||||
}
|
||||
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
#if GRDBCUSTOMSQLITE
|
||||
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
|
||||
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
|
||||
// > planner that the prepared statement will be retained for a long
|
||||
// > time and probably reused many times.
|
||||
//
|
||||
// This looks like a perfect match for cached statements.
|
||||
//
|
||||
// However SQLITE_PREPARE_PERSISTENT was only introduced in
|
||||
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
let statement = try db.makeSelectStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
#else
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
#endif
|
||||
selectStatements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
@@ -872,7 +956,20 @@ struct StatementCache {
|
||||
return statement
|
||||
}
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
#if GRDBCUSTOMSQLITE
|
||||
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
|
||||
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
|
||||
// > planner that the prepared statement will be retained for a long
|
||||
// > time and probably reused many times.
|
||||
//
|
||||
// This looks like a perfect match for cached statements.
|
||||
//
|
||||
// However SQLITE_PREPARE_PERSISTENT was only introduced in
|
||||
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
let statement = try db.makeUpdateStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
#else
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
#endif
|
||||
updateStatements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A protocol around sqlite3_set_authorizer
|
||||
protocol StatementAuthorizer : class {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
}
|
||||
|
||||
/// A class that gathers information about one statement during its compilation.
|
||||
final class StatementCompilationAuthorizer : StatementAuthorizer {
|
||||
/// What this statements reads
|
||||
var selectionInfo = SelectStatement.SelectionInfo()
|
||||
|
||||
/// What this statements writes
|
||||
var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// True if a statement alter the schema in a way that required schema cache
|
||||
/// invalidation. For example, adding a column to a table invalidates the
|
||||
/// schema cache, but not creating a table.
|
||||
var invalidatesDatabaseSchemaCache = false
|
||||
|
||||
/// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or
|
||||
/// savepoint statement.
|
||||
var transactionEffect: UpdateStatement.TransactionEffect?
|
||||
|
||||
/// True if statement may trigger the truncate optimization
|
||||
var needsTruncateOptimizationPreventionDuringExecution = false
|
||||
|
||||
private var isDropStatement = false
|
||||
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
{
|
||||
// print("StatementCompilationAuthorizer: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
|
||||
|
||||
switch actionCode {
|
||||
case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE,
|
||||
SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX:
|
||||
isDropStatement = true
|
||||
invalidatesDatabaseSchemaCache = true
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_DROP_VIEW, SQLITE_DROP_TEMP_VIEW,
|
||||
SQLITE_DROP_TRIGGER, SQLITE_CREATE_TEMP_TRIGGER:
|
||||
isDropStatement = true
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_DETACH, SQLITE_ALTER_TABLE,
|
||||
SQLITE_CREATE_INDEX, SQLITE_CREATE_TEMP_INDEX:
|
||||
invalidatesDatabaseSchemaCache = true
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_READ:
|
||||
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
if columnName.isEmpty {
|
||||
// SELECT COUNT(*) FROM table
|
||||
selectionInfo.insert(allColumnsOfTable: tableName)
|
||||
} else {
|
||||
// SELECT column FROM table
|
||||
selectionInfo.insert(column: columnName, ofTable: tableName)
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_INSERT:
|
||||
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
databaseEventKinds.append(.insert(tableName: tableName))
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_DELETE:
|
||||
if isDropStatement { return SQLITE_OK }
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
|
||||
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
|
||||
databaseEventKinds.append(.delete(tableName: String(cString: cString1)))
|
||||
// Prevent the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
|
||||
// See also TruncateOptimizationBlocker
|
||||
needsTruncateOptimizationPreventionDuringExecution = true
|
||||
return SQLITE_IGNORE
|
||||
|
||||
case SQLITE_UPDATE:
|
||||
guard let tableName = cString1.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
insertUpdateEventKind(tableName: tableName, columnName: columnName)
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_TRANSACTION:
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
if strcmp(cString1, "BEGIN") == 0 {
|
||||
transactionEffect = .beginTransaction
|
||||
} else if strcmp(cString1, "COMMIT") == 0 {
|
||||
transactionEffect = .commitTransaction
|
||||
} else if strcmp(cString1, "ROLLBACK") == 0 {
|
||||
transactionEffect = .rollbackTransaction
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_SAVEPOINT:
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
guard let name = cString2.map({ String(cString: $0) }) else { return SQLITE_OK }
|
||||
if strcmp(cString1, "BEGIN") == 0 {
|
||||
transactionEffect = .beginSavepoint(name)
|
||||
} else if strcmp(cString1, "RELEASE") == 0 {
|
||||
transactionEffect = .releaseSavepoint(name)
|
||||
} else if strcmp(cString1, "ROLLBACK") == 0 {
|
||||
transactionEffect = .rollbackSavepoint(name)
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_FUNCTION:
|
||||
// Starting SQLite 3.19.0, `SELECT COUNT(*) FROM table` triggers
|
||||
// an authorization callback for SQLITE_READ with an empty
|
||||
// column: http://www.sqlite.org/changes.html#version_3_19_0
|
||||
//
|
||||
// Before SQLite 3.19.0, `SELECT COUNT(*) FROM table` does not
|
||||
// trigger any authorization callback that tells about the
|
||||
// counted table: any use of the COUNT function makes the
|
||||
// selection undetermined.
|
||||
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
|
||||
guard let cString2 = cString2 else { return SQLITE_OK }
|
||||
if sqlite3_stricmp(cString2, "COUNT") == 0 {
|
||||
selectionInfo = .unknown
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
default:
|
||||
return SQLITE_OK
|
||||
}
|
||||
}
|
||||
|
||||
func insertUpdateEventKind(tableName: String, columnName: String) {
|
||||
for (index, eventKind) in databaseEventKinds.enumerated() {
|
||||
if case .update(let t, let columnNames) = eventKind, t == tableName {
|
||||
var columnNames = columnNames
|
||||
columnNames.insert(columnName)
|
||||
databaseEventKinds[index] = .update(tableName: tableName, columnNames: columnNames)
|
||||
return
|
||||
}
|
||||
}
|
||||
databaseEventKinds.append(.update(tableName: tableName, columnNames: [columnName]))
|
||||
}
|
||||
}
|
||||
|
||||
/// This authorizer prevents the [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
|
||||
/// which makes transaction observers unable to observe individual deletions
|
||||
/// when user runs `DELETE FROM t` statements.
|
||||
//
|
||||
/// Warning: to perform well, this authorizer requires that:
|
||||
//
|
||||
/// - It is used during statement execution, not during statement compilation.
|
||||
/// - Statement compilation was authorized with a StatementCompilationAuthorizer
|
||||
/// that has set its needsTruncateOptimizationPreventionDuringExecution flag.
|
||||
final class TruncateOptimizationBlocker : StatementAuthorizer {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
{
|
||||
// print("TruncateOptimizationBlocker: \(actionCode) \([cString1, cString2, cString3, cString4].flatMap { $0.map({ String(cString: $0) }) })")
|
||||
return (actionCode == SQLITE_DELETE) ? SQLITE_IGNORE : SQLITE_OK
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,46 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// When a type adopts both DatabaseValueConvertible and
|
||||
/// StatementColumnConvertible, it is granted with faster access to the SQLite
|
||||
/// database values.
|
||||
/// The StatementColumnConvertible protocol grants access to the low-level C
|
||||
/// interface that extracts values from query results:
|
||||
/// https://www.sqlite.org/c3ref/column_blob.html. It can bring performance
|
||||
/// improvements.
|
||||
///
|
||||
/// To use it, have a value type adopt both StatementColumnConvertible and
|
||||
/// DatabaseValueConvertible. GRDB will then automatically apply the
|
||||
/// optimization whenever direct access to SQLite is possible:
|
||||
///
|
||||
/// let rows = Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() {
|
||||
/// let int: Int = row[0] // there
|
||||
/// }
|
||||
/// let ints = Int.fetchAll(db, "SELECT ...") // there
|
||||
/// struct Player {
|
||||
/// init(row: Row) {
|
||||
/// name = row["name"] // there
|
||||
/// score = row["score"] // there
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// StatementColumnConvertible is already adopted by all Swift integer types,
|
||||
/// Float, Double, String, and Bool.
|
||||
public protocol StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
/// Initializes a value from a raw SQLite statement pointer.
|
||||
///
|
||||
/// As an example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
/// public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
/// init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
/// self = sqlite3_column_int64(sqliteStatement, index)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// When you implement this method, don't check for NULL.
|
||||
/// This initializer is never called for NULL database values: don't perform
|
||||
/// any extra check.
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/column_blob.html for more information.
|
||||
///
|
||||
@@ -27,6 +50,91 @@ public protocol StatementColumnConvertible {
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32)
|
||||
}
|
||||
|
||||
/// 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")
|
||||
/// while let name = names.next() { // String
|
||||
/// print(name)
|
||||
/// }
|
||||
/// }
|
||||
public final class ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
public func next() throws -> Value? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
|
||||
var error = "could not convert database value NULL to \(Value.self) with statement `\(statement.sql)`"
|
||||
if !statement.arguments.isEmpty {
|
||||
error += " arguments \(statement.arguments)"
|
||||
}
|
||||
fatalError(error)
|
||||
}
|
||||
return Value(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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")
|
||||
/// while let email = emails.next() { // String?
|
||||
/// print(email ?? "<NULL>")
|
||||
/// }
|
||||
/// }
|
||||
public final class NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private let columnIndex: Int32
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
self.columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
public func next() throws -> Value?? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
|
||||
return .some(nil)
|
||||
}
|
||||
return Value(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Types that adopt both DatabaseValueConvertible and
|
||||
/// StatementColumnConvertible can be efficiently initialized from
|
||||
@@ -41,7 +149,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // DatabaseCursor<String>
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -57,20 +165,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
let columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
return statement.cursor(arguments: arguments, next: {
|
||||
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
|
||||
var error = "could not convert database value NULL to \(Self.self) with statement `\(statement.sql)`"
|
||||
if let arguments = arguments, !arguments.isEmpty {
|
||||
error += " arguments \(arguments)"
|
||||
}
|
||||
fatalError(error)
|
||||
}
|
||||
return Self.init(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
})
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor<Self> {
|
||||
return try ColumnCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
@@ -100,15 +196,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
|
||||
// We'll read from leftmost column at index 0, unless adapter mangles columns
|
||||
let columnIndex = try Int32(adapter?.baseColumnIndex(atIndex: 0, layout: statement) ?? 0)
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
let cursor: DatabaseCursor<Self?> = statement.cursor(arguments: arguments, next: {
|
||||
if sqlite3_column_type(sqliteStatement, columnIndex) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
return Self.init(sqliteStatement: sqliteStatement, index: columnIndex)
|
||||
})
|
||||
// fetchOne returns nil if there is no row, or if there is a row with a null value
|
||||
let cursor = try NullableColumnCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
|
||||
return try cursor.next() ?? nil
|
||||
}
|
||||
}
|
||||
@@ -120,8 +209,8 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// Returns a cursor over values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // DatabaseCursor<String>
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchCursor(db, request) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -136,7 +225,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - 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 -> DatabaseCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> ColumnCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
@@ -144,7 +233,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// Returns an array of values fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let names = try String.fetchAll(db, request) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -160,7 +249,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn)
|
||||
/// let request = Player.select(nameColumn)
|
||||
/// let name = try String.fetchOne(db, request) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -177,7 +266,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns a cursor over values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // DatabaseCursor<String>
|
||||
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
/// }
|
||||
@@ -194,7 +283,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
|
||||
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))
|
||||
}
|
||||
|
||||
@@ -228,3 +317,143 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch cursors
|
||||
/// and arrays of optional DatabaseValueConvertible:
|
||||
///
|
||||
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // 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:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor<Wrapped> {
|
||||
return try NullableColumnCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchAll(statement) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
/// Returns a cursor over optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // 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.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor<Wrapped> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
|
||||
return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,23 @@
|
||||
import Foundation
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// Data is convertible to and from DatabaseValue.
|
||||
extension Data : DatabaseValueConvertible {
|
||||
extension Data : DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
self.init(bytes: bytes, count: count) // copy bytes
|
||||
} else {
|
||||
self.init()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
// SQLite cant' store zero-length blobs.
|
||||
guard count > 0 else {
|
||||
return .null
|
||||
}
|
||||
return DatabaseValue(storage: .blob(self))
|
||||
}
|
||||
|
||||
|
||||
+15
-1
@@ -13,7 +13,7 @@ import Foundation
|
||||
///
|
||||
/// // ... then the ReferenceConvertible type can freely adopt DatabaseValueConvertible:
|
||||
/// extension Foo : DatabaseValueConvertible { /* empty */ }
|
||||
extension ReferenceConvertible where Self: DatabaseValueConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
@@ -25,3 +25,17 @@ extension ReferenceConvertible where Self: DatabaseValueConvertible, Self.Refere
|
||||
return ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) }
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Decodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
// Preserve custom database decoding
|
||||
return ReferenceType.fromDatabaseValue(databaseValue).flatMap { cast($0) }
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Encodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
// Preserve custom database encoding
|
||||
return (self as! ReferenceType).databaseValue
|
||||
}
|
||||
}
|
||||
@@ -3,26 +3,75 @@ import Foundation
|
||||
/// NSDate is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension NSDate : DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns a database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return storageDateFormatter.string(from: self as Date).databaseValue
|
||||
return (self as Date).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a Date initialized from *dbValue*, if possible.
|
||||
/// Returns a date initialized from dbValue, if possible.
|
||||
///
|
||||
/// If database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
///
|
||||
/// If database value contains a string, that string is interpreted as a
|
||||
/// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time
|
||||
/// zone. Nil is returned if the date string does not contain at least the
|
||||
/// year, month and day components. Other components (minutes, etc.)
|
||||
/// are set to zero if missing.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(dbValue) {
|
||||
return cast(fromDatabaseDateComponents(databaseDateComponents))
|
||||
guard let date = Date.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
if let julianDayNumber = Double.fromDatabaseValue(dbValue) {
|
||||
return cast(fromJulianDayNumber(julianDayNumber))
|
||||
return cast(date)
|
||||
}
|
||||
}
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension Date : DatabaseValueConvertible {
|
||||
/// Returns a database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return storageDateFormatter.string(from: self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a date initialized from dbValue, if possible.
|
||||
///
|
||||
/// If database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
///
|
||||
/// If database value contains a string, that string is interpreted as a
|
||||
/// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time
|
||||
/// zone. Nil is returned if the date string does not contain at least the
|
||||
/// year, month and day components. Other components (minutes, etc.)
|
||||
/// are set to zero if missing.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Date? {
|
||||
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(dbValue) {
|
||||
return Date(databaseDateComponents: databaseDateComponents)
|
||||
}
|
||||
if let timestamp = Double.fromDatabaseValue(dbValue) {
|
||||
return Date(timeIntervalSince1970: timestamp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
private static func fromJulianDayNumber(_ julianDayNumber: Double) -> Date? {
|
||||
private init?(databaseDateComponents: DatabaseDateComponents) {
|
||||
guard databaseDateComponents.format.hasYMDComponents else {
|
||||
// Refuse to turn hours without any date information into Date:
|
||||
return nil
|
||||
}
|
||||
guard let date = UTCCalendar.date(from: databaseDateComponents.dateComponents) else {
|
||||
return nil
|
||||
}
|
||||
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
|
||||
}
|
||||
|
||||
/// Creates a date from a [Julian Day](https://en.wikipedia.org/wiki/Julian_day).
|
||||
public init?(julianDay: Double) {
|
||||
// Conversion uses the same algorithm as SQLite: https://www.sqlite.org/src/artifact/8ec787fed4929d8c
|
||||
let JD = Int64(julianDayNumber * 86400000)
|
||||
// TODO: check for overflows one day, and return nil when computation can't complete.
|
||||
let JD = Int64(julianDay * 86400000)
|
||||
let Z = Int(((JD + 43200000)/86400000))
|
||||
var A = Int(((Double(Z) - 1867216.25)/36524.25))
|
||||
A = Z + 1 + A - (A/4)
|
||||
@@ -52,22 +101,13 @@ extension NSDate : DatabaseValueConvertible {
|
||||
dateComponents.second = Int(second)
|
||||
dateComponents.nanosecond = Int((second - Double(Int(second))) * 1.0e9)
|
||||
|
||||
return UTCCalendar.date(from: dateComponents)!
|
||||
}
|
||||
|
||||
private static func fromDatabaseDateComponents(_ databaseDateComponents: DatabaseDateComponents) -> Date? {
|
||||
guard databaseDateComponents.format.hasYMDComponents else {
|
||||
// Refuse to turn hours without any date information into Date:
|
||||
guard let date = UTCCalendar.date(from: dateComponents) else {
|
||||
return nil
|
||||
}
|
||||
return UTCCalendar.date(from: databaseDateComponents.dateComponents)!
|
||||
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
|
||||
}
|
||||
}
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension Date : DatabaseValueConvertible { }
|
||||
|
||||
/// The DatabaseDate date formatter for stored dates.
|
||||
private let storageDateFormatter: DateFormatter = {
|
||||
let formatter = DateFormatter()
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
|
||||
let dbValue: DatabaseValue
|
||||
let codingPath: [CodingKey]
|
||||
|
||||
/// Decodes a null value.
|
||||
///
|
||||
/// - returns: Whether the encountered value was null.
|
||||
func decodeNil() -> Bool {
|
||||
return dbValue.isNull
|
||||
}
|
||||
|
||||
/// Decodes a single value of the given type.
|
||||
///
|
||||
/// - parameter type: The type to decode as.
|
||||
/// - returns: A value of the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
|
||||
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
|
||||
func decode(_ type: Bool.Type) throws -> Bool { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int.Type) throws -> Int { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int8.Type) throws -> Int8 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int16.Type) throws -> Int16 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int32.Type) throws -> Int32 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Int64.Type) throws -> Int64 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt.Type) throws -> UInt { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt8.Type) throws -> UInt8 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt16.Type) throws -> UInt16 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt32.Type) throws -> UInt32 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: UInt64.Type) throws -> UInt64 { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Float.Type) throws -> Float { return dbValue.losslessConvert() }
|
||||
func decode(_ type: Double.Type) throws -> Double { return dbValue.losslessConvert() }
|
||||
func decode(_ type: String.Type) throws -> String { return dbValue.losslessConvert() }
|
||||
|
||||
/// Decodes a single value of the given type.
|
||||
///
|
||||
/// - parameter type: The type to decode as.
|
||||
/// - returns: A value of the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
|
||||
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
|
||||
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows custom database decoding, such as decoding Date from
|
||||
// String, for example.
|
||||
return type.fromDatabaseValue(dbValue) as! T
|
||||
} else {
|
||||
return try T(from: DatabaseValueDecoder(dbValue: dbValue, codingPath: codingPath))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct DatabaseValueDecoder: Decoder {
|
||||
let dbValue: DatabaseValue
|
||||
|
||||
init(dbValue: DatabaseValue, codingPath: [CodingKey]) {
|
||||
self.dbValue = dbValue
|
||||
self.codingPath = codingPath
|
||||
}
|
||||
|
||||
// Decoder
|
||||
let codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey : Any] { return [:] }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
|
||||
throw DecodingError.typeMismatch(
|
||||
type,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "keyed decoding is not supported"))
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
throw DecodingError.typeMismatch(
|
||||
UnkeyedDecodingContainer.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
return DatabaseValueDecodingContainer(dbValue: dbValue, codingPath: codingPath)
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Decodable {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
return try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Decodable & RawRepresentable, Self.RawValue: DatabaseValueConvertible {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
// Preserve custom database decoding
|
||||
return RawValue.fromDatabaseValue(databaseValue).flatMap { self.init(rawValue: $0) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
|
||||
var codingPath: [CodingKey] { return [] }
|
||||
|
||||
/// Encodes a null value.
|
||||
///
|
||||
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
mutating func encodeNil() throws { encode(.null) }
|
||||
|
||||
/// Encodes a single value of the given type.
|
||||
///
|
||||
/// - parameter value: The value to encode.
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
mutating func encode(_ value: Bool) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Int) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Int8) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Int16) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Int32) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Int64) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: UInt) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: UInt8) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: UInt16) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: UInt32) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: UInt64) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Float) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: Double) throws { encode(value.databaseValue) }
|
||||
mutating func encode(_ value: String) throws { encode(value.databaseValue) }
|
||||
|
||||
/// Encodes a single value of the given type.
|
||||
///
|
||||
/// - parameter value: The value to encode.
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
mutating func encode<T>(_ value: T) throws where T : Encodable {
|
||||
if let dbValueConvertible = value as? DatabaseValueConvertible {
|
||||
// Prefer DatabaseValueConvertible encoding over Decodable.
|
||||
// This allows us to encode Date as String, for example.
|
||||
encode(dbValueConvertible.databaseValue)
|
||||
} else {
|
||||
try value.encode(to: DatabaseValueEncoder(encode: encode))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct DatabaseValueEncoder : Encoder {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
|
||||
/// The path of coding keys taken to get to this point in encoding.
|
||||
/// A `nil` value indicates an unkeyed container.
|
||||
var codingPath: [CodingKey] { return [] }
|
||||
|
||||
/// Any contextual information set by the user for encoding.
|
||||
var userInfo: [CodingUserInfoKey : Any] = [:]
|
||||
|
||||
init(encode: @escaping (DatabaseValue) -> Void) {
|
||||
self.encode = encode
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding multiple values keyed by the given key type.
|
||||
///
|
||||
/// - parameter type: The key type to use for the container.
|
||||
/// - returns: A new keyed encoding container.
|
||||
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
|
||||
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
|
||||
fatalError("keyed encoding is not supported")
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding multiple unkeyed values.
|
||||
///
|
||||
/// - returns: A new empty unkeyed container.
|
||||
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
|
||||
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
fatalError("unkeyed encoding is not supported")
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding a single primitive value.
|
||||
///
|
||||
/// - returns: A new empty single value container.
|
||||
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
|
||||
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
|
||||
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
return DatabaseValueEncodingContainer(encode: encode)
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Encodable {
|
||||
public var databaseValue: DatabaseValue {
|
||||
var dbValue: DatabaseValue! = nil
|
||||
let encoder = DatabaseValueEncoder(encode: { dbValue = $0 })
|
||||
try! self.encode(to: encoder)
|
||||
return dbValue
|
||||
}
|
||||
}
|
||||
|
||||
public extension DatabaseValueConvertible where Self: Encodable & RawRepresentable, Self.RawValue: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
// Preserve custom database encoding
|
||||
return rawValue.databaseValue
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
///
|
||||
/// // ... then the RawRepresentable type can freely adopt DatabaseValueConvertible:
|
||||
/// extension Color : DatabaseValueConvertible { /* empty */ }
|
||||
extension RawRepresentable where Self: DatabaseValueConvertible, Self.RawValue: DatabaseValueConvertible {
|
||||
extension DatabaseValueConvertible where Self: RawRepresentable, Self.RawValue: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
@@ -1,5 +1,7 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - Value Types
|
||||
@@ -114,17 +116,64 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns an Int initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
return Int(exactly: int64)
|
||||
case .double(let double):
|
||||
guard double >= Double(Int64.min) else { return nil }
|
||||
guard double < Double(Int64.max) else { return nil }
|
||||
return Int(exactly: Int64(double))
|
||||
default:
|
||||
return nil
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = Int8(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to Int8")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int8 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = Int16(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to Int16")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int16 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
@@ -151,16 +200,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns an Int32 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
return Int32(exactly: int64)
|
||||
case .double(let double):
|
||||
guard double >= Double(Int64.min) else { return nil }
|
||||
guard double < Double(Int64.max) else { return nil }
|
||||
return Int32(exactly: Int64(double))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,6 +236,146 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to UInt")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an Int initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt8(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to UInt8")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an UInt8 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt16(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to UInt16")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an UInt16 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt32(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to UInt32")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an UInt32 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
if let v = UInt64(exactly: int64) {
|
||||
self = v
|
||||
} else {
|
||||
fatalError("could not convert database value \(int64) to UInt64")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
return Int64(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an UInt64 initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64? {
|
||||
return Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
|
||||
extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
@@ -298,7 +478,7 @@ extension DatabaseFunction {
|
||||
/// capitalized:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.capitalized)
|
||||
/// let request = Player.select(nameColumn.capitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public static let capitalize = DatabaseFunction("swiftCapitalizedString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -317,7 +497,7 @@ extension DatabaseFunction {
|
||||
/// lowercased:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.lowercased())
|
||||
/// let request = Player.select(nameColumn.lowercased())
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public static let lowercase = DatabaseFunction("swiftLowercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -336,7 +516,7 @@ extension DatabaseFunction {
|
||||
/// uppercased:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.uppercased())
|
||||
/// let request = Player.select(nameColumn.uppercased())
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public static let uppercase = DatabaseFunction("swiftUppercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -357,7 +537,7 @@ extension DatabaseFunction {
|
||||
/// localizedCapitalized:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.localizedCapitalized)
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
|
||||
@@ -377,7 +557,7 @@ extension DatabaseFunction {
|
||||
/// localizedLowercased:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.localizedLowercased)
|
||||
/// let request = Player.select(nameColumn.localizedLowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
@@ -397,7 +577,7 @@ extension DatabaseFunction {
|
||||
/// localizedUppercased:
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.localizedUppercased)
|
||||
/// let request = Player.select(nameColumn.localizedUppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
@@ -433,7 +613,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
|
||||
/// dbQueue.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "CREATE TABLE players (" +
|
||||
/// "name TEXT COLLATE \(collationName)" +
|
||||
/// ")"
|
||||
/// )
|
||||
@@ -451,7 +631,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
|
||||
/// dbQueue.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "CREATE TABLE players (" +
|
||||
/// "name TEXT COLLATE \(collationName)" +
|
||||
/// ")"
|
||||
/// )
|
||||
@@ -469,7 +649,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name
|
||||
/// dbQueue.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "CREATE TABLE players (" +
|
||||
/// "name TEXT COLLATE \(collationName)" +
|
||||
/// ")"
|
||||
/// )
|
||||
@@ -487,7 +667,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// let collationName = DatabaseCollation.localizedCompare.name
|
||||
/// dbQueue.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "CREATE TABLE players (" +
|
||||
/// "name TEXT COLLATE \(collationName)" +
|
||||
/// ")"
|
||||
/// )
|
||||
@@ -505,7 +685,7 @@ extension DatabaseCollation {
|
||||
///
|
||||
/// let collationName = DatabaseCollation.localizedStandardCompare.name
|
||||
/// dbQueue.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "CREATE TABLE players (" +
|
||||
/// "name TEXT COLLATE \(collationName)" +
|
||||
/// ")"
|
||||
/// )
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+19
-24
@@ -95,7 +95,7 @@ public struct FTS4 : VirtualTableModule {
|
||||
case .synchronized(let contentTable):
|
||||
// https://www.sqlite.org/fts3.html#_external_content_fts4_tables_
|
||||
|
||||
let rowIDColumn = (try? db.primaryKey(contentTable))??.rowIDColumn ?? "rowid"
|
||||
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
|
||||
let ftsTable = tableName.quotedDatabaseIdentifier
|
||||
let content = contentTable.quotedDatabaseIdentifier
|
||||
let indexedColumns = definition.columns.map { $0.name }
|
||||
@@ -110,25 +110,20 @@ public struct FTS4 : VirtualTableModule {
|
||||
|
||||
let oldRowID = "old.\(rowIDColumn.quotedDatabaseIdentifier)"
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN " +
|
||||
"DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); " +
|
||||
"END")
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN " +
|
||||
"DELETE FROM \(ftsTable) WHERE docid=\(oldRowID); " +
|
||||
"END")
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN " +
|
||||
"INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); " +
|
||||
"END")
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN " +
|
||||
"INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns)); " +
|
||||
"END")
|
||||
try db.execute("""
|
||||
CREATE TRIGGER \("__\(contentTable)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
|
||||
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
|
||||
END;
|
||||
CREATE TRIGGER \("__\(contentTable)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN
|
||||
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
|
||||
END;
|
||||
CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
|
||||
END;
|
||||
CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
|
||||
END;
|
||||
""")
|
||||
|
||||
// https://www.sqlite.org/fts3.html#*fts4rebuidcmd
|
||||
|
||||
@@ -247,7 +242,7 @@ public final class FTS4TableDefinition {
|
||||
///
|
||||
/// You get instances of this class when you create an FTS4 table:
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// t.column("content") // FTS4ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
@@ -266,7 +261,7 @@ public final class FTS4ColumnDefinition {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Excludes the column from the full-text index.
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
@@ -284,7 +279,7 @@ public final class FTS4ColumnDefinition {
|
||||
#else
|
||||
/// Excludes the column from the full-text index.
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
@@ -304,7 +299,7 @@ public final class FTS4ColumnDefinition {
|
||||
|
||||
/// Uses the column as the Int32 language id hidden column.
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS4()) { t in
|
||||
/// try db.create(virtualTable: "documents", using: FTS4()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("lid").asLanguageId()
|
||||
/// }
|
||||
|
||||
+34
-29
@@ -62,7 +62,7 @@
|
||||
}
|
||||
case .synchronized(let contentTable):
|
||||
arguments.append("content=\(contentTable.sqlExpression.sql)")
|
||||
if let rowIDColumn = try db.primaryKey(contentTable)?.rowIDColumn {
|
||||
if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn {
|
||||
arguments.append("content_rowid=\(rowIDColumn.sqlExpression.sql)")
|
||||
}
|
||||
}
|
||||
@@ -93,7 +93,7 @@
|
||||
case .synchronized(let contentTable):
|
||||
// https://sqlite.org/fts5.html#external_content_tables
|
||||
|
||||
let rowIDColumn = (try? db.primaryKey(contentTable))??.rowIDColumn ?? "rowid"
|
||||
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
|
||||
let ftsTable = tableName.quotedDatabaseIdentifier
|
||||
let content = contentTable.quotedDatabaseIdentifier
|
||||
let indexedColumns = definition.columns.map { $0.name }
|
||||
@@ -110,21 +110,18 @@
|
||||
.map { "old.\($0.quotedDatabaseIdentifier)" }
|
||||
.joined(separator: ", ")
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN " +
|
||||
"INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); " +
|
||||
"END")
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN " +
|
||||
"INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); " +
|
||||
"END")
|
||||
|
||||
try db.execute(
|
||||
"CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN " +
|
||||
"INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); " +
|
||||
"INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); " +
|
||||
"END")
|
||||
try db.execute("""
|
||||
CREATE TRIGGER \("__\(contentTable)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
|
||||
END;
|
||||
CREATE TRIGGER \("__\(contentTable)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
|
||||
END;
|
||||
CREATE TRIGGER \("__\(contentTable)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
|
||||
END;
|
||||
""")
|
||||
|
||||
// https://sqlite.org/fts5.html#the_rebuild_command
|
||||
|
||||
@@ -132,17 +129,25 @@
|
||||
}
|
||||
}
|
||||
|
||||
static func api(_ db: Database) -> UnsafePointer<fts5_api>? {
|
||||
do {
|
||||
return try Data.fetchOne(db, "SELECT fts5()").flatMap { data in
|
||||
guard data.count == MemoryLayout<UnsafePointer<fts5_api>>.size else {
|
||||
return nil
|
||||
}
|
||||
return data.withUnsafeBytes { $0.pointee }
|
||||
}
|
||||
} catch {
|
||||
return nil
|
||||
static func api(_ db: Database) -> UnsafePointer<fts5_api> {
|
||||
let sqliteConnection = db.sqliteConnection
|
||||
var statement: SQLiteStatement? = nil
|
||||
var api: UnsafePointer<fts5_api>? = nil
|
||||
let type: StaticString = "fts5_api_ptr"
|
||||
|
||||
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
fatalError("FTS5 is not available")
|
||||
}
|
||||
defer { sqlite3_finalize(statement) }
|
||||
type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in
|
||||
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
|
||||
}
|
||||
sqlite3_step(statement)
|
||||
guard let result = api else {
|
||||
fatalError("FTS5 is not available")
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,7 +284,7 @@
|
||||
///
|
||||
/// You get instances of this class when you create an FTS5 table:
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS5()) { t in
|
||||
/// try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
/// t.column("content") // FTS5ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
@@ -295,7 +300,7 @@
|
||||
|
||||
/// Excludes the column from the full-text index.
|
||||
///
|
||||
/// try db.create(virtualTable: "persons", using: FTS5()) { t in
|
||||
/// try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
/// t.column("a")
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Custom FTS5 Tokenizers
|
||||
// MARK: - FTS5
|
||||
|
||||
private class FTS5TokenizerConstructor {
|
||||
let db: Database
|
||||
@@ -55,10 +55,7 @@
|
||||
/// class MyTokenizer : FTS5CustomTokenizer { ... }
|
||||
/// db.add(tokenizer: MyTokenizer.self)
|
||||
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
|
||||
guard let api = FTS5.api(self) else {
|
||||
// Assume a GRDB bug or an SQLite miscompilation: there is no point throwing any error.
|
||||
fatalError("FTS5 is not enabled")
|
||||
}
|
||||
let api = FTS5.api(self)
|
||||
|
||||
// Swift won't let the @convention(c) xCreate() function below create
|
||||
// an instance of the generic Tokenizer type.
|
||||
|
||||
@@ -77,6 +77,8 @@
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - FTS5
|
||||
|
||||
/// Creates a pattern from a raw pattern string; throws DatabaseError on
|
||||
/// invalid syntax.
|
||||
///
|
||||
|
||||
@@ -106,8 +106,9 @@
|
||||
}
|
||||
|
||||
extension Database {
|
||||
/// MARK: - FTS5 Tokenizers
|
||||
|
||||
// MARK: - FTS5
|
||||
|
||||
/// Private type that makes a pre-registered FTS5 tokenizer available
|
||||
/// through the FTS5Tokenizer protocol.
|
||||
private final class FTS5RegisteredTokenizer : FTS5Tokenizer {
|
||||
@@ -188,9 +189,7 @@
|
||||
/// }
|
||||
/// }
|
||||
public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> FTS5Tokenizer {
|
||||
guard let api = FTS5.api(self) else {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "FTS5 API not found")
|
||||
}
|
||||
let api = FTS5.api(self)
|
||||
|
||||
let xTokenizerPointer: UnsafeMutablePointer<fts5_tokenizer> = .allocate(capacity: 1)
|
||||
defer { xTokenizerPointer.deallocate(capacity: 1) }
|
||||
|
||||
@@ -48,8 +48,8 @@ extension RowConvertible where Self: TableMapping {
|
||||
public static func fetch(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) -> Any { preconditionFailure() }
|
||||
}
|
||||
|
||||
@available(*, unavailable, message:"DatabaseSequence has been replaced by DatabaseCursor.")
|
||||
@available(*, unavailable, message:"DatabaseSequence has been replaced by Cursor.")
|
||||
public struct DatabaseSequence<T> { }
|
||||
|
||||
@available(*, unavailable, message:"DatabaseIterator has been replaced by DatabaseCursor.")
|
||||
@available(*, unavailable, message:"DatabaseIterator has been replaced by Cursor.")
|
||||
public struct DatabaseIterator<T> { }
|
||||
@@ -4,6 +4,6 @@ extension Database {
|
||||
}
|
||||
|
||||
extension DatabaseValue {
|
||||
@available(*, unavailable, message:"DatabaseSequence has been replaced by DatabaseCursor.")
|
||||
@available(*, unavailable, message:"DatabaseSequence has been replaced by Cursor.")
|
||||
public func value() -> Any { preconditionFailure() }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
extension Row {
|
||||
@available(*, unavailable, message:"use subscript instead: row[index]")
|
||||
public func value(atIndex index: Int) -> DatabaseValueConvertible? { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[index]")
|
||||
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value? { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[index]")
|
||||
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[column]")
|
||||
public func value(named name: String) -> DatabaseValueConvertible? { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[column]")
|
||||
public func value<Value: DatabaseValueConvertible>(named name: String) -> Value? { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[column]")
|
||||
public func value<Value: DatabaseValueConvertible>(named name: String) -> Value { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[column]")
|
||||
public func value(_ column: Column) -> DatabaseValueConvertible? { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[column]")
|
||||
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value? { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message:"use subscript instead: row[column]")
|
||||
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value { preconditionFailure() }
|
||||
}
|
||||
@@ -10,29 +10,31 @@
|
||||
/// var migrator = DatabaseMigrator()
|
||||
///
|
||||
/// // v1.0 database
|
||||
/// migrator.registerMigration("createPersons") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "id INTEGER PRIMARY KEY, " +
|
||||
/// "creationDate TEXT, " +
|
||||
/// "name TEXT NOT NULL" +
|
||||
/// ")")
|
||||
/// migrator.registerMigration("createAuthors") { db in
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE authors (
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// creationDate TEXT,
|
||||
/// name TEXT NOT NULL
|
||||
/// )
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// migrator.registerMigration("createBooks") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE books (" +
|
||||
/// "uuid TEXT PRIMARY KEY, " +
|
||||
/// "ownerID INTEGER NOT NULL " +
|
||||
/// " REFERENCES persons(id) " +
|
||||
/// " ON DELETE CASCADE ON UPDATE CASCADE, " +
|
||||
/// "title TEXT NOT NULL" +
|
||||
/// ")")
|
||||
/// 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
|
||||
/// migrator.registerMigration("AddAgeToPersons") { db in
|
||||
/// try db.execute("ALTER TABLE persons ADD COLUMN age INT")
|
||||
/// migrator.registerMigration("AddBirthYearToAuthors") { db in
|
||||
/// try db.execute("ALTER TABLE authors ADD COLUMN birthYear INT")
|
||||
/// }
|
||||
///
|
||||
/// try migrator.migrate(dbQueue)
|
||||
@@ -44,13 +46,14 @@ public struct DatabaseMigrator {
|
||||
|
||||
/// Registers a migration.
|
||||
///
|
||||
/// migrator.registerMigration("createPersons") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE persons (" +
|
||||
/// "id INTEGER PRIMARY KEY, " +
|
||||
/// "creationDate TEXT, " +
|
||||
/// "name TEXT NOT NULL" +
|
||||
/// ")")
|
||||
/// migrator.registerMigration("createPlayers") { db in
|
||||
/// try db.execute("""
|
||||
/// CREATE TABLE players (
|
||||
/// id INTEGER PRIMARY KEY,
|
||||
/// creationDate TEXT,
|
||||
/// name TEXT NOT NULL
|
||||
/// )
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -64,13 +67,14 @@ public struct DatabaseMigrator {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
|
||||
///
|
||||
/// // Add a NOT NULL constraint on persons.name:
|
||||
/// // Add a NOT NULL constraint on players.name:
|
||||
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" +
|
||||
/// "INSERT INTO new_persons SELECT * FROM persons;" +
|
||||
/// "DROP TABLE persons;" +
|
||||
/// "ALTER TABLE new_persons RENAME TO persons;")
|
||||
/// 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;
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// While your migration code runs with disabled foreign key checks, those
|
||||
@@ -88,13 +92,14 @@ public struct DatabaseMigrator {
|
||||
@available(iOS 8.2, OSX 10.10, *)
|
||||
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
|
||||
///
|
||||
/// // Add a NOT NULL constraint on persons.name:
|
||||
/// // Add a NOT NULL constraint on players.name:
|
||||
/// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in
|
||||
/// try db.execute(
|
||||
/// "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT NOT NULL);" +
|
||||
/// "INSERT INTO new_persons SELECT * FROM persons;" +
|
||||
/// "DROP TABLE persons;" +
|
||||
/// "ALTER TABLE new_persons RENAME TO persons;")
|
||||
/// 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;
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// While your migration code runs with disabled foreign key checks, those
|
||||
|
||||
@@ -31,14 +31,12 @@ extension TableMapping {
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM books WHERE books 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.
|
||||
public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest<Self> {
|
||||
return all().matching(pattern)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
///
|
||||
/// 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.
|
||||
public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<T> {
|
||||
switch query.source {
|
||||
case .table(let name, let alias)?:
|
||||
@@ -36,12 +40,6 @@
|
||||
/// // SELECT * FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection
|
||||
/// includes the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM books WHERE books MATCH '...'
|
||||
/// var request = Book.matching(pattern)
|
||||
///
|
||||
/// If the search pattern is nil, the request does not match any
|
||||
/// database row.
|
||||
public static func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest<Self> {
|
||||
|
||||
@@ -34,13 +34,13 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest with a new net of selected columns.
|
||||
///
|
||||
/// // SELECT id, email FROM persons
|
||||
/// var request = Person.all()
|
||||
/// // SELECT id, email FROM players
|
||||
/// var request = Player.all()
|
||||
/// request = request.select(Column("id"), Column("email"))
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM persons
|
||||
/// // SELECT email FROM players
|
||||
/// request
|
||||
/// .select(Column("id"))
|
||||
/// .select(Column("email"))
|
||||
@@ -50,13 +50,13 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest with a new net of selected columns.
|
||||
///
|
||||
/// // SELECT id, email FROM persons
|
||||
/// var request = Person.all()
|
||||
/// // SELECT id, email FROM players
|
||||
/// var request = Player.all()
|
||||
/// request = request.select([Column("id"), Column("email")])
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM persons
|
||||
/// // SELECT email FROM players
|
||||
/// request
|
||||
/// .select([Column("id")])
|
||||
/// .select([Column("email")])
|
||||
@@ -68,13 +68,13 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest with a new net of selected columns.
|
||||
///
|
||||
/// // SELECT id, email FROM persons
|
||||
/// var request = Person.all()
|
||||
/// // SELECT id, email FROM players
|
||||
/// var request = Player.all()
|
||||
/// request = request.select(sql: "id, email")
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM persons
|
||||
/// // SELECT email FROM players
|
||||
/// request
|
||||
/// .select(sql: "id")
|
||||
/// .select(sql: "email")
|
||||
@@ -84,12 +84,12 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest which returns distinct rows.
|
||||
///
|
||||
/// // SELECT DISTINCT * FROM persons
|
||||
/// var request = Person.all()
|
||||
/// // SELECT DISTINCT * FROM players
|
||||
/// var request = Player.all()
|
||||
/// request = request.distinct()
|
||||
///
|
||||
/// // SELECT DISTINCT name FROM persons
|
||||
/// var request = Person.select(Column("name"))
|
||||
/// // SELECT DISTINCT name FROM players
|
||||
/// var request = Player.select(Column("name"))
|
||||
/// request = request.distinct()
|
||||
public func distinct() -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
@@ -100,8 +100,8 @@ extension QueryInterfaceRequest {
|
||||
/// A new QueryInterfaceRequest with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM persons WHERE email = 'arthur@example.com'
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter(Column("email") == "arthur@example.com")
|
||||
public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
@@ -116,8 +116,8 @@ extension QueryInterfaceRequest {
|
||||
/// A new QueryInterfaceRequest with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT * FROM persons WHERE email = 'arthur@example.com'
|
||||
/// var request = Person.all()
|
||||
/// // 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))
|
||||
@@ -160,13 +160,13 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *orderings*.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order(Column("name"))
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// request
|
||||
/// .order(Column("email"))
|
||||
/// .reversed()
|
||||
@@ -177,13 +177,13 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *orderings*.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order([Column("name")])
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// request
|
||||
/// .order([Column("email")])
|
||||
/// .reversed()
|
||||
@@ -197,13 +197,13 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest with the provided *sql* used for sorting.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// var request = Player.all()
|
||||
/// request = request.order(sql: "name")
|
||||
///
|
||||
/// Any previous ordering is replaced:
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// request
|
||||
/// .order(sql: "email")
|
||||
/// .order(sql: "name")
|
||||
@@ -213,8 +213,8 @@ extension QueryInterfaceRequest {
|
||||
|
||||
/// A new QueryInterfaceRequest sorted in reversed order.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name DESC
|
||||
/// var request = Person.all().order(Column("name"))
|
||||
/// // SELECT * FROM players ORDER BY name DESC
|
||||
/// var request = Player.all().order(Column("name"))
|
||||
/// request = request.reversed()
|
||||
public func reversed() -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
@@ -225,8 +225,8 @@ extension QueryInterfaceRequest {
|
||||
/// A QueryInterfaceRequest which fetches *limit* rows, starting
|
||||
/// at *offset*.
|
||||
///
|
||||
/// // SELECT * FROM persons LIMIT 1
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players LIMIT 1
|
||||
/// var request = Player.all()
|
||||
/// request = request.limit(1)
|
||||
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
@@ -235,7 +235,7 @@ extension QueryInterfaceRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
|
||||
|
||||
// MARK: Deleting
|
||||
|
||||
@@ -257,22 +257,14 @@ extension TableMapping {
|
||||
|
||||
/// Creates a QueryInterfaceRequest which fetches all records.
|
||||
///
|
||||
/// // SELECT * FROM persons
|
||||
/// var request = Person.all()
|
||||
/// // SELECT * FROM players
|
||||
/// let request = Player.all()
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons
|
||||
/// var request = Person.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.
|
||||
public static func all() -> QueryInterfaceRequest<Self> {
|
||||
let selection: [SQLSelectable]
|
||||
if selectsRowID {
|
||||
selection = [SQLStar(), Column.rowID]
|
||||
} else {
|
||||
selection = [SQLStar()]
|
||||
}
|
||||
return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: selection, from: .table(name: databaseTableName, alias: nil)))
|
||||
return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: databaseSelection, from: .table(name: databaseTableName, alias: nil)))
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest which fetches no record.
|
||||
@@ -282,52 +274,48 @@ extension TableMapping {
|
||||
|
||||
/// Creates a QueryInterfaceRequest which selects *selection*.
|
||||
///
|
||||
/// // SELECT id, email FROM persons
|
||||
/// var request = Person.select(Column("id"), Column("email"))
|
||||
/// // SELECT id, email FROM players
|
||||
/// 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*.
|
||||
///
|
||||
/// // SELECT id, email FROM persons
|
||||
/// var request = Person.select([Column("id"), Column("email")])
|
||||
/// // SELECT id, email FROM players
|
||||
/// 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*.
|
||||
///
|
||||
/// // SELECT id, email FROM persons
|
||||
/// var request = Person.select(sql: "id, email")
|
||||
/// // SELECT id, email FROM players
|
||||
/// 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*.
|
||||
///
|
||||
/// // SELECT * FROM persons WHERE email = 'arthur@example.com'
|
||||
/// var request = Person.filter(Column("email") == "arthur@example.com")
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
/// let request = Player.filter(Column("email") == "arthur@example.com")
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons WHERE email = 'arthur@example.com'
|
||||
/// var request = Person.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.
|
||||
public static func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(predicate)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest with the provided *predicate*.
|
||||
///
|
||||
/// // SELECT * FROM persons WHERE email = 'arthur@example.com'
|
||||
/// var request = Person.filter(sql: "email = ?", arguments: ["arthur@example.com"])
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com'
|
||||
/// let request = Player.filter(sql: "email = ?", arguments: ["arthur@example.com"])
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons WHERE email = 'arthur@example.com'
|
||||
/// var request = Person.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.
|
||||
public static func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
|
||||
return all().filter(sql: sql, arguments: arguments)
|
||||
}
|
||||
@@ -335,14 +323,12 @@ extension TableMapping {
|
||||
/// Creates a QueryInterfaceRequest sorted according to the
|
||||
/// provided *orderings*.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// var request = Person.order(Column("name"))
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// let request = Player.order(Column("name"))
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons ORDER BY name
|
||||
/// var request = Person.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.
|
||||
public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<Self> {
|
||||
return all().order(orderings)
|
||||
}
|
||||
@@ -350,28 +336,24 @@ extension TableMapping {
|
||||
/// Creates a QueryInterfaceRequest sorted according to the
|
||||
/// provided *orderings*.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// var request = Person.order([Column("name")])
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// let request = Player.order([Column("name")])
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons ORDER BY name
|
||||
/// var request = Person.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.
|
||||
public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<Self> {
|
||||
return all().order(orderings)
|
||||
}
|
||||
|
||||
/// Creates a QueryInterfaceRequest sorted according to *sql*.
|
||||
///
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// var request = Person.order(sql: "name")
|
||||
/// // SELECT * FROM players ORDER BY name
|
||||
/// let request = Player.order(sql: "name")
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons ORDER BY name
|
||||
/// var request = Person.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.
|
||||
public static func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
|
||||
return all().order(sql: sql, arguments: arguments)
|
||||
}
|
||||
@@ -379,14 +361,12 @@ extension TableMapping {
|
||||
/// Creates a QueryInterfaceRequest which fetches *limit* rows, starting at
|
||||
/// *offset*.
|
||||
///
|
||||
/// // SELECT * FROM persons LIMIT 1
|
||||
/// var request = Person.limit(1)
|
||||
/// // SELECT * FROM players LIMIT 1
|
||||
/// let request = Player.limit(1)
|
||||
///
|
||||
/// If the `selectsRowID` type property is true, then the selection includes
|
||||
/// the hidden "rowid" column:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons LIMIT 1
|
||||
/// var request = Person.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.
|
||||
public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<Self> {
|
||||
return all().limit(limit, offset: offset)
|
||||
}
|
||||
|
||||
@@ -59,26 +59,7 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
sql += " HAVING " + havingExpression.expressionSQL(&arguments)
|
||||
}
|
||||
|
||||
var orderings = self.orderings
|
||||
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.
|
||||
orderings = [Column.rowID.desc]
|
||||
} else {
|
||||
orderings = orderings.map { $0.reversed }
|
||||
}
|
||||
}
|
||||
let orderings = self.queryOrderings
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ")
|
||||
}
|
||||
@@ -101,11 +82,6 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
fatalError("Can't delete query with GROUP BY expression")
|
||||
}
|
||||
|
||||
guard limit == nil else {
|
||||
// Programmer error
|
||||
fatalError("Can't delete query with limit")
|
||||
}
|
||||
|
||||
var sql = "DELETE"
|
||||
var arguments: StatementArguments? = StatementArguments()
|
||||
|
||||
@@ -117,11 +93,48 @@ struct QueryInterfaceSelectQueryDefinition {
|
||||
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
|
||||
@@ -176,7 +189,7 @@ extension QueryInterfaceSelectQueryDefinition : Request {
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
var countQuery = unorderedQuery
|
||||
countQuery.selection = [SQLExpressionCount(SQLStar())]
|
||||
countQuery.selection = [SQLExpressionCount(AllColumns())]
|
||||
return countQuery
|
||||
}
|
||||
}
|
||||
@@ -184,7 +197,7 @@ extension QueryInterfaceSelectQueryDefinition : Request {
|
||||
// SELECT COUNT(*) FROM (self)
|
||||
private var trivialCountQuery: QueryInterfaceSelectQueryDefinition {
|
||||
return QueryInterfaceSelectQueryDefinition(
|
||||
select: [SQLExpressionCount(SQLStar())],
|
||||
select: [SQLExpressionCount(AllColumns())],
|
||||
from: .query(query: unorderedQuery, alias: nil))
|
||||
}
|
||||
}
|
||||
@@ -227,8 +240,8 @@ struct SQLLimit {
|
||||
extension SQLCount {
|
||||
var sqlSelectable: SQLSelectable {
|
||||
switch self {
|
||||
case .star:
|
||||
return SQLExpressionCount(SQLStar())
|
||||
case .all:
|
||||
return SQLExpressionCount(AllColumns())
|
||||
case .distinct(let expression):
|
||||
return SQLExpressionCountDistinct(expression)
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
///
|
||||
/// let email: SQLCollatedExpression = Column("email").collating(.nocase)
|
||||
///
|
||||
/// // SELECT * FROM persons WHERE email = 'arthur@example.com' COLLATE NOCASE
|
||||
/// Persons.filter(email == "arthur@example.com")
|
||||
/// // SELECT * FROM players WHERE email = 'arthur@example.com' COLLATE NOCASE
|
||||
/// Players.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 persons ORDER BY email COLLATE NOCASE ASC
|
||||
/// Persons.order(email.asc)
|
||||
/// // SELECT * FROM players ORDER BY email COLLATE NOCASE ASC
|
||||
/// Players.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 persons ORDER BY email COLLATE NOCASE DESC
|
||||
/// Persons.order(email.desc)
|
||||
/// // SELECT * FROM players ORDER BY email COLLATE NOCASE DESC
|
||||
/// Players.order(email.desc)
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
public var desc: SQLOrderingTerm {
|
||||
|
||||
@@ -28,12 +28,6 @@ public protocol SQLCollection {
|
||||
///
|
||||
/// Returns an expression that check whether the collection contains
|
||||
/// the expression.
|
||||
///
|
||||
/// The default implementation returns a SQLExpressionContains which applies
|
||||
/// the `IN` operator:
|
||||
///
|
||||
/// let request = Person.select(Column("id"))
|
||||
/// request.contains(Column("id")) // id IN (SELECT id FROM persons)
|
||||
func contains(_ value: SQLExpressible) -> SQLExpression
|
||||
}
|
||||
|
||||
@@ -43,10 +37,7 @@ public protocol SQLCollection {
|
||||
extension SQLCollection {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns a SQLExpressionContains which applies the `IN` operator:
|
||||
///
|
||||
/// let request = Person.select(Column("id"))
|
||||
/// request.contains(Column("id")) // id IN (SELECT id FROM persons)
|
||||
/// Returns a SQLExpressionContains which applies the `IN` SQL operator.
|
||||
public func contains(_ value: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionContains(value, self)
|
||||
}
|
||||
|
||||
@@ -191,6 +191,30 @@ public struct SQLBinaryOperator : Hashable {
|
||||
public static func == (lhs: SQLBinaryOperator, rhs: SQLBinaryOperator) -> Bool {
|
||||
return lhs.sql == rhs.sql
|
||||
}
|
||||
|
||||
// TODO: make it an extension of Sequence (like joined(separator:)) when Swift can better handle existentials
|
||||
// TODO: make it public eventually
|
||||
/// Return nil if expressions is empty.
|
||||
func join(_ expressions: [SQLExpression]) -> SQLExpression? {
|
||||
switch expressions.count {
|
||||
case 0:
|
||||
return nil
|
||||
case 1:
|
||||
return expressions[0]
|
||||
default:
|
||||
let literals = expressions.map { $0.literal }
|
||||
let firstLiteral = literals[0]
|
||||
var sql = firstLiteral.sql
|
||||
var arguments = firstLiteral.arguments ?? StatementArguments()
|
||||
for literal in literals.suffix(from: 1) {
|
||||
sql += " \(self.sql) \(literal.sql)"
|
||||
if let args = literal.arguments {
|
||||
arguments += args
|
||||
}
|
||||
}
|
||||
return SQLExpressionLiteral("(\(sql))", arguments: arguments.isEmpty ? nil : arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
@@ -438,9 +462,8 @@ struct SQLExpressionCollate : SQLExpression {
|
||||
|
||||
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
let sql = expression.expressionSQL(&arguments)
|
||||
let chars = sql.characters
|
||||
if chars.last! == ")" {
|
||||
return String(chars.prefix(upTo: chars.index(chars.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")"
|
||||
if sql.last! == ")" {
|
||||
return String(sql.prefix(upTo: sql.index(sql.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")"
|
||||
} else {
|
||||
return sql + " COLLATE " + collationName.rawValue
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ extension SQLExpression {
|
||||
// SELECT expr FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
return .star
|
||||
return .all
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,37 @@
|
||||
// MARK: - SQLStar
|
||||
// MARK: - AllColumns
|
||||
|
||||
struct SQLStar : SQLSelectable {
|
||||
func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
/// AllColumns is the `*` in `SELECT *`.
|
||||
///
|
||||
/// You use AllColumns in your custom implementation of
|
||||
/// TableMapping.databaseSelection.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player : TableMapping {
|
||||
/// static var databaseTableName = "players"
|
||||
/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, rowid FROM players
|
||||
/// let request = Player.all()
|
||||
public struct AllColumns {
|
||||
///
|
||||
public init() { }
|
||||
}
|
||||
|
||||
extension AllColumns : SQLSelectable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "*"
|
||||
}
|
||||
|
||||
func countedSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func countedSQL(_ arguments: inout StatementArguments?) -> String {
|
||||
return "*"
|
||||
}
|
||||
|
||||
func count(distinct: Bool) -> SQLCount? {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
public func count(distinct: Bool) -> SQLCount? {
|
||||
// SELECT DISTINCT * FROM tableName ...
|
||||
guard !distinct else {
|
||||
return nil
|
||||
@@ -18,7 +40,7 @@ struct SQLStar : SQLSelectable {
|
||||
// SELECT * FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
return .star
|
||||
return .all
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ public enum SQLCount {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Represents COUNT(*)
|
||||
case star
|
||||
case all
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
|
||||
@@ -39,7 +39,7 @@ extension SQLSpecificExpressible {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// Person.filter(Column("email").collating(.nocase) == "contact@example.com")
|
||||
/// Player.filter(Column("email").collating(.nocase) == "contact@example.com")
|
||||
public func collating(_ collation: Database.CollationName) -> SQLCollatedExpression {
|
||||
return SQLCollatedExpression(sqlExpression, collationName: collation)
|
||||
}
|
||||
@@ -48,7 +48,7 @@ extension SQLSpecificExpressible {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// Person.filter(Column("name").collating(.localizedStandardCompare) == "Hervé")
|
||||
/// Player.filter(Column("name").collating(.localizedStandardCompare) == "Hervé")
|
||||
public func collating(_ collation: DatabaseCollation) -> SQLCollatedExpression {
|
||||
return SQLCollatedExpression(sqlExpression, collationName: Database.CollationName(collation.name))
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ extension SQLSpecificExpressible {
|
||||
/// capitalized String property. It is NULL for non-String arguments.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.capitalized)
|
||||
/// let request = Player.select(nameColumn.capitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public var capitalized: SQLExpression {
|
||||
return DatabaseFunction.capitalize.apply(sqlExpression)
|
||||
@@ -161,7 +161,7 @@ extension SQLSpecificExpressible {
|
||||
/// lowercased String property. It is NULL for non-String arguments.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.lowercased())
|
||||
/// let request = Player.select(nameColumn.lowercased())
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public var lowercased: SQLExpression {
|
||||
return DatabaseFunction.lowercase.apply(sqlExpression)
|
||||
@@ -171,7 +171,7 @@ extension SQLSpecificExpressible {
|
||||
/// uppercased String property. It is NULL for non-String arguments.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.uppercased())
|
||||
/// let request = Player.select(nameColumn.uppercased())
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
public var uppercased: SQLExpression {
|
||||
return DatabaseFunction.uppercase.apply(sqlExpression)
|
||||
@@ -183,7 +183,7 @@ extension SQLSpecificExpressible {
|
||||
/// localizedCapitalized String property. It is NULL for non-String arguments.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.localizedCapitalized)
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public var localizedCapitalized: SQLExpression {
|
||||
@@ -194,7 +194,7 @@ extension SQLSpecificExpressible {
|
||||
/// localizedLowercased String property. It is NULL for non-String arguments.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.localizedLowercased)
|
||||
/// let request = Player.select(nameColumn.localizedLowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public var localizedLowercased: SQLExpression {
|
||||
@@ -205,7 +205,7 @@ extension SQLSpecificExpressible {
|
||||
/// localizedUppercased String property. It is NULL for non-String arguments.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.select(nameColumn.localizedUppercased)
|
||||
/// let request = Player.select(nameColumn.localizedUppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public var localizedUppercased: SQLExpression {
|
||||
|
||||
@@ -14,6 +14,28 @@ extension SQLBinaryOperator {
|
||||
static let isNot = SQLBinaryOperator("IS NOT", negated: "IS")
|
||||
}
|
||||
|
||||
// Outputs "x = y" or "x IS NULL"
|
||||
private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression {
|
||||
switch (lhs, rhs) {
|
||||
case (let lhs, let rhs as DatabaseValue):
|
||||
switch rhs.storage {
|
||||
case .null:
|
||||
return SQLExpressionBinary(.is, lhs, DatabaseValue.null)
|
||||
default:
|
||||
return SQLExpressionBinary(.equal, lhs, rhs)
|
||||
}
|
||||
case (let lhs as DatabaseValue, let rhs):
|
||||
switch lhs.storage {
|
||||
case .null:
|
||||
return SQLExpressionBinary(.is, rhs, DatabaseValue.null)
|
||||
default:
|
||||
return SQLExpressionBinary(.equal, lhs, rhs)
|
||||
}
|
||||
default:
|
||||
return SQLExpressionBinary(.equal, lhs, rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `=` SQL operator.
|
||||
///
|
||||
/// // name = 'Arthur'
|
||||
@@ -24,11 +46,7 @@ extension SQLBinaryOperator {
|
||||
/// // name IS NULL
|
||||
/// Column("name") == nil
|
||||
public func == (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
|
||||
if let rhs = rhs {
|
||||
return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression)
|
||||
} else {
|
||||
return SQLExpressionBinary(.`is`, lhs.sqlExpression, DatabaseValue.null)
|
||||
}
|
||||
return isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `=` SQL operator.
|
||||
@@ -71,11 +89,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression {
|
||||
/// // name IS NULL
|
||||
/// nil == Column("name")
|
||||
public func == (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
if let lhs = lhs {
|
||||
return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression)
|
||||
} else {
|
||||
return SQLExpressionBinary(.`is`, rhs.sqlExpression, DatabaseValue.null)
|
||||
}
|
||||
return isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `=` SQL operator.
|
||||
@@ -113,7 +127,7 @@ public func == (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // email = login
|
||||
/// Column("email") == Column("login")
|
||||
public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.equal, lhs.sqlExpression, rhs.sqlExpression)
|
||||
return isEqual(lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<>` SQL operator.
|
||||
@@ -126,11 +140,7 @@ public func == (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
|
||||
/// // name IS NOT NULL
|
||||
/// Column("name") != nil
|
||||
public func != (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
|
||||
if let rhs = rhs {
|
||||
return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
} else {
|
||||
return SQLExpressionBinary(.isNot, lhs.sqlExpression, DatabaseValue.null)
|
||||
}
|
||||
return isEqual(lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null).negated
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<>` SQL operator.
|
||||
@@ -173,11 +183,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: Bool) -> SQLExpression {
|
||||
/// // name IS NOT NULL
|
||||
/// nil != Column("name")
|
||||
public func != (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
if let lhs = lhs {
|
||||
return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
} else {
|
||||
return SQLExpressionBinary(.isNot, rhs.sqlExpression, DatabaseValue.null)
|
||||
}
|
||||
return isEqual(lhs?.sqlExpression ?? DatabaseValue.null, rhs.sqlExpression).negated
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<>` SQL operator.
|
||||
@@ -215,7 +221,7 @@ public func != (lhs: Bool, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // email <> login
|
||||
/// Column("email") != Column("login")
|
||||
public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.notEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
return isEqual(lhs.sqlExpression, rhs.sqlExpression).negated
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `IS` SQL operator.
|
||||
@@ -223,7 +229,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
|
||||
/// // name IS 'Arthur'
|
||||
/// Column("name") === "Arthur"
|
||||
public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression {
|
||||
return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
|
||||
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `IS` SQL operator.
|
||||
@@ -240,9 +246,9 @@ public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress
|
||||
/// "Arthur" === Column("name")
|
||||
public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
if let lhs = lhs {
|
||||
return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs.sqlExpression)
|
||||
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression)
|
||||
} else {
|
||||
return SQLExpressionBinary(.`is`, rhs.sqlExpression, DatabaseValue.null)
|
||||
return SQLExpressionBinary(.is, rhs.sqlExpression, DatabaseValue.null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,7 +257,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpres
|
||||
/// // name IS 'Arthur' COLLATE NOCASE
|
||||
/// "Arthur" === Column("name").collating(.nocase)
|
||||
public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpression {
|
||||
return SQLExpressionCollate(lhs == rhs.expression, collationName: rhs.collationName)
|
||||
return SQLExpressionCollate(lhs === rhs.expression, collationName: rhs.collationName)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `IS` SQL operator.
|
||||
@@ -259,7 +265,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress
|
||||
/// // email IS login
|
||||
/// Column("email") === Column("login")
|
||||
public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.`is`, lhs.sqlExpression, rhs.sqlExpression)
|
||||
return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `IS NOT` SQL operator.
|
||||
@@ -325,8 +331,8 @@ extension SQLBinaryOperator {
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<` SQL operator.
|
||||
///
|
||||
/// // age < 18
|
||||
/// Column("age") < 18
|
||||
/// // score < 18
|
||||
/// Column("score") < 18
|
||||
public func < (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
@@ -341,8 +347,8 @@ public func < (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<` SQL operator.
|
||||
///
|
||||
/// // 18 < age
|
||||
/// 18 < Column("age")
|
||||
/// // 18 < score
|
||||
/// 18 < Column("score")
|
||||
public func < (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.lessThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
@@ -365,8 +371,8 @@ public func < (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<=` SQL operator.
|
||||
///
|
||||
/// // age <= 18
|
||||
/// Column("age") <= 18
|
||||
/// // score <= 18
|
||||
/// Column("score") <= 18
|
||||
public func <= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
@@ -381,8 +387,8 @@ public func <= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpressio
|
||||
|
||||
/// An SQL expression that compares two expressions with the `<=` SQL operator.
|
||||
///
|
||||
/// // 18 <= age
|
||||
/// 18 <= Column("age")
|
||||
/// // 18 <= score
|
||||
/// 18 <= Column("score")
|
||||
public func <= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.lessThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
@@ -405,15 +411,15 @@ public func <= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>` SQL operator.
|
||||
///
|
||||
/// // age > 18
|
||||
/// Column("age") > 18
|
||||
/// // score > 18
|
||||
/// Column("score") > 18
|
||||
public func > (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>` SQL operator.
|
||||
///
|
||||
/// // age > 'Arthur' COLLATE NOCASE
|
||||
/// // name > 'Arthur' COLLATE NOCASE
|
||||
/// Column("name").collating(.nocase) > "Arthur"
|
||||
public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionCollate(lhs.expression > rhs, collationName: lhs.collationName)
|
||||
@@ -421,8 +427,8 @@ public func > (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpression
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>` SQL operator.
|
||||
///
|
||||
/// // 18 > age
|
||||
/// 18 > Column("age")
|
||||
/// // 18 > score
|
||||
/// 18 > Column("score")
|
||||
public func > (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.greaterThan, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
@@ -445,8 +451,8 @@ public func > (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>=` SQL operator.
|
||||
///
|
||||
/// // age >= 18
|
||||
/// Column("age") >= 18
|
||||
/// // score >= 18
|
||||
/// Column("score") >= 18
|
||||
public func >= (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
@@ -461,16 +467,16 @@ public func >= (lhs: SQLCollatedExpression, rhs: SQLExpressible) -> SQLExpressio
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>=` SQL operator.
|
||||
///
|
||||
/// // 18 >= age
|
||||
/// 18 >= Column("age")
|
||||
/// // 18 >= score
|
||||
/// 18 >= Column("score")
|
||||
public func >= (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression {
|
||||
return SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that compares two expressions with the `>=` SQL operator.
|
||||
///
|
||||
/// // 'Arthur' >= age COLLATE NOCASE
|
||||
/// "Arthur" >= Column("age").collating(.nocase)
|
||||
/// // 'Arthur' >= name COLLATE NOCASE
|
||||
/// "Arthur" >= Column("name").collating(.nocase)
|
||||
public func >= (lhs: SQLExpressible, rhs: SQLCollatedExpression) -> SQLExpression {
|
||||
return SQLExpressionCollate(lhs >= rhs.expression, collationName: rhs.collationName)
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ extension Database {
|
||||
|
||||
/// Modifies a database table.
|
||||
///
|
||||
/// try db.alter(table: "persons") { t in
|
||||
/// try db.alter(table: "players") { t in
|
||||
/// t.add(column: "url", .text)
|
||||
/// }
|
||||
///
|
||||
@@ -126,7 +126,7 @@ extension Database {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Creates an index.
|
||||
///
|
||||
/// try db.create(index: "personByEmail", on: "person", columns: ["email"])
|
||||
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
|
||||
///
|
||||
/// SQLite can also index expressions (https://www.sqlite.org/expridx.html)
|
||||
/// and use specific collations. To create such an index, use a raw SQL
|
||||
@@ -154,7 +154,7 @@ extension Database {
|
||||
#else
|
||||
/// Creates an index.
|
||||
///
|
||||
/// try db.create(index: "personByEmail", on: "person", columns: ["email"])
|
||||
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"])
|
||||
///
|
||||
/// SQLite can also index expressions (https://www.sqlite.org/expridx.html)
|
||||
/// and use specific collations. To create such an index, use a raw SQL
|
||||
@@ -180,7 +180,7 @@ extension Database {
|
||||
|
||||
/// Creates a partial index.
|
||||
///
|
||||
/// try db.create(index: "personByEmail", on: "person", columns: ["email"], condition: Column("email") != nil)
|
||||
/// try db.create(index: "playerByEmail", on: "player", columns: ["email"], condition: Column("email") != nil)
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createindex.html, and
|
||||
/// https://www.sqlite.org/partialindex.html
|
||||
@@ -217,7 +217,7 @@ extension Database {
|
||||
/// You don't create instances of this class. Instead, you use the Database
|
||||
/// `create(table:)` method:
|
||||
///
|
||||
/// try db.create(table: "persons") { t in // t is TableDefinition
|
||||
/// try db.create(table: "players") { t in // t is TableDefinition
|
||||
/// t.column(...)
|
||||
/// }
|
||||
///
|
||||
@@ -244,18 +244,18 @@ public final class TableDefinition {
|
||||
|
||||
/// Appends a table column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("name", .text)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#tablecoldef
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
/// - parameter type: the column type.
|
||||
/// - parameter type: the eventual column type.
|
||||
/// - returns: An ColumnDefinition that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult
|
||||
public func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition {
|
||||
public func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition {
|
||||
let column = ColumnDefinition(name: name, type: type)
|
||||
columns.append(column)
|
||||
return column
|
||||
@@ -264,9 +264,9 @@ public final class TableDefinition {
|
||||
/// Defines the table primary key.
|
||||
///
|
||||
/// try db.create(table: "citizenships") { t in
|
||||
/// t.column("personID", .integer)
|
||||
/// t.column("citizenID", .integer)
|
||||
/// t.column("countryCode", .text)
|
||||
/// t.primaryKey(["personID", "countryCode"])
|
||||
/// t.primaryKey(["citizenID", "countryCode"])
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#primkeyconst and
|
||||
@@ -304,9 +304,9 @@ public final class TableDefinition {
|
||||
///
|
||||
/// try db.create(table: "passport") { t in
|
||||
/// t.column("issueDate", .date)
|
||||
/// t.column("personID", .integer)
|
||||
/// t.column("citizenID", .integer)
|
||||
/// t.column("countryCode", .text)
|
||||
/// t.foreignKey(["personID", "countryCode"], references: "citizenships", onDelete: .cascade)
|
||||
/// t.foreignKey(["citizenID", "countryCode"], references: "citizenships", onDelete: .cascade)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/foreignkeys.html
|
||||
@@ -327,7 +327,7 @@ public final class TableDefinition {
|
||||
|
||||
/// Adds a CHECK constraint.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("personalPhone", .text)
|
||||
/// t.column("workPhone", .text)
|
||||
/// let personalPhone = Column("personalPhone")
|
||||
@@ -344,7 +344,7 @@ public final class TableDefinition {
|
||||
|
||||
/// Adds a CHECK constraint.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("personalPhone", .text)
|
||||
/// t.column("workPhone", .text)
|
||||
/// t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL")
|
||||
@@ -358,95 +358,109 @@ public final class TableDefinition {
|
||||
}
|
||||
|
||||
fileprivate func sql(_ db: Database) throws -> String {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CREATE")
|
||||
if temporary {
|
||||
chunks.append("TEMPORARY")
|
||||
}
|
||||
chunks.append("TABLE")
|
||||
if ifNotExists {
|
||||
chunks.append("IF NOT EXISTS")
|
||||
}
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
|
||||
let primaryKeyColumns: [String]
|
||||
if let (columns, _) = primaryKeyConstraint {
|
||||
primaryKeyColumns = columns
|
||||
} else if let index = columns.index(where: { $0.primaryKey != nil }) {
|
||||
primaryKeyColumns = [columns[index].name]
|
||||
} else {
|
||||
primaryKeyColumns = []
|
||||
}
|
||||
var statements: [String] = []
|
||||
|
||||
do {
|
||||
var items: [String] = []
|
||||
try items.append(contentsOf: columns.map { try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) })
|
||||
var chunks: [String] = []
|
||||
chunks.append("CREATE")
|
||||
if temporary {
|
||||
chunks.append("TEMPORARY")
|
||||
}
|
||||
chunks.append("TABLE")
|
||||
if ifNotExists {
|
||||
chunks.append("IF NOT EXISTS")
|
||||
}
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
|
||||
if let (columns, conflictResolution) = primaryKeyConstraint {
|
||||
var chunks: [String] = []
|
||||
chunks.append("PRIMARY KEY")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
let primaryKeyColumns: [String]
|
||||
if let (columns, _) = primaryKeyConstraint {
|
||||
primaryKeyColumns = columns
|
||||
} else if let index = columns.index(where: { $0.primaryKey != nil }) {
|
||||
primaryKeyColumns = [columns[index].name]
|
||||
} else {
|
||||
// WITHOUT ROWID optimization requires a primary key. If the
|
||||
// user sets withoutRowID, but does not define a primary key,
|
||||
// this is undefined behavior.
|
||||
//
|
||||
// We thus can use the rowId column even when the withoutRowID
|
||||
// flag is set ;-)
|
||||
primaryKeyColumns = [Column.rowID.name]
|
||||
}
|
||||
|
||||
for (columns, conflictResolution) in uniqueKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("UNIQUE")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
do {
|
||||
var items: [String] = []
|
||||
try items.append(contentsOf: columns.map { try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) })
|
||||
|
||||
if let (columns, conflictResolution) = primaryKeyConstraint {
|
||||
var chunks: [String] = []
|
||||
chunks.append("PRIMARY KEY")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
|
||||
for (columns, conflictResolution) in uniqueKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("UNIQUE")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("FOREIGN KEY")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
chunks.append("REFERENCES")
|
||||
if let destinationColumns = destinationColumns {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if table == name {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else {
|
||||
let primaryKey = try db.primaryKey(table)
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
}
|
||||
if let deleteAction = deleteAction {
|
||||
chunks.append("ON DELETE")
|
||||
chunks.append(deleteAction.rawValue)
|
||||
}
|
||||
if let updateAction = updateAction {
|
||||
chunks.append("ON UPDATE")
|
||||
chunks.append(updateAction.rawValue)
|
||||
}
|
||||
if deferred {
|
||||
chunks.append("DEFERRABLE INITIALLY DEFERRED")
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
for checkExpression in checkConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CHECK")
|
||||
chunks.append("(" + checkExpression.sql + ")")
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
chunks.append("(\(items.joined(separator: ", ")))")
|
||||
}
|
||||
|
||||
for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("FOREIGN KEY")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
chunks.append("REFERENCES")
|
||||
if let destinationColumns = destinationColumns {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if table == name {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if let primaryKey = try db.primaryKey(table) {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else {
|
||||
// Programmer error
|
||||
fatalError("explicit referenced column(s) required, since table \(table) has no primary key")
|
||||
}
|
||||
if let deleteAction = deleteAction {
|
||||
chunks.append("ON DELETE")
|
||||
chunks.append(deleteAction.rawValue)
|
||||
}
|
||||
if let updateAction = updateAction {
|
||||
chunks.append("ON UPDATE")
|
||||
chunks.append(updateAction.rawValue)
|
||||
}
|
||||
if deferred {
|
||||
chunks.append("DEFERRABLE INITIALLY DEFERRED")
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
if withoutRowID {
|
||||
chunks.append("WITHOUT ROWID")
|
||||
}
|
||||
|
||||
for checkExpression in checkConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CHECK")
|
||||
chunks.append("(" + checkExpression.sql + ")")
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
chunks.append("(\(items.joined(separator: ", ")))")
|
||||
statements.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
if withoutRowID {
|
||||
chunks.append("WITHOUT ROWID")
|
||||
}
|
||||
return chunks.joined(separator: " ")
|
||||
let indexStatements = columns
|
||||
.flatMap { $0.indexDefinition(in: name) }
|
||||
.map { $0.sql() }
|
||||
statements.append(contentsOf: indexStatements)
|
||||
return statements.joined(separator: "; ")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -455,7 +469,7 @@ public final class TableDefinition {
|
||||
/// You don't create instances of this class. Instead, you use the Database
|
||||
/// `alter(table:)` method:
|
||||
///
|
||||
/// try db.alter(table: "persons") { t in // t is TableAlteration
|
||||
/// try db.alter(table: "players") { t in // t is TableAlteration
|
||||
/// t.add(column: ...)
|
||||
/// }
|
||||
///
|
||||
@@ -470,7 +484,7 @@ public final class TableAlteration {
|
||||
|
||||
/// Appends a column to the table.
|
||||
///
|
||||
/// try db.alter(table: "persons") { t in
|
||||
/// try db.alter(table: "players") { t in
|
||||
/// t.add(column: "url", .text)
|
||||
/// }
|
||||
///
|
||||
@@ -495,9 +509,13 @@ public final class TableAlteration {
|
||||
chunks.append("ALTER TABLE")
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
chunks.append("ADD COLUMN")
|
||||
try chunks.append(column.sql(db, tableName: nil, primaryKeyColumns: nil))
|
||||
try chunks.append(column.sql(db, tableName: name, primaryKeyColumns: nil))
|
||||
let statement = chunks.joined(separator: " ")
|
||||
statements.append(statement)
|
||||
|
||||
if let indexDefinition = column.indexDefinition(in: name) {
|
||||
statements.append(indexDefinition.sql())
|
||||
}
|
||||
}
|
||||
|
||||
return statements.joined(separator: "; ")
|
||||
@@ -508,35 +526,40 @@ public final class TableAlteration {
|
||||
///
|
||||
/// You get instances of this class when you create or alter a database table:
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column(...) // ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
/// try db.alter(table: "persons") { t in
|
||||
/// try db.alter(table: "players") { t in
|
||||
/// t.add(column: ...) // ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html and
|
||||
/// https://www.sqlite.org/lang_altertable.html
|
||||
public final class ColumnDefinition {
|
||||
enum Index {
|
||||
case none
|
||||
case index
|
||||
case unique(Database.ConflictResolution)
|
||||
}
|
||||
fileprivate let name: String
|
||||
private let type: Database.ColumnType
|
||||
private let type: Database.ColumnType?
|
||||
fileprivate var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)?
|
||||
private var index: Index = .none
|
||||
private var notNullConflictResolution: Database.ConflictResolution?
|
||||
private var uniqueConflictResolution: Database.ConflictResolution?
|
||||
private var checkConstraints: [SQLExpression] = []
|
||||
private var foreignKeyConstraints: [(table: String, column: String?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = []
|
||||
private var defaultExpression: SQLExpression?
|
||||
private var collationName: String?
|
||||
|
||||
init(name: String, type: Database.ColumnType) {
|
||||
init(name: String, type: Database.ColumnType?) {
|
||||
self.name = name
|
||||
self.type = type
|
||||
}
|
||||
|
||||
/// Adds a primary key constraint on the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("id", .integer).primaryKey()
|
||||
/// }
|
||||
///
|
||||
@@ -556,7 +579,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Adds a NOT NULL constraint on the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("name", .text).notNull()
|
||||
/// }
|
||||
///
|
||||
@@ -573,7 +596,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Adds a UNIQUE constraint on the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("email", .text).unique()
|
||||
/// }
|
||||
///
|
||||
@@ -584,13 +607,30 @@ public final class ColumnDefinition {
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
|
||||
uniqueConflictResolution = conflictResolution ?? .abort
|
||||
index = .unique(conflictResolution ?? .abort)
|
||||
return self
|
||||
}
|
||||
|
||||
/// Adds an index of the column.
|
||||
///
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("email", .text).indexed()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#uniqueconst
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
public func indexed() -> Self {
|
||||
if case .none = index {
|
||||
self.index = .index
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
/// Adds a CHECK constraint on the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("name", .text).check { length($0) > 0 }
|
||||
/// }
|
||||
///
|
||||
@@ -607,7 +647,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Adds a CHECK constraint on the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("name", .text).check(sql: "LENGTH(name) > 0")
|
||||
/// }
|
||||
///
|
||||
@@ -623,7 +663,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Defines the default column value.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("name", .text).defaults(to: "Anonymous")
|
||||
/// }
|
||||
///
|
||||
@@ -639,7 +679,7 @@ public final class ColumnDefinition {
|
||||
|
||||
/// Defines the default column value.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP")
|
||||
/// }
|
||||
///
|
||||
@@ -655,7 +695,7 @@ public final class ColumnDefinition {
|
||||
|
||||
// Defines the default column collation.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("email", .text).collate(.nocase)
|
||||
/// }
|
||||
///
|
||||
@@ -671,7 +711,7 @@ public final class ColumnDefinition {
|
||||
|
||||
// Defines the default column collation.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// try db.create(table: "players") { t in
|
||||
/// t.column("name", .text).collate(.localizedCaseInsensitiveCompare)
|
||||
/// }
|
||||
///
|
||||
@@ -708,10 +748,12 @@ public final class ColumnDefinition {
|
||||
return self
|
||||
}
|
||||
|
||||
fileprivate func sql(_ db: Database, tableName: String?, primaryKeyColumns: [String]?) throws -> String {
|
||||
fileprivate func sql(_ db: Database, tableName: String, primaryKeyColumns: [String]?) throws -> String {
|
||||
var chunks: [String] = []
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
chunks.append(type.rawValue)
|
||||
if let type = type {
|
||||
chunks.append(type.rawValue)
|
||||
}
|
||||
|
||||
if let (conflictResolution, autoincrement) = primaryKey {
|
||||
chunks.append("PRIMARY KEY")
|
||||
@@ -734,14 +776,19 @@ public final class ColumnDefinition {
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
|
||||
switch uniqueConflictResolution {
|
||||
switch index {
|
||||
case .none:
|
||||
break
|
||||
case .abort?:
|
||||
chunks.append("UNIQUE")
|
||||
case let conflictResolution?:
|
||||
chunks.append("UNIQUE ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
case .unique(let conflictResolution):
|
||||
switch conflictResolution {
|
||||
case .abort:
|
||||
chunks.append("UNIQUE")
|
||||
default:
|
||||
chunks.append("UNIQUE ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
case .index:
|
||||
break
|
||||
}
|
||||
|
||||
for checkConstraint in checkConstraints {
|
||||
@@ -762,14 +809,16 @@ public final class ColumnDefinition {
|
||||
for (table, column, deleteAction, updateAction, deferred) in foreignKeyConstraints {
|
||||
chunks.append("REFERENCES")
|
||||
if let column = column {
|
||||
// explicit reference
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))")
|
||||
} else if let tableName = tableName, let primaryKeyColumns = primaryKeyColumns, table == tableName {
|
||||
} else if table.lowercased() == tableName.lowercased() {
|
||||
// implicit autoreference
|
||||
let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(table).columns
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if let primaryKey = try db.primaryKey(table) {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else {
|
||||
// Programmer error
|
||||
fatalError("explicit referenced column required, since table \(table) has no primary key")
|
||||
// implicit external reference
|
||||
let primaryKeyColumns = try db.primaryKey(table).columns
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
}
|
||||
if let deleteAction = deleteAction {
|
||||
chunks.append("ON DELETE")
|
||||
@@ -786,6 +835,21 @@ public final class ColumnDefinition {
|
||||
|
||||
return chunks.joined(separator: " ")
|
||||
}
|
||||
|
||||
fileprivate func indexDefinition(in table: String) -> IndexDefinition? {
|
||||
switch index {
|
||||
case .none: return nil
|
||||
case .unique: return nil
|
||||
case .index:
|
||||
return IndexDefinition(
|
||||
name: "\(table)_on_\(name)",
|
||||
table: table,
|
||||
columns: [name],
|
||||
unique: false,
|
||||
ifNotExists: false,
|
||||
condition: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct IndexDefinition {
|
||||
|
||||
@@ -39,7 +39,7 @@ public protocol VirtualTableModule {
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Schema: Virtual Table
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// Creates a virtual database table.
|
||||
///
|
||||
|
||||
@@ -85,7 +85,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
if let isSameRecord = isSameRecord {
|
||||
itemsAreIdenticalFactory = { _ in { isSameRecord($0.record, $1.record) } }
|
||||
} else {
|
||||
itemsAreIdenticalFactory = { _ in { _ in false } }
|
||||
itemsAreIdenticalFactory = { _ in { _,_ in false } }
|
||||
}
|
||||
|
||||
try self.init(
|
||||
@@ -95,7 +95,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
}
|
||||
|
||||
fileprivate init<Request>(
|
||||
private init<Request>(
|
||||
_ databaseWriter: DatabaseWriter,
|
||||
request: Request,
|
||||
queue: DispatchQueue,
|
||||
@@ -211,11 +211,33 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
onChange: ((FetchedRecordsController<Record>, Record, FetchedRecordChange) -> ())? = nil,
|
||||
didChange: ((FetchedRecordsController<Record>) -> ())? = nil)
|
||||
{
|
||||
// I hate you SE-0110.
|
||||
let wrappedWillChange: ((FetchedRecordsController<Record>, Void) -> ())?
|
||||
if let willChange = willChange {
|
||||
wrappedWillChange = { (controller, _) in willChange(controller) }
|
||||
} else {
|
||||
wrappedWillChange = nil
|
||||
}
|
||||
|
||||
let wrappedDidChange: ((FetchedRecordsController<Record>, Void) -> ())?
|
||||
if let didChange = didChange {
|
||||
wrappedDidChange = { (controller, _) in didChange(controller) }
|
||||
} else {
|
||||
wrappedDidChange = nil
|
||||
}
|
||||
|
||||
trackChanges(
|
||||
fetchAlongside: { _ in },
|
||||
willChange: willChange.map { callback in { (controller, _) in callback(controller) } },
|
||||
willChange: wrappedWillChange,
|
||||
onChange: onChange,
|
||||
didChange: didChange.map { callback in { (controller, _) in callback(controller) } })
|
||||
didChange: wrappedDidChange)
|
||||
|
||||
// Without bloody SE-0110:
|
||||
// trackChanges(
|
||||
// fetchAlongside: { _ in },
|
||||
// willChange: willChange.map { callback in { (controller, _) in callback(controller) } },
|
||||
// onChange: onChange,
|
||||
// didChange: didChange.map { callback in { (controller, _) in callback(controller) } })
|
||||
}
|
||||
|
||||
/// Registers changes notification callbacks.
|
||||
@@ -348,16 +370,16 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
fileprivate var fetchedItems: [Item<Record>]?
|
||||
|
||||
/// The record comparator
|
||||
fileprivate var itemsAreIdentical: ItemComparator<Record>
|
||||
private var itemsAreIdentical: ItemComparator<Record>
|
||||
|
||||
/// The record comparator factory (support for request change)
|
||||
fileprivate let itemsAreIdenticalFactory: ItemComparatorFactory<Record>
|
||||
private let itemsAreIdenticalFactory: ItemComparatorFactory<Record>
|
||||
|
||||
/// The request
|
||||
fileprivate var request: Request
|
||||
|
||||
/// The observed selection info
|
||||
fileprivate var selectionInfo : SelectStatement.SelectionInfo
|
||||
private var selectionInfo : SelectStatement.SelectionInfo
|
||||
|
||||
/// The eventual current database observer
|
||||
private var observer: FetchedRecordsObserver<Record>?
|
||||
@@ -461,29 +483,25 @@ extension FetchedRecordsController where Record: TableMapping {
|
||||
// non-null value.
|
||||
let itemsAreIdenticalFactory: ItemComparatorFactory<Record> = { db in
|
||||
// Extract primary key columns from database table
|
||||
let columns: [String]
|
||||
if let primaryKey = try db.primaryKey(Record.databaseTableName) {
|
||||
columns = primaryKey.columns
|
||||
} else if Record.selectsRowID {
|
||||
columns = [Column.rowID.name]
|
||||
} else {
|
||||
// No primary key => can't compare rows
|
||||
return { _ in false }
|
||||
}
|
||||
let columns = try db.primaryKey(Record.databaseTableName).columns
|
||||
|
||||
// Compare primary keys
|
||||
assert(!columns.isEmpty)
|
||||
return { (lItem, rItem) in
|
||||
var notNullValue = false
|
||||
for column in columns {
|
||||
let lValue: DatabaseValue = lItem.row.value(named: column)
|
||||
let rValue: DatabaseValue = rItem.row.value(named: column)
|
||||
let lValue: DatabaseValue = lItem.row[column]
|
||||
let rValue: DatabaseValue = rItem.row[column]
|
||||
if lValue != rValue {
|
||||
// different primary keys
|
||||
return false
|
||||
}
|
||||
if !lValue.isNull || !rValue.isNull {
|
||||
notNullValue = true
|
||||
}
|
||||
}
|
||||
// identical primary keys
|
||||
return true
|
||||
// identical primary keys iff at least one value is not null
|
||||
return notNullValue
|
||||
}
|
||||
}
|
||||
try self.init(
|
||||
@@ -559,7 +577,7 @@ private final class FetchedRecordsObserver<Record: RowConvertible> : Transaction
|
||||
|
||||
// MARK: - Changes
|
||||
|
||||
fileprivate func makeFetchFunction<Record, T>(
|
||||
private func makeFetchFunction<Record, T>(
|
||||
controller: FetchedRecordsController<Record>,
|
||||
fetchAlongside: @escaping (Database) throws -> T,
|
||||
willProcessTransaction: @escaping () -> (),
|
||||
@@ -634,7 +652,7 @@ fileprivate func makeFetchFunction<Record, T>(
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func makeFetchAndNotifyChangesFunction<Record, T>(
|
||||
private func makeFetchAndNotifyChangesFunction<Record, T>(
|
||||
controller: FetchedRecordsController<Record>,
|
||||
fetchAlongside: @escaping (Database) throws -> T,
|
||||
itemsAreIdentical: @escaping ItemComparator<Record>,
|
||||
@@ -704,7 +722,7 @@ fileprivate func makeFetchAndNotifyChangesFunction<Record, T>(
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Record>], itemsAreIdentical: ItemComparator<Record>) -> [ItemChange<Record>] {
|
||||
private func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Record>], itemsAreIdentical: ItemComparator<Record>) -> [ItemChange<Record>] {
|
||||
let m = s.count
|
||||
let n = t.count
|
||||
|
||||
@@ -776,7 +794,7 @@ fileprivate func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Reco
|
||||
func changedValues(from oldRow: Row, to newRow: Row) -> [String: DatabaseValue] {
|
||||
var changedValues: [String: DatabaseValue] = [:]
|
||||
for (column, newValue) in newRow {
|
||||
let oldValue: DatabaseValue? = oldRow.value(named: column)
|
||||
let oldValue: DatabaseValue? = oldRow[column]
|
||||
if newValue != oldValue {
|
||||
changedValues[column] = oldValue
|
||||
}
|
||||
@@ -840,7 +858,7 @@ fileprivate func computeChanges<Record>(from s: [Item<Record>], to t: [Item<Reco
|
||||
return standardize(changes: d[m][n], itemsAreIdentical: itemsAreIdentical)
|
||||
}
|
||||
|
||||
fileprivate func identicalItemArrays<Record>(_ lhs: [Item<Record>], _ rhs: [Item<Record>]) -> Bool {
|
||||
private func identicalItemArrays<Record>(_ lhs: [Item<Record>], _ rhs: [Item<Record>]) -> Bool {
|
||||
guard lhs.count == rhs.count else {
|
||||
return false
|
||||
}
|
||||
@@ -855,8 +873,8 @@ fileprivate func identicalItemArrays<Record>(_ lhs: [Item<Record>], _ rhs: [Item
|
||||
|
||||
// MARK: - UITableView Support
|
||||
|
||||
fileprivate typealias ItemComparator<Record: RowConvertible> = (Item<Record>, Item<Record>) -> Bool
|
||||
fileprivate typealias ItemComparatorFactory<Record: RowConvertible> = (Database) throws -> ItemComparator<Record>
|
||||
private typealias ItemComparator<Record: RowConvertible> = (Item<Record>, Item<Record>) -> Bool
|
||||
private typealias ItemComparatorFactory<Record: RowConvertible> = (Database) throws -> ItemComparator<Record>
|
||||
|
||||
extension FetchedRecordsController {
|
||||
|
||||
@@ -986,8 +1004,6 @@ public enum FetchedRecordChange {
|
||||
}
|
||||
|
||||
extension FetchedRecordChange: CustomStringConvertible {
|
||||
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .insertion(let indexPath):
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
private struct PersistableKeyedEncodingContainer<Key: CodingKey> : KeyedEncodingContainerProtocol {
|
||||
let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void
|
||||
|
||||
init(encode: @escaping (_ value: DatabaseValueConvertible?, _ key: String) -> Void) {
|
||||
self.encode = encode
|
||||
}
|
||||
|
||||
/// The path of coding keys taken to get to this point in encoding.
|
||||
/// A `nil` value indicates an unkeyed container.
|
||||
var codingPath: [CodingKey] { return [] }
|
||||
|
||||
/// Encodes the given value for the given key.
|
||||
///
|
||||
/// - parameter value: The value to encode.
|
||||
/// - parameter key: The key to associate the value with.
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
mutating func encode(_ value: Bool, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Int, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Int8, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Int16, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Int32, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Int64, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: UInt, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: UInt8, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: UInt16, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: UInt32, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: UInt64, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Float, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: Double, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
mutating func encode(_ value: String, forKey key: Key) throws { encode(value, key.stringValue) }
|
||||
|
||||
/// Encodes the given value for the given key.
|
||||
///
|
||||
/// - parameter value: The value to encode.
|
||||
/// - parameter key: The key to associate the value with.
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
mutating func encode<T>(_ value: T, forKey key: Key) throws where T : Encodable {
|
||||
if T.self is DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible encoding over Decodable.
|
||||
// This allows us to encode Date as String, for example.
|
||||
encode((value as! DatabaseValueConvertible), key.stringValue)
|
||||
} else {
|
||||
try value.encode(to: PersistableEncoder(codingPath: [key], encode: encode))
|
||||
}
|
||||
}
|
||||
|
||||
// Provide explicit encoding of optionals, because default implementation does not encode nil values.
|
||||
mutating func encodeNil(forKey key: Key) throws { encode(nil, key.stringValue) }
|
||||
mutating func encodeIfPresent(_ value: Bool?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int8?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int16?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int32?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Int64?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Float?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: Double?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent(_ value: String?, forKey key: Key) throws { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
mutating func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T : Encodable { if let value = value { try encode(value, forKey: key) } else { try encodeNil(forKey: key) } }
|
||||
|
||||
/// Stores a keyed encoding container for the given key and returns it.
|
||||
///
|
||||
/// - parameter keyType: The key type to use for the container.
|
||||
/// - parameter key: The key to encode the container for.
|
||||
/// - returns: A new keyed encoding container.
|
||||
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
/// Stores an unkeyed encoding container for the given key and returns it.
|
||||
///
|
||||
/// - parameter key: The key to encode the container for.
|
||||
/// - returns: A new unkeyed encoding container.
|
||||
mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
/// Stores a new nested container for the default `super` key and returns a new `Encoder` instance for encoding `super` into that container.
|
||||
///
|
||||
/// Equivalent to calling `superEncoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
|
||||
///
|
||||
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
|
||||
mutating func superEncoder() -> Encoder {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
/// Stores a new nested container for the given key and returns a new `Encoder` instance for encoding `super` into that container.
|
||||
///
|
||||
/// - parameter key: The key to encode `super` for.
|
||||
/// - returns: A new `Encoder` to pass to `super.encode(to:)`.
|
||||
mutating func superEncoder(forKey key: Key) -> Encoder {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
|
||||
private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer {
|
||||
let key: CodingKey
|
||||
let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void
|
||||
|
||||
var codingPath: [CodingKey] { return [key] }
|
||||
|
||||
/// Encodes a null value.
|
||||
///
|
||||
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
func encodeNil() throws { encode(nil, key.stringValue) }
|
||||
|
||||
/// Encodes a single value of the given type.
|
||||
///
|
||||
/// - parameter value: The value to encode.
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
func encode(_ value: Bool) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Int) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Int8) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Int16) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Int32) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Int64) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: UInt) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: UInt8) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: UInt16) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: UInt32) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: UInt64) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Float) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: Double) throws { encode(value, key.stringValue) }
|
||||
func encode(_ value: String) throws { encode(value, key.stringValue) }
|
||||
|
||||
/// Encodes a single value of the given type.
|
||||
///
|
||||
/// - parameter value: The value to encode.
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
func encode<T>(_ value: T) throws where T : Encodable {
|
||||
if let dbValueConvertible = value as? DatabaseValueConvertible {
|
||||
// Prefer DatabaseValueConvertible encoding over Decodable.
|
||||
// This allows us to encode Date as String, for example.
|
||||
encode(dbValueConvertible.databaseValue, key.stringValue)
|
||||
} else {
|
||||
try value.encode(to: PersistableEncoder(codingPath: [key], encode: encode))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct PersistableEncoder : Encoder {
|
||||
/// The path of coding keys taken to get to this point in encoding.
|
||||
/// A `nil` value indicates an unkeyed container.
|
||||
var codingPath: [CodingKey]
|
||||
|
||||
/// Any contextual information set by the user for encoding.
|
||||
var userInfo: [CodingUserInfoKey : Any] = [:]
|
||||
|
||||
let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void
|
||||
|
||||
init(codingPath: [CodingKey], encode: @escaping (_ value: DatabaseValueConvertible?, _ key: String) -> Void) {
|
||||
self.codingPath = codingPath
|
||||
self.encode = encode
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding multiple values keyed by the given key type.
|
||||
///
|
||||
/// - parameter type: The key type to use for the container.
|
||||
/// - returns: A new keyed encoding container.
|
||||
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
|
||||
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
|
||||
// Asked for a keyed type: top level required
|
||||
guard codingPath.isEmpty else {
|
||||
fatalError("unkeyed encoding is not supported")
|
||||
}
|
||||
return KeyedEncodingContainer(PersistableKeyedEncodingContainer<Key>(encode: encode))
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding multiple unkeyed values.
|
||||
///
|
||||
/// - returns: A new empty unkeyed container.
|
||||
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
|
||||
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
fatalError("unkeyed encoding is not supported")
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding a single primitive value.
|
||||
///
|
||||
/// - returns: A new empty single value container.
|
||||
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
|
||||
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
|
||||
/// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call.
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
return DatabaseValueEncodingContainer(key: codingPath.last!, encode: encode)
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistable where Self: Encodable {
|
||||
public func encode(to container: inout PersistenceContainer) {
|
||||
// The inout container parameter won't enter an escaping closure since
|
||||
// SE-0035: https://github.com/apple/swift-evolution/blob/master/proposals/0035-limit-inout-capture.md
|
||||
//
|
||||
// So let's use it in a non-escaping closure:
|
||||
func encode(_ encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void) {
|
||||
withoutActuallyEscaping(encode) { escapableEncode in
|
||||
let encoder = PersistableEncoder(codingPath: [], encode: escapableEncode)
|
||||
try! self.encode(to: encoder)
|
||||
}
|
||||
}
|
||||
encode { (value, key) in
|
||||
container[key] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
+154
-27
@@ -1,3 +1,15 @@
|
||||
extension Database.ConflictResolution {
|
||||
var invalidatesLastInsertedRowID: Bool {
|
||||
switch self {
|
||||
case .abort, .fail, .rollback, .replace:
|
||||
return false
|
||||
case .ignore:
|
||||
// Statement may have succeeded without inserting any row
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - PersistenceError
|
||||
|
||||
/// An error thrown by a type that adopts Persistable.
|
||||
@@ -9,7 +21,6 @@ public enum PersistenceError: Error {
|
||||
}
|
||||
|
||||
extension PersistenceError : CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .recordNotFound(let persistable):
|
||||
@@ -18,13 +29,12 @@ extension PersistenceError : CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - PersistenceContainer
|
||||
|
||||
/// Use persistence containers in the `encode(to:)` method of your
|
||||
/// persistable records:
|
||||
///
|
||||
/// struct Person : MutablePersistable {
|
||||
/// struct Player : MutablePersistable {
|
||||
/// var id: Int64?
|
||||
/// var name: String?
|
||||
///
|
||||
@@ -38,12 +48,20 @@ public struct PersistenceContainer {
|
||||
fileprivate var storage: [String: DatabaseValueConvertible?]
|
||||
|
||||
/// Accesses the value associated with the given column.
|
||||
///
|
||||
/// It is undefined behavior to set different values for the same column.
|
||||
/// Column names are case insensitive, so defining both "name" and "NAME"
|
||||
/// is considered undefined behavior.
|
||||
public subscript(_ column: String) -> DatabaseValueConvertible? {
|
||||
get { return storage[column] ?? nil }
|
||||
set { storage.updateValue(newValue, forKey: column) }
|
||||
}
|
||||
|
||||
/// Accesses the value associated with the given column.
|
||||
///
|
||||
/// It is undefined behavior to set different values for the same column.
|
||||
/// Column names are case insensitive, so defining both "name" and "NAME"
|
||||
/// is considered undefined behavior.
|
||||
public subscript(_ column: Column) -> DatabaseValueConvertible? {
|
||||
get { return self[column.name] }
|
||||
set { self[column.name] = newValue }
|
||||
@@ -124,7 +142,6 @@ extension Row {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - MutablePersistable
|
||||
|
||||
/// The MutablePersistable protocol uses this type in order to handle SQLite
|
||||
@@ -170,7 +187,7 @@ public protocol MutablePersistable : TableMapping {
|
||||
///
|
||||
/// Primary key columns, if any, must be included.
|
||||
///
|
||||
/// struct Person : MutablePersistable {
|
||||
/// struct Player : MutablePersistable {
|
||||
/// var id: Int64?
|
||||
/// var name: String?
|
||||
///
|
||||
@@ -179,6 +196,10 @@ public protocol MutablePersistable : TableMapping {
|
||||
/// container["name"] = name
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// It is undefined behavior to set different values for the same column.
|
||||
/// Column names are case insensitive, so defining both "name" and "NAME"
|
||||
/// is considered undefined behavior.
|
||||
func encode(to container: inout PersistenceContainer)
|
||||
|
||||
/// Notifies the record that it was succesfully inserted.
|
||||
@@ -189,7 +210,7 @@ public protocol MutablePersistable : TableMapping {
|
||||
///
|
||||
/// This method is optional: the default implementation does nothing.
|
||||
///
|
||||
/// struct Person : MutablePersistable {
|
||||
/// struct Player : MutablePersistable {
|
||||
/// var id: Int64?
|
||||
/// var name: String?
|
||||
///
|
||||
@@ -203,7 +224,6 @@ public protocol MutablePersistable : TableMapping {
|
||||
/// - column: The name of the eventual INTEGER PRIMARY KEY column.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?)
|
||||
|
||||
|
||||
// MARK: - CRUD
|
||||
|
||||
/// Executes an INSERT statement.
|
||||
@@ -289,6 +309,13 @@ public protocol MutablePersistable : TableMapping {
|
||||
func exists(_ db: Database) throws -> Bool
|
||||
}
|
||||
|
||||
extension MutablePersistable {
|
||||
/// A dictionary whose keys are the columns encoded in the `encode(to:)` method.
|
||||
public var databaseDictionary: [String: DatabaseValue] {
|
||||
return PersistenceContainer(self).storage.mapValues { $0?.databaseValue ?? .null }
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistable {
|
||||
/// Describes the conflict policy for insertions and updates.
|
||||
///
|
||||
@@ -304,7 +331,6 @@ extension MutablePersistable {
|
||||
public mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
}
|
||||
|
||||
|
||||
// MARK: - CRUD
|
||||
|
||||
/// Executes an INSERT statement.
|
||||
@@ -332,7 +358,7 @@ extension MutablePersistable {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Iterator.Element == Column {
|
||||
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Element == Column {
|
||||
try update(db, columns: Set(columns.map { $0.name }))
|
||||
}
|
||||
|
||||
@@ -343,7 +369,7 @@ extension MutablePersistable {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database.
|
||||
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Iterator.Element == String {
|
||||
public func update<Sequence: Swift.Sequence>(_ db: Database, columns: Sequence) throws where Sequence.Element == String {
|
||||
try update(db, columns: Set(columns))
|
||||
}
|
||||
|
||||
@@ -383,13 +409,12 @@ extension MutablePersistable {
|
||||
return try performExists(db)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - CRUD Internals
|
||||
|
||||
/// Return true if record has a non-null primary key
|
||||
fileprivate func canUpdate(_ db: Database) throws -> Bool {
|
||||
let databaseTableName = type(of: self).databaseTableName
|
||||
let primaryKey = try db.primaryKey(databaseTableName) ?? PrimaryKeyInfo.hiddenRowID
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
let container = PersistenceContainer(self)
|
||||
for column in primaryKey.columns {
|
||||
if let value = container[caseInsensitive: column], !value.databaseValue.isNull {
|
||||
@@ -502,15 +527,117 @@ extension MutablePersistable {
|
||||
|
||||
}
|
||||
|
||||
extension Database.ConflictResolution {
|
||||
var invalidatesLastInsertedRowID: Bool {
|
||||
switch self {
|
||||
case .abort, .fail, .rollback, .replace:
|
||||
return false
|
||||
case .ignore:
|
||||
// Statement may have succeeded without inserting any row
|
||||
return true
|
||||
extension MutablePersistable {
|
||||
|
||||
// MARK: - Deleting All
|
||||
|
||||
/// Deletes all records; returns the number of deleted rows.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: The number of deleted rows
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database) throws -> Int {
|
||||
return try all().deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistable {
|
||||
|
||||
// MARK: - Deleting by Single-Column Primary Key
|
||||
|
||||
/// Delete records identified by their primary keys; returns the number of
|
||||
/// deleted rows.
|
||||
///
|
||||
/// // DELETE FROM players WHERE id IN (1, 2, 3)
|
||||
/// try Player.deleteAll(db, keys: [1, 2, 3])
|
||||
///
|
||||
/// // DELETE FROM countries WHERE code IN ('FR', 'US', 'DE')
|
||||
/// try Country.deleteAll(db, keys: ["FR", "US", "DE"])
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM documents WHERE rowid IN (1, 2, 3)
|
||||
/// try Document.deleteAll(db, keys: [1, 2, 3])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible {
|
||||
let keys = Array(keys)
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(db, keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by its primary key; returns whether a
|
||||
/// database row was deleted.
|
||||
///
|
||||
/// // DELETE FROM players WHERE id = 123
|
||||
/// try Player.deleteOne(db, key: 123)
|
||||
///
|
||||
/// // DELETE FROM countries WHERE code = 'FR'
|
||||
/// try Country.deleteOne(db, key: "FR")
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM documents WHERE rowid = 1
|
||||
/// try Document.deleteOne(db, key: 1)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A primary key value.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool {
|
||||
guard let key = key else {
|
||||
// Avoid hitting the database
|
||||
return false
|
||||
}
|
||||
return try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistable {
|
||||
|
||||
// MARK: - Deleting by Key
|
||||
|
||||
/// Delete records identified by the provided unique keys (primary key or
|
||||
/// any key with a unique index on it); returns the number of deleted rows.
|
||||
///
|
||||
/// try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - keys: An array of key dictionaries.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int {
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(db, keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by a unique key (the primary key or any key
|
||||
/// with a unique index on it); returns whether a database row was deleted.
|
||||
///
|
||||
/// Player.deleteOne(db, key: ["name": Arthur"])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A dictionary of values.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool {
|
||||
return try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
}
|
||||
|
||||
@@ -679,7 +806,7 @@ final class DAO {
|
||||
|
||||
init(_ db: Database, _ record: MutablePersistable) throws {
|
||||
let databaseTableName = type(of: record).databaseTableName
|
||||
let primaryKey = try db.primaryKey(databaseTableName) ?? PrimaryKeyInfo.hiddenRowID
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
let persistenceContainer = PersistenceContainer(record)
|
||||
|
||||
GRDBPrecondition(!persistenceContainer.isEmpty, "\(type(of: record)): invalid empty persistence container")
|
||||
@@ -696,7 +823,7 @@ final class DAO {
|
||||
onConflict: onConflict,
|
||||
tableName: databaseTableName,
|
||||
insertedColumns: persistenceContainer.columns)
|
||||
let statement = try db.updateStatement(query.sql, fromCache: .grdb)
|
||||
let statement = try db.internalCachedUpdateStatement(query.sql)
|
||||
statement.unsafeSetArguments(StatementArguments(persistenceContainer.values))
|
||||
return statement
|
||||
}
|
||||
@@ -715,8 +842,8 @@ final class DAO {
|
||||
var updatedColumns: [String] = []
|
||||
for column in columns {
|
||||
let lowercaseColumn = column.lowercased()
|
||||
// Make sure the requested column is present in persistenceContainer
|
||||
GRDBPrecondition(lowercasePersistentColumns.contains(lowercaseColumn), "column \(column) can't be updated because it is missing from persistence container")
|
||||
// Don't update columns that are not present in the persistenceContainer
|
||||
guard lowercasePersistentColumns.contains(lowercaseColumn) else { continue }
|
||||
// Don't update primary key columns
|
||||
guard !lowercasePrimaryKeyColumns.contains(lowercaseColumn) else { continue }
|
||||
updatedColumns.append(column)
|
||||
@@ -742,7 +869,7 @@ final class DAO {
|
||||
tableName: databaseTableName,
|
||||
updatedColumns: updatedColumns,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
let statement = try db.updateStatement(query.sql, fromCache: .grdb)
|
||||
let statement = try db.internalCachedUpdateStatement(query.sql)
|
||||
statement.unsafeSetArguments(StatementArguments(updatedValues + primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
@@ -759,7 +886,7 @@ final class DAO {
|
||||
let query = DeleteQuery(
|
||||
tableName: databaseTableName,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
let statement = try db.updateStatement(query.sql, fromCache: .grdb)
|
||||
let statement = try db.internalCachedUpdateStatement(query.sql)
|
||||
statement.unsafeSetArguments(StatementArguments(primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
@@ -776,7 +903,7 @@ final class DAO {
|
||||
let query = ExistsQuery(
|
||||
tableName: databaseTableName,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
let statement = try db.selectStatement(query.sql, fromCache: .grdb)
|
||||
let statement = try db.internalCachedSelectStatement(query.sql)
|
||||
statement.unsafeSetArguments(StatementArguments(primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
|
||||
+54
-15
@@ -30,9 +30,9 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
/// This table name is required by the insert, update, save, delete,
|
||||
/// and exists methods.
|
||||
///
|
||||
/// class Person : Record {
|
||||
/// class Player : Record {
|
||||
/// override class var databaseTableName: String {
|
||||
/// return "persons"
|
||||
/// return "players"
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
@@ -60,20 +60,37 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
return PersistenceConflictPolicy(insert: .abort, update: .abort)
|
||||
}
|
||||
|
||||
/// This flag tells whether the hidden "rowid" column should be fetched
|
||||
/// with other columns.
|
||||
/// The default request selection.
|
||||
///
|
||||
/// Its default value is false:
|
||||
/// Unless this method is overriden, requests select all columns:
|
||||
///
|
||||
/// // SELECT * FROM persons
|
||||
/// try Person.fetchAll(db)
|
||||
/// // SELECT * FROM players
|
||||
/// try Player.fetchAll(db)
|
||||
///
|
||||
/// When true, the rowid column is fetched:
|
||||
/// You can override this property and provide an explicit list
|
||||
/// of columns:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons
|
||||
/// try Person.fetchAll(db)
|
||||
open class var selectsRowID: Bool {
|
||||
return false
|
||||
/// class RestrictedPlayer : Record {
|
||||
/// override static var databaseSelection: [SQLSelectable] {
|
||||
/// return [Column("id"), Column("name")]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id, name FROM players
|
||||
/// try RestrictedPlayer.fetchAll(db)
|
||||
///
|
||||
/// You can also add extra columns such as the `rowid` column:
|
||||
///
|
||||
/// class ExtendedPlayer : Player {
|
||||
/// override static var databaseSelection: [SQLSelectable] {
|
||||
/// return [AllColumns(), Column.rowID]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, rowid FROM players
|
||||
/// try ExtendedPlayer.fetchAll(db)
|
||||
open class var databaseSelection: [SQLSelectable] {
|
||||
return [AllColumns()]
|
||||
}
|
||||
|
||||
|
||||
@@ -84,7 +101,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
///
|
||||
/// Primary key columns, if any, must be included.
|
||||
///
|
||||
/// class Person : Record {
|
||||
/// class Player : Record {
|
||||
/// var id: Int64?
|
||||
/// var name: String?
|
||||
///
|
||||
@@ -107,7 +124,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
///
|
||||
/// The implementation of the base Record class does nothing.
|
||||
///
|
||||
/// class Person : Record {
|
||||
/// class Player : Record {
|
||||
/// var id: Int64?
|
||||
/// var name: String?
|
||||
///
|
||||
@@ -196,7 +213,7 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
// Loop until we find a change, or exhaust columns:
|
||||
while let (column, newValue) = newValueIterator.next() {
|
||||
let new = newValue?.databaseValue ?? .null
|
||||
guard let oldRow = oldRow, let old: DatabaseValue = oldRow.value(named: column) else {
|
||||
guard let oldRow = oldRow, let old: DatabaseValue = oldRow[column] else {
|
||||
return (column: column, old: nil)
|
||||
}
|
||||
if new != old {
|
||||
@@ -284,6 +301,28 @@ open class Record : RowConvertible, TableMapping, Persistable {
|
||||
referenceRow = Row(dao.persistenceContainer)
|
||||
}
|
||||
|
||||
/// If the record has been changed, executes an UPDATE statement so that
|
||||
/// those changes and only those changes are saved in the database.
|
||||
///
|
||||
/// On success, this method sets the *hasPersistentChangedValues* flag
|
||||
/// to false.
|
||||
///
|
||||
/// This method is guaranteed to have saved the eventual changes in the
|
||||
/// database if it returns without error.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter columns: The columns to update.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
/// PersistenceError.recordNotFound is thrown if the primary key does not
|
||||
/// match any row in the database and record could not be updated.
|
||||
final public func updateChanges(_ db: Database) throws {
|
||||
let changedColumns = Set(persistentChangedValues.keys)
|
||||
guard !changedColumns.isEmpty else {
|
||||
return
|
||||
}
|
||||
try update(db, columns: changedColumns)
|
||||
}
|
||||
|
||||
/// Executes an INSERT or an UPDATE statement so that `self` is saved in
|
||||
/// the database.
|
||||
///
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
private struct RowKeyedDecodingContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
|
||||
let row: Row
|
||||
|
||||
init(row: Row) {
|
||||
self.row = row
|
||||
}
|
||||
|
||||
/// The path of coding keys taken to get to this point in decoding.
|
||||
/// A `nil` value indicates an unkeyed container.
|
||||
var codingPath: [CodingKey] { return [] }
|
||||
|
||||
/// All the keys the `Decoder` has for this container.
|
||||
///
|
||||
/// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type.
|
||||
var allKeys: [Key] {
|
||||
return row.columnNames.flatMap { Key(stringValue: $0) }
|
||||
}
|
||||
|
||||
/// Returns whether the `Decoder` contains a value associated with the given key.
|
||||
///
|
||||
/// The value associated with the given key may be a null value as appropriate for the data format.
|
||||
///
|
||||
/// - parameter key: The key to search for.
|
||||
/// - returns: Whether the `Decoder` has an entry for the given key.
|
||||
func contains(_ key: Key) -> Bool {
|
||||
return row.hasColumn(key.stringValue)
|
||||
}
|
||||
|
||||
/// Decodes a null value for the given key.
|
||||
///
|
||||
/// - parameter key: The key that the decoded value is associated with.
|
||||
/// - returns: Whether the encountered value was null.
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
|
||||
func decodeNil(forKey key: Key) throws -> Bool {
|
||||
return row[key.stringValue] == nil
|
||||
}
|
||||
|
||||
/// Decodes a value of the given type for the given key.
|
||||
///
|
||||
/// - parameter type: The type of value to decode.
|
||||
/// - parameter key: The key that the decoded value is associated with.
|
||||
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
|
||||
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
|
||||
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return row[key.stringValue] }
|
||||
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return row[key.stringValue] }
|
||||
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return row[key.stringValue] }
|
||||
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return row[key.stringValue] }
|
||||
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return row[key.stringValue] }
|
||||
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return row[key.stringValue] }
|
||||
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return row[key.stringValue] }
|
||||
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return row[key.stringValue] }
|
||||
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return row[key.stringValue] }
|
||||
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return row[key.stringValue] }
|
||||
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return row[key.stringValue] }
|
||||
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return row[key.stringValue] }
|
||||
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return row[key.stringValue] }
|
||||
func decode(_ type: String.Type, forKey key: Key) throws -> String { return row[key.stringValue] }
|
||||
|
||||
/// Decodes a value of the given type for the given key.
|
||||
///
|
||||
/// - parameter type: The type of value to decode.
|
||||
/// - parameter key: The key that the decoded value is associated with.
|
||||
/// - returns: A value of the requested type, if present for the given key and convertible to the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value is not convertible to the requested type.
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
|
||||
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
|
||||
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable {
|
||||
let dbValue: DatabaseValue = row[key.stringValue]
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
return type.fromDatabaseValue(dbValue) as! T
|
||||
} else {
|
||||
return try T(from: RowDecoder(row: row, codingPath: codingPath + [key]))
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the data stored for the given key as represented in a container keyed by the given key type.
|
||||
///
|
||||
/// - parameter type: The key type to use for the container.
|
||||
/// - parameter key: The key that the nested container is associated with.
|
||||
/// - returns: A keyed decoding container view into `self`.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container.
|
||||
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
/// Returns the data stored for the given key as represented in an unkeyed container.
|
||||
///
|
||||
/// - parameter key: The key that the nested container is associated with.
|
||||
/// - returns: An unkeyed decoding container view into `self`.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container.
|
||||
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
/// Returns a `Decoder` instance for decoding `super` from the container associated with the default `super` key.
|
||||
///
|
||||
/// Equivalent to calling `superDecoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`.
|
||||
///
|
||||
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the default `super` key.
|
||||
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the default `super` key.
|
||||
public func superDecoder() throws -> Decoder {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
/// Returns a `Decoder` instance for decoding `super` from the container associated with the given key.
|
||||
///
|
||||
/// - parameter key: The key to decode `super` for.
|
||||
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
|
||||
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key.
|
||||
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for the given key.
|
||||
public func superDecoder(forKey key: Key) throws -> Decoder {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
|
||||
private struct RowSingleValueDecodingContainer: SingleValueDecodingContainer {
|
||||
let row: Row
|
||||
let column: CodingKey
|
||||
|
||||
var codingPath: [CodingKey] { return [] }
|
||||
|
||||
/// Decodes a null value.
|
||||
///
|
||||
/// - returns: Whether the encountered value was null.
|
||||
func decodeNil() -> Bool {
|
||||
return row[column.stringValue] == nil
|
||||
}
|
||||
|
||||
/// Decodes a single value of the given type.
|
||||
///
|
||||
/// - parameter type: The type to decode as.
|
||||
/// - returns: A value of the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
|
||||
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
|
||||
func decode(_ type: Bool.Type) throws -> Bool { return row[column.stringValue] }
|
||||
func decode(_ type: Int.Type) throws -> Int { return row[column.stringValue] }
|
||||
func decode(_ type: Int8.Type) throws -> Int8 { return row[column.stringValue] }
|
||||
func decode(_ type: Int16.Type) throws -> Int16 { return row[column.stringValue] }
|
||||
func decode(_ type: Int32.Type) throws -> Int32 { return row[column.stringValue] }
|
||||
func decode(_ type: Int64.Type) throws -> Int64 { return row[column.stringValue] }
|
||||
func decode(_ type: UInt.Type) throws -> UInt { return row[column.stringValue] }
|
||||
func decode(_ type: UInt8.Type) throws -> UInt8 { return row[column.stringValue] }
|
||||
func decode(_ type: UInt16.Type) throws -> UInt16 { return row[column.stringValue] }
|
||||
func decode(_ type: UInt32.Type) throws -> UInt32 { return row[column.stringValue] }
|
||||
func decode(_ type: UInt64.Type) throws -> UInt64 { return row[column.stringValue] }
|
||||
func decode(_ type: Float.Type) throws -> Float { return row[column.stringValue] }
|
||||
func decode(_ type: Double.Type) throws -> Double { return row[column.stringValue] }
|
||||
func decode(_ type: String.Type) throws -> String { return row[column.stringValue] }
|
||||
|
||||
/// Decodes a single value of the given type.
|
||||
///
|
||||
/// - parameter type: The type to decode as.
|
||||
/// - returns: A value of the requested type.
|
||||
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value cannot be converted to the requested type.
|
||||
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
|
||||
func decode<T>(_ type: T.Type) throws -> T where T : Decodable {
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
return type.fromDatabaseValue(row[column.stringValue]) as! T
|
||||
} else {
|
||||
return try T(from: RowDecoder(row: row, codingPath: [column]))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct RowDecoder: Decoder {
|
||||
let row: Row
|
||||
|
||||
init(row: Row, codingPath: [CodingKey]) {
|
||||
self.row = row
|
||||
self.codingPath = codingPath
|
||||
}
|
||||
|
||||
// Decoder
|
||||
let codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey : Any] { return [:] }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
|
||||
// Asked for a keyed type: top level required
|
||||
guard codingPath.isEmpty else {
|
||||
throw DecodingError.typeMismatch(
|
||||
RowDecoder.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "nested decoding is not supported"))
|
||||
}
|
||||
|
||||
return KeyedDecodingContainer(RowKeyedDecodingContainer<Key>(row: row))
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
throw DecodingError.typeMismatch(
|
||||
UnkeyedDecodingContainer.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
// Asked for a value type: column name required
|
||||
guard let codingKey = codingPath.last else {
|
||||
throw DecodingError.typeMismatch(
|
||||
RowDecoder.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "single value decoding requires a coding key"))
|
||||
}
|
||||
return RowSingleValueDecodingContainer(row: row, column: codingKey)
|
||||
}
|
||||
}
|
||||
|
||||
extension RowConvertible where Self: Decodable {
|
||||
/// Initializes a record from `row`.
|
||||
public init(row: Row) {
|
||||
try! self.init(from: RowDecoder(row: row, codingPath: []))
|
||||
}
|
||||
}
|
||||
@@ -4,8 +4,9 @@ extension RowConvertible where Self: TableMapping {
|
||||
|
||||
/// A cursor over all records fetched from the database.
|
||||
///
|
||||
/// let persons = try Person.fetchCursor(db) // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() { // Person
|
||||
/// // SELECT * FROM players
|
||||
/// let players = try Player.fetchCursor(db) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
@@ -16,16 +17,25 @@ extension RowConvertible where Self: TableMapping {
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispath queue.
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database) throws -> DatabaseCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database) throws -> RecordCursor<Self> {
|
||||
return try all().fetchCursor(db)
|
||||
}
|
||||
|
||||
/// An array of all records fetched from the database.
|
||||
///
|
||||
/// let persons = try Person.fetchAll(db) // [Person]
|
||||
/// // SELECT * FROM players
|
||||
/// let players = try Player.fetchAll(db) // [Player]
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@@ -35,7 +45,12 @@ extension RowConvertible where Self: TableMapping {
|
||||
|
||||
/// The first found record.
|
||||
///
|
||||
/// let person = try Person.fetchOne(db) // Person?
|
||||
/// // SELECT * FROM players
|
||||
/// let player = try Player.fetchOne(db) // Player?
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@@ -50,8 +65,8 @@ extension RowConvertible where Self: TableMapping {
|
||||
|
||||
/// Returns a cursor over records, given their primary keys.
|
||||
///
|
||||
/// let persons = try Person.fetchCursor(db, keys: [1, 2, 3]) // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() {
|
||||
/// let players = try Player.fetchCursor(db, keys: [1, 2, 3]) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
@@ -62,16 +77,13 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> DatabaseCursor<Self>? where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
guard let statement = try makeFetchByPrimaryKeyStatement(db, keys: keys) else {
|
||||
return nil
|
||||
}
|
||||
return try fetchCursor(statement)
|
||||
public static func fetchCursor<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> RecordCursor<Self> where Sequence.Element: DatabaseValueConvertible {
|
||||
return try filter(db, keys: keys).fetchCursor(db)
|
||||
}
|
||||
|
||||
/// Returns an array of records, given their primary keys.
|
||||
///
|
||||
/// let persons = try Person.fetchAll(db, keys: [1, 2, 3]) // [Person]
|
||||
/// let players = try Player.fetchAll(db, keys: [1, 2, 3]) // [Player]
|
||||
///
|
||||
/// The order of records in the returned array is undefined.
|
||||
///
|
||||
@@ -80,16 +92,18 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> [Self] where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
guard let statement = try makeFetchByPrimaryKeyStatement(db, keys: keys) else {
|
||||
public static func fetchAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> [Self] where Sequence.Element: DatabaseValueConvertible {
|
||||
let keys = Array(keys)
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return []
|
||||
}
|
||||
return try fetchAll(statement)
|
||||
return try filter(db, keys: keys).fetchAll(db)
|
||||
}
|
||||
|
||||
/// Returns a single record given its primary key.
|
||||
///
|
||||
/// let person = try Person.fetchOne(db, key: 123) // Person?
|
||||
/// let player = try Player.fetchOne(db, key: 123) // Player?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
@@ -98,43 +112,10 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Self? {
|
||||
guard let key = key else {
|
||||
// Avoid hitting the database
|
||||
return nil
|
||||
}
|
||||
return try fetchOne(makeFetchByPrimaryKeyStatement(db, keys: [key])!)
|
||||
}
|
||||
|
||||
// Returns "SELECT * FROM table WHERE id IN (?,?,?)"
|
||||
//
|
||||
// Returns nil if values is empty.
|
||||
private static func makeFetchByPrimaryKeyStatement<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> SelectStatement? where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
// Fail early if database table does not exist.
|
||||
let databaseTableName = self.databaseTableName
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
|
||||
// Fail early if database table has not one column in its primary key
|
||||
let columns = primaryKey?.columns ?? []
|
||||
GRDBPrecondition(columns.count <= 1, "requires single column primary key in table: \(databaseTableName)")
|
||||
let column = columns.first ?? Column.rowID.name
|
||||
|
||||
let keys = Array(keys)
|
||||
switch keys.count {
|
||||
case 0:
|
||||
// Avoid performing useless SELECT
|
||||
return nil
|
||||
case 1:
|
||||
// SELECT * FROM table WHERE id = ?
|
||||
let sql = "SELECT \(defaultSelection) FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?"
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
statement.arguments = StatementArguments(keys)
|
||||
return statement
|
||||
case let count:
|
||||
// SELECT * FROM table WHERE id IN (?,?,?)
|
||||
let keysSQL = databaseQuestionMarks(count: count)
|
||||
let sql = "SELECT \(defaultSelection) FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(keysSQL))"
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
statement.arguments = StatementArguments(keys)
|
||||
return statement
|
||||
}
|
||||
return try filter(db, keys: [key]).fetchOne(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,8 +126,8 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// Returns a cursor over records identified by the provided unique keys
|
||||
/// (primary key or any key with a unique index on it).
|
||||
///
|
||||
/// let persons = try Person.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() { // Person
|
||||
/// let players = try Player.fetchCursor(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
@@ -157,17 +138,14 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - keys: An array of key dictionaries.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> DatabaseCursor<Self>? {
|
||||
guard let statement = try makeFetchByKeyStatement(db, keys: keys) else {
|
||||
return nil
|
||||
}
|
||||
return try fetchCursor(statement)
|
||||
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor<Self> {
|
||||
return try filter(db, keys: keys).fetchCursor(db)
|
||||
}
|
||||
|
||||
/// Returns an array of records identified by the provided unique keys
|
||||
/// (primary key or any key with a unique index on it).
|
||||
///
|
||||
/// let persons = try Person.fetchAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // [Person]
|
||||
/// let players = try Player.fetchAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]]) // [Player]
|
||||
///
|
||||
/// The order of records in the returned array is undefined.
|
||||
///
|
||||
@@ -177,16 +155,18 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> [Self] {
|
||||
guard let statement = try makeFetchByKeyStatement(db, keys: keys) else {
|
||||
let keys = Array(keys)
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return []
|
||||
}
|
||||
return try fetchAll(statement)
|
||||
return try filter(db, keys: keys).fetchAll(db)
|
||||
}
|
||||
|
||||
/// Returns a single record identified by a unique key (the primary key or
|
||||
/// any key with a unique index on it).
|
||||
///
|
||||
/// let person = try Person.fetchOne(db, key: ["name": Arthur"]) // Person?
|
||||
/// let player = try Player.fetchOne(db, key: ["name": Arthur"]) // Player?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
@@ -194,54 +174,6 @@ extension RowConvertible where Self: TableMapping {
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self? {
|
||||
return try fetchOne(makeFetchByKeyStatement(db, keys: [key])!)
|
||||
}
|
||||
|
||||
// Returns "SELECT * FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ...
|
||||
//
|
||||
// Returns nil if keys is empty.
|
||||
//
|
||||
// If there is no unique index on the columns, the method raises a fatal
|
||||
// (unless fatalErrorOnMissingUniqueIndex is false, for testability).
|
||||
static func makeFetchByKeyStatement(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> SelectStatement? {
|
||||
// Avoid performing useless SELECT
|
||||
guard keys.count > 0 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let databaseTableName = self.databaseTableName
|
||||
var arguments: [DatabaseValueConvertible?] = []
|
||||
var whereClauses: [String] = []
|
||||
for dictionary in keys {
|
||||
GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary")
|
||||
let columns = Array(dictionary.keys)
|
||||
guard let orderedColumns = try db.columnsForUniqueKey(columns, in: databaseTableName) else {
|
||||
let error = DatabaseError(resultCode: .SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.sorted().joined(separator: ", "))")
|
||||
if fatalErrorOnMissingUniqueIndex {
|
||||
// Programmer error
|
||||
fatalError(error.description)
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
arguments.append(contentsOf: orderedColumns.map { orderedColumn in
|
||||
dictionary.first { (column, value) in column.lowercased() == orderedColumn.lowercased() }!.value
|
||||
})
|
||||
whereClauses.append("(" + (orderedColumns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")")
|
||||
}
|
||||
|
||||
let whereClause = whereClauses.joined(separator: " OR ")
|
||||
let sql = "SELECT \(defaultSelection) FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)"
|
||||
let statement = try db.makeSelectStatement(sql)
|
||||
statement.arguments = StatementArguments(arguments)
|
||||
return statement
|
||||
}
|
||||
|
||||
fileprivate static var defaultSelection: String {
|
||||
if selectsRowID {
|
||||
return "*, rowid"
|
||||
} else {
|
||||
return "*"
|
||||
}
|
||||
return try filter(db, keys: [key]).fetchOne(db)
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,25 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// Types that adopt RowConvertible can be initialized from a database Row.
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, "SELECT ...")!
|
||||
/// let person = Person(row)
|
||||
/// let player = Player(row)
|
||||
///
|
||||
/// The protocol comes with built-in methods that allow to fetch cursors,
|
||||
/// arrays, or single records:
|
||||
///
|
||||
/// try Person.fetchCursor(db, "SELECT ...", arguments:...) // DatabaseCursor<Person>
|
||||
/// try Person.fetchAll(db, "SELECT ...", arguments:...) // [Person]
|
||||
/// try Person.fetchOne(db, "SELECT ...", arguments:...) // Person?
|
||||
/// try Player.fetchCursor(db, "SELECT ...", arguments:...) // Cursor of Player
|
||||
/// try Player.fetchAll(db, "SELECT ...", arguments:...) // [Player]
|
||||
/// try Player.fetchOne(db, "SELECT ...", arguments:...) // Player?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT ...")
|
||||
/// try Person.fetchCursor(statement, arguments:...) // DatabaseCursor<Person>
|
||||
/// try Person.fetchAll(statement, arguments:...) // [Person]
|
||||
/// try Person.fetchOne(statement, arguments:...) // Person?
|
||||
/// try Player.fetchCursor(statement, arguments:...) // Cursor of Player
|
||||
/// try Player.fetchAll(statement, arguments:...) // [Player]
|
||||
/// try Player.fetchOne(statement, arguments:...) // Player?
|
||||
///
|
||||
/// RowConvertible is adopted by Record.
|
||||
public protocol RowConvertible {
|
||||
@@ -26,15 +32,49 @@ public protocol RowConvertible {
|
||||
init(row: Row)
|
||||
}
|
||||
|
||||
/// A cursor of records. For example:
|
||||
///
|
||||
/// struct Player : RowConvertible { ... }
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let players: RecordCursor<Player> = try Player.fetchCursor(db, "SELECT * FROM players")
|
||||
/// }
|
||||
public final class RecordCursor<Record: RowConvertible> : Cursor {
|
||||
private let statement: SelectStatement
|
||||
private let row: Row // Reused for performance
|
||||
private let sqliteStatement: SQLiteStatement
|
||||
private var done = false
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
self.row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
statement.cursorReset(arguments: arguments)
|
||||
}
|
||||
|
||||
public func next() throws -> Record? {
|
||||
if done { return nil }
|
||||
switch sqlite3_step(sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
done = true
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Record(row: row)
|
||||
case let code:
|
||||
statement.database.selectStatementDidFail(statement)
|
||||
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension RowConvertible {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
/// A cursor over records fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
|
||||
/// let persons = try Person.fetchCursor(statement) // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() { // Person
|
||||
/// let statement = try db.makeSelectStatement("SELECT * FROM players")
|
||||
/// let players = try Player.fetchCursor(statement) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
@@ -49,17 +89,14 @@ extension RowConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseCursor<Self> {
|
||||
// Reuse a single mutable row for performance.
|
||||
// It is the record's responsibility to copy the row if needed.
|
||||
let row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
return statement.cursor(arguments: arguments, next: { self.init(row: row) })
|
||||
public static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> {
|
||||
return try RecordCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of records fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
|
||||
/// let persons = try Person.fetchAll(statement) // [Person]
|
||||
/// let statement = try db.makeSelectStatement("SELECT * FROM players")
|
||||
/// let players = try Player.fetchAll(statement) // [Player]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
@@ -73,8 +110,8 @@ extension RowConvertible {
|
||||
|
||||
/// Returns a single record fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement("SELECT * FROM persons")
|
||||
/// let person = try Person.fetchOne(statement) // Person?
|
||||
/// let statement = try db.makeSelectStatement("SELECT * FROM players")
|
||||
/// let player = try Player.fetchOne(statement) // Player?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
@@ -94,8 +131,8 @@ extension RowConvertible {
|
||||
/// Returns a cursor over records fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("firstName")
|
||||
/// let request = Person.order(nameColumn)
|
||||
/// let identities = try Identity.fetchCursor(db, request) // DatabaseCursor<Identity>
|
||||
/// let request = Player.order(nameColumn)
|
||||
/// let identities = try Identity.fetchCursor(db, request) // Cursor of Identity
|
||||
/// while let identity = try identities.next() { // Identity
|
||||
/// ...
|
||||
/// }
|
||||
@@ -110,7 +147,7 @@ extension RowConvertible {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database, _ request: Request) throws -> RecordCursor<Self> {
|
||||
let (statement, adapter) = try request.prepare(db)
|
||||
return try fetchCursor(statement, adapter: adapter)
|
||||
}
|
||||
@@ -118,7 +155,7 @@ extension RowConvertible {
|
||||
/// Returns an array of records fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.order(nameColumn)
|
||||
/// let request = Player.order(nameColumn)
|
||||
/// let identities = try Identity.fetchAll(db, request) // [Identity]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -131,7 +168,7 @@ extension RowConvertible {
|
||||
/// Returns a single record fetched from a fetch request.
|
||||
///
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Person.order(nameColumn)
|
||||
/// let request = Player.order(nameColumn)
|
||||
/// let identity = try Identity.fetchOne(db, request) // Identity?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -148,8 +185,8 @@ extension RowConvertible {
|
||||
|
||||
/// Returns a cursor over records fetched from an SQL query.
|
||||
///
|
||||
/// let persons = try Person.fetchCursor(db, "SELECT * FROM persons") // DatabaseCursor<Person>
|
||||
/// while let person = try persons.next() { // Person
|
||||
/// let players = try Player.fetchCursor(db, "SELECT * FROM players") // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
@@ -165,13 +202,13 @@ extension RowConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - 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 -> DatabaseCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> {
|
||||
return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of records fetched from an SQL query.
|
||||
///
|
||||
/// let persons = try Person.fetchAll(db, "SELECT * FROM persons") // [Person]
|
||||
/// let players = try Player.fetchAll(db, "SELECT * FROM players") // [Player]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
@@ -186,7 +223,7 @@ extension RowConvertible {
|
||||
|
||||
/// Returns a single record fetched from an SQL query.
|
||||
///
|
||||
/// let person = try Person.fetchOne(db, "SELECT * FROM persons") // Person?
|
||||
/// let player = try Player.fetchOne(db, "SELECT * FROM players") // Player?
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
|
||||
+79
-211
@@ -4,32 +4,56 @@
|
||||
/// Types that adopt both TableMapping and RowConvertible are granted with
|
||||
/// built-in methods that allow to fetch instances identified by key:
|
||||
///
|
||||
/// try Person.fetchOne(db, key: 123) // Person?
|
||||
/// try Citizenship.fetchOne(db, key: ["personId": 12, "countryId": 45]) // Citizenship?
|
||||
/// try Player.fetchOne(db, key: 123) // Player?
|
||||
/// try Citizenship.fetchOne(db, key: ["citizenId": 12, "countryId": 45]) // Citizenship?
|
||||
///
|
||||
/// TableMapping is adopted by Record.
|
||||
public protocol TableMapping {
|
||||
/// The name of the database table
|
||||
/// The name of the database table used to build requests.
|
||||
///
|
||||
/// struct Player : TableMapping {
|
||||
/// static var databaseTableName = "players"
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM players
|
||||
/// try Player.fetchAll(db)
|
||||
static var databaseTableName: String { get }
|
||||
|
||||
/// This flag tells whether the hidden "rowid" column should be fetched
|
||||
/// with other columns.
|
||||
/// The default request selection.
|
||||
///
|
||||
/// Its default value is false:
|
||||
/// Unless said otherwise, requests select all columns:
|
||||
///
|
||||
/// // SELECT * FROM persons
|
||||
/// try Person.fetchAll(db)
|
||||
/// // SELECT * FROM players
|
||||
/// try Player.fetchAll(db)
|
||||
///
|
||||
/// When true, the rowid column is fetched:
|
||||
/// You can provide a custom implementation and provide an explicit list
|
||||
/// of columns:
|
||||
///
|
||||
/// // SELECT *, rowid FROM persons
|
||||
/// try Person.fetchAll(db)
|
||||
static var selectsRowID: Bool { get }
|
||||
/// struct RestrictedPlayer : TableMapping {
|
||||
/// static var databaseTableName = "players"
|
||||
/// static var databaseSelection = [Column("id"), Column("name")]
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id, name FROM players
|
||||
/// try RestrictedPlayer.fetchAll(db)
|
||||
///
|
||||
/// You can also add extra columns such as the `rowid` column:
|
||||
///
|
||||
/// struct ExtendedPlayer : TableMapping {
|
||||
/// static var databaseTableName = "players"
|
||||
/// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, rowid FROM players
|
||||
/// try ExtendedPlayer.fetchAll(db)
|
||||
static var databaseSelection: [SQLSelectable] { get }
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
/// Default value: false.
|
||||
public static var selectsRowID: Bool { return false }
|
||||
/// Default value: `[AllColumns()]`.
|
||||
public static var databaseSelection: [SQLSelectable] {
|
||||
return [AllColumns()]
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
@@ -46,219 +70,63 @@ extension TableMapping {
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Deleting All
|
||||
// MARK: Key Requests
|
||||
|
||||
/// Deletes all records; returns the number of deleted rows.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: The number of deleted rows
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database) throws -> Int {
|
||||
return try all().deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Deleting by Single-Column Primary Key
|
||||
|
||||
/// Delete records identified by their primary keys; returns the number of
|
||||
/// deleted rows.
|
||||
///
|
||||
/// try Person.deleteAll(db, keys: [1, 2, 3])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
guard let statement = try makeDeleteByPrimaryKeyStatement(db, keys: keys) else {
|
||||
return 0
|
||||
}
|
||||
try statement.execute()
|
||||
return db.changesCount
|
||||
}
|
||||
|
||||
/// Delete a record, identified by its primary key; returns whether a
|
||||
/// database row was deleted.
|
||||
///
|
||||
/// try Person.deleteOne(db, key: 123)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A primary key value.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool {
|
||||
guard let key = key else {
|
||||
return false
|
||||
}
|
||||
return try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
|
||||
// Returns "DELETE FROM table WHERE id IN (?,?,?)"
|
||||
//
|
||||
// Returns nil if keys is empty.
|
||||
private static func makeDeleteByPrimaryKeyStatement<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> UpdateStatement? where Sequence.Iterator.Element: DatabaseValueConvertible {
|
||||
// Fail early if database table does not exist.
|
||||
let databaseTableName = self.databaseTableName
|
||||
static func filter<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> QueryInterfaceRequest<Self> where Sequence.Element: DatabaseValueConvertible {
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
|
||||
// Fail early if database table has not one column in its primary key
|
||||
let columns = primaryKey?.columns ?? []
|
||||
GRDBPrecondition(columns.count <= 1, "requires single column primary key in table: \(databaseTableName)")
|
||||
let column = columns.first ?? Column.rowID.name
|
||||
let columns = primaryKey.columns.map { Column($0) }
|
||||
GRDBPrecondition(columns.count == 1, "table \(databaseTableName) has multiple columns in its primary key")
|
||||
let column = columns[0]
|
||||
|
||||
let keys = Array(keys)
|
||||
switch keys.count {
|
||||
case 0:
|
||||
// Avoid performing useless DELETE
|
||||
return nil
|
||||
return none()
|
||||
case 1:
|
||||
// DELETE FROM table WHERE id = ?
|
||||
let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) = ?"
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
statement.arguments = StatementArguments(keys)
|
||||
return statement
|
||||
case let count:
|
||||
// DELETE FROM table WHERE id IN (?,?,?)
|
||||
let keysSQL = databaseQuestionMarks(count: count)
|
||||
let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(column.quotedDatabaseIdentifier) IN (\(keysSQL))"
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
statement.arguments = StatementArguments(keys)
|
||||
return statement
|
||||
return filter(column == keys[0])
|
||||
default:
|
||||
return filter(keys.contains(column))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
|
||||
// MARK: Deleting by Key
|
||||
|
||||
/// Delete records identified by the provided unique keys (primary key or
|
||||
/// any key with a unique index on it); returns the number of deleted rows.
|
||||
///
|
||||
/// try Person.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - keys: An array of key dictionaries.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int {
|
||||
guard let statement = try makeDeleteByKeyStatement(db, keys: keys) else {
|
||||
return 0
|
||||
}
|
||||
try statement.execute()
|
||||
return db.changesCount
|
||||
}
|
||||
|
||||
/// Delete a record, identified by a unique key (the primary key or any key
|
||||
/// with a unique index on it); returns whether a database row was deleted.
|
||||
///
|
||||
/// Person.deleteOne(db, key: ["name": Arthur"])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A dictionary of values.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool {
|
||||
return try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
|
||||
// Returns "DELETE FROM table WHERE (a = ? AND b = ?) OR (a = ? AND b = ?) ...
|
||||
// Raises a fatal error if there is no unique index on the columns (unless
|
||||
// fatalErrorOnMissingUniqueIndex is false, for testability).
|
||||
//
|
||||
// Returns nil if keys is empty.
|
||||
//
|
||||
// If there is no unique index on the columns, the method raises a fatal
|
||||
// (unless fatalErrorOnMissingUniqueIndex is false, for testability).
|
||||
static func makeDeleteByKeyStatement(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> UpdateStatement? {
|
||||
// Avoid performing useless SELECT
|
||||
guard keys.count > 0 else {
|
||||
return nil
|
||||
}
|
||||
|
||||
let databaseTableName = self.databaseTableName
|
||||
var arguments: [DatabaseValueConvertible?] = []
|
||||
var whereClauses: [String] = []
|
||||
for dictionary in keys {
|
||||
GRDBPrecondition(dictionary.count > 0, "Invalid empty key dictionary")
|
||||
let columns = Array(dictionary.keys)
|
||||
guard let orderedColumns = try db.columnsForUniqueKey(columns, in: databaseTableName) else {
|
||||
let error = DatabaseError(resultCode: .SQLITE_MISUSE, message: "table \(databaseTableName) has no unique index on column(s) \(columns.sorted().joined(separator: ", "))")
|
||||
// TODO: think about
|
||||
// - allowing non unique keys in Type.fetchOne(db, key: ...) ???
|
||||
// - allowing non unique keys in Type.fetchAll/Cursor(db, keys: ...)
|
||||
// - forbidding nil values: Player.deleteOne(db, key: ["email": nil]) may delete several rows (case of a nullable unique key)
|
||||
static func filter(_ db: Database, keys: [[String: DatabaseValueConvertible?]], fatalErrorOnMissingUniqueIndex: Bool = true) throws -> QueryInterfaceRequest<Self> {
|
||||
// SELECT * FROM table WHERE ((a=? AND b=?) OR (c=? AND d=?) OR ...)
|
||||
let keyPredicates: [SQLExpression] = try keys.map { key in
|
||||
// Prevent filter(db, keys: [[:]])
|
||||
GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary")
|
||||
|
||||
// Prevent filter(db, 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: databaseTableName) else {
|
||||
let message = "table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))"
|
||||
if fatalErrorOnMissingUniqueIndex {
|
||||
fatalError(error.description)
|
||||
fatalError(message)
|
||||
} else {
|
||||
throw error
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: message)
|
||||
}
|
||||
}
|
||||
arguments.append(contentsOf: orderedColumns.map { orderedColumn in
|
||||
dictionary.first { (column, value) in column.lowercased() == orderedColumn.lowercased() }!.value
|
||||
})
|
||||
whereClauses.append("(" + (orderedColumns.map { "\($0.quotedDatabaseIdentifier) = ?" } as [String]).joined(separator: " AND ") + ")")
|
||||
|
||||
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 whereClause = whereClauses.joined(separator: " OR ")
|
||||
let sql = "DELETE FROM \(databaseTableName.quotedDatabaseIdentifier) WHERE \(whereClause)"
|
||||
let statement = try db.makeUpdateStatement(sql)
|
||||
statement.arguments = StatementArguments(arguments)
|
||||
return statement
|
||||
}
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
/// Returns a function that returns the primary key of a row.
|
||||
///
|
||||
/// If the table has no primary key, and selectsRowID is true, the primary
|
||||
/// key is the "rowid" column.
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let primaryKey = try Person.rowPrimaryKey(db)
|
||||
/// let row = try Row.fetchOne(db, "SELECT * FROM persons")!
|
||||
/// primaryKey(row) // ["id": 1]
|
||||
/// }
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
static func rowPrimaryKey(_ db: Database) throws -> (Row) -> [String: DatabaseValue] {
|
||||
if let primaryKey = try db.primaryKey(databaseTableName) {
|
||||
let columns = primaryKey.columns
|
||||
return { row in Dictionary(keys: columns) { row.value(named: $0) } }
|
||||
} else if selectsRowID {
|
||||
return { row in [Column.rowID.name: row.value(Column.rowID)] }
|
||||
} else {
|
||||
return { _ in [:] }
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a function that returns true if and only if two rows have the
|
||||
/// same primary key and both primary keys contain at least one non-null
|
||||
/// value.
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// let comparator = try Person.primaryKeyRowComparator(db)
|
||||
/// let row0 = Row(["id": nil, "name": "Unsaved"])
|
||||
/// let row1 = Row(["id": 1, "name": "Arthur"])
|
||||
/// let row2 = Row(["id": 1, "name": "Arthur"])
|
||||
/// let row3 = Row(["id": 2, "name": "Barbara"])
|
||||
/// comparator(row0, row0) // false
|
||||
/// comparator(row1, row2) // true
|
||||
/// comparator(row1, row3) // false
|
||||
/// }
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
/// - attention: This method is deprecated. It will be removed is the next
|
||||
/// major version of the library, without any replacement.
|
||||
@available(*, deprecated)
|
||||
public static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool {
|
||||
let primaryKey = try rowPrimaryKey(db)
|
||||
return { (lhs, rhs) in
|
||||
let (lhs, rhs) = (primaryKey(lhs), primaryKey(rhs))
|
||||
guard lhs.contains(where: { !$1.isNull }) else { return false }
|
||||
guard rhs.contains(where: { !$1.isNull }) else { return false }
|
||||
return lhs == rhs
|
||||
}
|
||||
guard let predicate = SQLBinaryOperator.or.join(keyPredicates) else {
|
||||
// No key
|
||||
return none()
|
||||
}
|
||||
|
||||
return filter(predicate)
|
||||
}
|
||||
}
|
||||
+28
-27
@@ -36,30 +36,39 @@ import Dispatch
|
||||
/// got 1
|
||||
/// got 3
|
||||
final class Pool<T> {
|
||||
var makeElement: (() throws -> T)?
|
||||
private var items: [PoolItem<T>] = []
|
||||
private let queue: DispatchQueue // protects items
|
||||
private class Item {
|
||||
let element: T
|
||||
var available: Bool
|
||||
|
||||
init(element: T, available: Bool) {
|
||||
self.element = element
|
||||
self.available = available
|
||||
}
|
||||
}
|
||||
|
||||
private let makeElement: () throws -> T
|
||||
private var items: ReadWriteBox<[Item]> = ReadWriteBox([])
|
||||
private let semaphore: DispatchSemaphore // limits the number of elements
|
||||
|
||||
init(maximumCount: Int, makeElement: (() throws -> T)? = nil) {
|
||||
init(maximumCount: Int, makeElement: @escaping () throws -> T) {
|
||||
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
|
||||
self.makeElement = makeElement
|
||||
self.queue = DispatchQueue(label: "GRDB.Pool")
|
||||
self.semaphore = DispatchSemaphore(value: maximumCount)
|
||||
}
|
||||
|
||||
/// Returns a tuple (element, releaseElement())
|
||||
/// Client MUST call releaseElement() after the element has been used.
|
||||
/// Returns a tuple (element, release)
|
||||
/// Client MUST call release() after the element has been used.
|
||||
func get() throws -> (T, () -> ()) {
|
||||
var item: PoolItem<T>! = nil
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
var item: Item! = nil
|
||||
do {
|
||||
try queue.sync {
|
||||
try items.write { items in
|
||||
if let availableItem = items.first(where: { $0.available }) {
|
||||
item = availableItem
|
||||
item.available = false
|
||||
} else {
|
||||
item = try PoolItem(element: makeElement!(), available: false)
|
||||
let element = try makeElement()
|
||||
item = Item(element: element, available: false)
|
||||
items.append(item)
|
||||
}
|
||||
}
|
||||
@@ -67,13 +76,15 @@ final class Pool<T> {
|
||||
semaphore.signal()
|
||||
throw error
|
||||
}
|
||||
let unlock = {
|
||||
self.queue.sync {
|
||||
let release = {
|
||||
self.items.write { _ in
|
||||
// This is why Item is a class, not a struct: so that we can
|
||||
// release it without having to find in it the items array.
|
||||
item.available = true
|
||||
}
|
||||
self.semaphore.signal()
|
||||
}
|
||||
return (item.element, unlock)
|
||||
return (item.element, release)
|
||||
}
|
||||
|
||||
/// Performs a synchronous block with an element. The element turns
|
||||
@@ -85,9 +96,9 @@ final class Pool<T> {
|
||||
}
|
||||
|
||||
/// Performs a block on each pool element, available or not.
|
||||
/// The block is run is some arbitrary queue.
|
||||
/// The block is run is some arbitrary dispatch queue.
|
||||
func forEach(_ body: (T) throws -> ()) rethrows {
|
||||
try queue.sync {
|
||||
try items.read { items in
|
||||
for item in items {
|
||||
try body(item.element)
|
||||
}
|
||||
@@ -102,19 +113,9 @@ final class Pool<T> {
|
||||
/// Empty the pool. Currently used items won't be reused.
|
||||
/// Eventual block is executed before any other element is dequeued.
|
||||
func clear(andThen block: () throws -> ()) rethrows {
|
||||
try queue.sync {
|
||||
items = []
|
||||
try items.write { items in
|
||||
items.removeAll()
|
||||
try block()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class PoolItem<T> {
|
||||
let element: T
|
||||
var available: Bool
|
||||
|
||||
init(element: T, available: Bool) {
|
||||
self.element = element
|
||||
self.available = available
|
||||
}
|
||||
}
|
||||
@@ -12,17 +12,15 @@ final class ReadWriteBox<T> {
|
||||
self.queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent])
|
||||
}
|
||||
|
||||
func read<U>(_ block: (T) -> U) -> U {
|
||||
var result: U? = nil
|
||||
queue.sync {
|
||||
result = block(self._value)
|
||||
func read<U>(_ block: (T) throws -> U) rethrows -> U {
|
||||
return try queue.sync {
|
||||
try block(_value)
|
||||
}
|
||||
return result!
|
||||
}
|
||||
|
||||
func write(_ block: (inout T) -> Void) {
|
||||
queue.sync(flags: [.barrier]) {
|
||||
block(&self._value)
|
||||
func write(_ block: (inout T) throws -> Void) rethrows {
|
||||
try queue.sync(flags: [.barrier]) {
|
||||
try block(&_value)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import Foundation
|
||||
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
// MARK: - Public
|
||||
|
||||
extension String {
|
||||
@@ -48,8 +44,6 @@ func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosu
|
||||
/// Custom precondition function which aims at solving
|
||||
/// https://bugs.swift.org/browse/SR-905 and
|
||||
/// https://github.com/groue/GRDB.swift/issues/37
|
||||
///
|
||||
/// TODO: remove this function when https://bugs.swift.org/browse/SR-905 is solved.
|
||||
if !condition() {
|
||||
fatalError(message, file: file, line: line)
|
||||
}
|
||||
@@ -69,21 +63,3 @@ extension Array {
|
||||
}
|
||||
}
|
||||
|
||||
extension Dictionary {
|
||||
|
||||
/// Create a dictionary with the keys and values in the given sequence.
|
||||
init<Sequence: Swift.Sequence>(keyValueSequence: Sequence) where Sequence.Iterator.Element == (Key, Value) {
|
||||
self.init(minimumCapacity: keyValueSequence.underestimatedCount)
|
||||
for (key, value) in keyValueSequence {
|
||||
self[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a dictionary from keys and a value builder.
|
||||
init<Sequence: Swift.Sequence>(keys: Sequence, value: (Key) -> Value) where Sequence.Iterator.Element == Key {
|
||||
self.init(minimumCapacity: keys.underestimatedCount)
|
||||
for key in keys {
|
||||
self[key] = value(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDBCipher'
|
||||
s.version = '1.1'
|
||||
s.version = '2.3.1'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
@@ -13,12 +13,12 @@ Pod::Spec.new do |s|
|
||||
s.osx.deployment_target = '10.9'
|
||||
s.watchos.deployment_target = '2.0'
|
||||
|
||||
s.source_files = 'GRDB/**/*.swift', 'SQLCipher/*.h', 'Support/grdb_config.{c,h}'
|
||||
s.source_files = 'GRDB/**/*.swift', 'SQLCipher/*.h', 'Support/grdb_config.h'
|
||||
s.module_map = 'SQLCipher/module.modulemap'
|
||||
s.xcconfig = {
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -DSQLITE_HAS_CODEC -DGRDBCIPHER',
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_HAS_CODEC -D GRDBCIPHER',
|
||||
'OTHER_CFLAGS' => '$(inherited) -DSQLITE_HAS_CODEC -DGRDBCIPHER',
|
||||
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) SQLITE_HAS_CODEC=1'
|
||||
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) SQLITE_HAS_CODEC=1 GRDBCIPHER=1'
|
||||
}
|
||||
s.framework = 'Foundation'
|
||||
s.dependency 'SQLCipher', '~> 3.4.1'
|
||||
|
||||
@@ -46,14 +46,14 @@ TEST_ACTIONS = clean build build-for-testing test-without-building
|
||||
# xcodebuild destination to run tests on iOS 8.1 (requires a pre-installed simulator)
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=8.1"
|
||||
|
||||
ifeq ($(XCODEVERSION),9.0)
|
||||
# xcodebuild destination to run tests on latest iOS (Xcode 9.0)
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 7,OS=11.0"
|
||||
else ifeq ($(XCODEVERSION),8.3)
|
||||
# xcodebuild destination to run tests on latest iOS (Xcode 8.3.3)
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 7,OS=10.3.1"
|
||||
ifeq ($(XCODEVERSION),9.2)
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.2"
|
||||
else ifeq ($(XCODEVERSION),9.1)
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.1"
|
||||
else ifeq ($(XCODEVERSION),9.0)
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0"
|
||||
else
|
||||
# Xcode < 8.3 is not supported
|
||||
# Xcode < 9.0 is not supported
|
||||
endif
|
||||
|
||||
# If xcpretty is available, use it for xcodebuild output
|
||||
@@ -204,7 +204,7 @@ test_install_GRDBCipher: SQLCipher
|
||||
|
||||
test_install_SPM:
|
||||
cd Tests/SPM && \
|
||||
$(SWIFT) package reset && \
|
||||
( if [ -a .build ] && [ -a Package.resolved ]; then $(SWIFT) package reset; fi ) && \
|
||||
rm -rf Packages/GRDB && \
|
||||
$(SWIFT) package edit GRDB --revision master && \
|
||||
rm -rf Packages/GRDB && \
|
||||
@@ -225,6 +225,13 @@ test_CarthageBuild: SQLiteCustom SQLCipher
|
||||
ifdef CARTHAGE
|
||||
rm -rf Carthage
|
||||
$(CARTHAGE) build --no-skip-current
|
||||
$(XCODEBUILD) \
|
||||
-project Tests/Carthage/GRDBiOS/iOS.xcodeproj \
|
||||
-scheme iOS \
|
||||
-configuration Release \
|
||||
-destination $(MAX_IOS_DESTINATION) \
|
||||
clean build \
|
||||
$(XCPRETTY)
|
||||
else
|
||||
@echo Carthage must be installed for test_CarthageBuild
|
||||
@exit 1
|
||||
@@ -233,13 +240,13 @@ endif
|
||||
test_performance: Realm FMDB SQLite.swift
|
||||
$(XCODEBUILD) \
|
||||
-project GRDB.xcodeproj \
|
||||
-scheme GRDBOSXPerformanceTests \
|
||||
-scheme GRDBOSXPerformanceComparisonTests \
|
||||
build-for-testing test-without-building
|
||||
|
||||
Realm: Tests/Performance/Realm/build/osx/swift-3.1/RealmSwift.framework
|
||||
Realm: Tests/Performance/Realm/build/osx/swift-4.0/RealmSwift.framework
|
||||
|
||||
# Makes sure the Tests/Performance/Realm submodule has been downloaded, and Realm framework has been built.
|
||||
Tests/Performance/Realm/build/osx/swift-3.1/RealmSwift.framework:
|
||||
Tests/Performance/Realm/build/osx/swift-4.0/RealmSwift.framework:
|
||||
$(GIT) submodule update --init --recursive Tests/Performance/Realm
|
||||
cd Tests/Performance/Realm && sh build.sh osx-swift
|
||||
|
||||
@@ -288,10 +295,10 @@ ifdef JAZZY
|
||||
--author 'Gwendal Roué' \
|
||||
--author_url https://github.com/groue \
|
||||
--github_url https://github.com/groue/GRDB.swift \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v1.1 \
|
||||
--module-version 1.1 \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.3.0 \
|
||||
--module-version 2.3 \
|
||||
--module GRDB \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/1.1/ \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/2.3/ \
|
||||
--output Documentation/Reference \
|
||||
--podspec GRDB.swift.podspec
|
||||
else
|
||||
@@ -304,16 +311,13 @@ endif
|
||||
# =======
|
||||
|
||||
distclean:
|
||||
$(SWIFT) package reset
|
||||
cd Tests/SPM && $(SWIFT) package reset
|
||||
rm -rf Documentation/Reference
|
||||
$(GIT) reset --hard
|
||||
$(GIT) clean -dffx .
|
||||
rm -rf Tests/Performance/fmdb && $(GIT) checkout -- Tests/Performance/fmdb
|
||||
rm -rf Tests/Performance/SQLite.swift && $(GIT) checkout -- Tests/Performance/SQLite.swift
|
||||
rm -rf Tests/Performance/Realm && $(GIT) checkout -- Tests/Performance/Realm
|
||||
rm -rf SQLCipher/src && $(GIT) checkout -- SQLCipher/src
|
||||
rm -rf SQLiteCustom/src && $(GIT) checkout -- SQLiteCustom/src
|
||||
find . -name xcuserdata | xargs rm -rf
|
||||
find . -name Package.pins | xargs rm -f
|
||||
|
||||
clean:
|
||||
$(SWIFT) package reset
|
||||
@@ -321,6 +325,6 @@ clean:
|
||||
rm -rf Documentation/Reference
|
||||
if [ -d SQLCipher/src ]; then cd SQLCipher/src && $(GIT) clean -f; fi
|
||||
if [ -a Tests/Performance/Realm/build.sh ]; then cd Tests/Performance/Realm && sh build.sh clean; fi
|
||||
find . -name Package.pins | xargs rm -f
|
||||
find . -name Package.resolved | xargs rm -f
|
||||
|
||||
.PHONY: distclean clean doc test SQLCipher SQLiteCustom
|
||||
+22
-16
@@ -1,23 +1,29 @@
|
||||
// swift-tools-version:4.0
|
||||
// The swift-tools-version declares the minimum version of Swift required to build this package.
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "GRDB",
|
||||
dependencies: [
|
||||
.Package(url: "https://github.com/groue/CSQLite.git", majorVersion: 0, minor: 2)
|
||||
products: [
|
||||
.library(name: "GRDB", targets: ["GRDB"]),
|
||||
],
|
||||
exclude: [
|
||||
"DemoApps",
|
||||
"Documentation",
|
||||
"GRDB.xcworkspace",
|
||||
"Playgrounds",
|
||||
"SQLCipher",
|
||||
"SQLiteCustom",
|
||||
"Support",
|
||||
"Tests/Carthage",
|
||||
"Tests/CocoaPods",
|
||||
"Tests/Crash",
|
||||
"Tests/GRDBCipher",
|
||||
"Tests/Performance",
|
||||
"Tests/SPM"
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/groue/CSQLite.git", from: "0.2.0"),
|
||||
],
|
||||
targets: [
|
||||
.target(name: "GRDB", path: "GRDB"),
|
||||
.testTarget(
|
||||
name: "GRDBTests",
|
||||
dependencies: ["GRDB"],
|
||||
path: "Tests",
|
||||
exclude: [
|
||||
"Carthage",
|
||||
"CocoaPods",
|
||||
"Crash",
|
||||
"GRDBCipher",
|
||||
"Performance",
|
||||
"SPM"
|
||||
])
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,101 @@
|
||||
// Issue156
|
||||
//
|
||||
// This playground exists as a test of issue #156, for which I'm not sure we
|
||||
// have a test today.
|
||||
|
||||
import Foundation
|
||||
import GRDB
|
||||
import PlaygroundSupport
|
||||
|
||||
class TestDeleteAll: NSObject {
|
||||
|
||||
let databasePool: DatabasePool
|
||||
let fetchedRecordsController: FetchedRecordsController<MyRecord>
|
||||
|
||||
override init() {
|
||||
// Init a databasePool & a fetchedRecordsController
|
||||
|
||||
let databasePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/myDatabase.sqlite"
|
||||
databasePool = try! DatabasePool(path: databasePath)
|
||||
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("1") { db in
|
||||
try! db.create(table: MyRecord.databaseTableName) { t in
|
||||
t.column(MyRecord.MyColumn.name, .text)
|
||||
}
|
||||
}
|
||||
try! migrator.migrate(databasePool)
|
||||
|
||||
fetchedRecordsController = try! FetchedRecordsController<MyRecord>(databasePool, request: MyRecord.all())
|
||||
try! fetchedRecordsController.performFetch()
|
||||
fetchedRecordsController.trackChanges { controller in
|
||||
print("RecordsDidChange triggered: number of records = \(controller.fetchedRecords.count)\n")
|
||||
}
|
||||
|
||||
super.init()
|
||||
run()
|
||||
}
|
||||
|
||||
func run() {
|
||||
insertThreeRecords()
|
||||
perform(#selector(deleteAllWithFilter), with: nil, afterDelay: 1)
|
||||
perform(#selector(insertThreeRecords), with: nil, afterDelay: 2)
|
||||
perform(#selector(deleteAll), with: nil, afterDelay: 3)
|
||||
perform(#selector(insertThreeRecords), with: nil, afterDelay: 4)
|
||||
}
|
||||
|
||||
@objc
|
||||
func insertThreeRecords() {
|
||||
print("Insert 3 records")
|
||||
let myRecord1 = MyRecord(myColumn: "1")
|
||||
let myRecord2 = MyRecord(myColumn: "2")
|
||||
let myRecord3 = MyRecord(myColumn: "3")
|
||||
try! databasePool.writeInTransaction { db in
|
||||
try myRecord1.save(db)
|
||||
try myRecord2.save(db)
|
||||
try myRecord3.save(db)
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
|
||||
@objc
|
||||
func deleteAllWithFilter() {
|
||||
print("Delete all records with filter(1 == 1).deleteAll(db)")
|
||||
_ = try! databasePool.write { db in
|
||||
try MyRecord.filter(1 == 1).deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
@objc
|
||||
func deleteAll() {
|
||||
print("Delete all records with deleteAll(db)")
|
||||
_ = try! databasePool.write { db in
|
||||
try MyRecord.deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
struct MyRecord: RowConvertible, TableMapping, Persistable {
|
||||
|
||||
static let MyColumn = Column("MyColumn")
|
||||
static var databaseTableName: String { return String(describing: self) }
|
||||
|
||||
let myColumn: String
|
||||
|
||||
init(myColumn: String) {
|
||||
self.myColumn = myColumn
|
||||
}
|
||||
|
||||
init(row: Row) {
|
||||
self.myColumn = row[MyRecord.MyColumn]
|
||||
}
|
||||
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container[MyRecord.MyColumn] = myColumn
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
TestDeleteAll()
|
||||
PlaygroundPage.current.needsIndefiniteExecution = true
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<playground version='5.0' target-platform='macos'>
|
||||
<timeline fileName='timeline.xctimeline'/>
|
||||
</playground>
|
||||
Loaded 100 of 232 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user