mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
+24
-1
@@ -1,6 +1,29 @@
|
||||
Release Notes
|
||||
=============
|
||||
|
||||
## 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)
|
||||
@@ -13,7 +36,7 @@ Released October 24, 2017 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
|
||||
```swift
|
||||
let request = Player.all()
|
||||
let sql = try request.asSQLRequest().sql
|
||||
let sql = try request.asSQLRequest(db).sql
|
||||
print(sql) // Prints "SELECT * FROM players"
|
||||
```
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
```sh
|
||||
cd [GRDB directory]
|
||||
git checkout v2.1.0
|
||||
git checkout v2.2.0
|
||||
git submodule update --init SQLiteCustom/src
|
||||
````
|
||||
|
||||
|
||||
@@ -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/2.1/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.1/Functions.html) functions:
|
||||
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/2.2/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/2.2/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/2.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.2/Protocols/SQLExpression.html) protocol.
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '2.1.0'
|
||||
s.version = '2.2.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
|
||||
@@ -566,6 +566,41 @@
|
||||
566AD8CB1D531BED002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; };
|
||||
566AD8CC1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; };
|
||||
566AD8CD1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; };
|
||||
566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91081FA4C3960012D5B0 /* Database+Statements.swift */; };
|
||||
566B910A1FA4C3970012D5B0 /* Database+Statements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91081FA4C3960012D5B0 /* Database+Statements.swift */; };
|
||||
566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91081FA4C3960012D5B0 /* Database+Statements.swift */; };
|
||||
566B910C1FA4C3970012D5B0 /* Database+Statements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91081FA4C3960012D5B0 /* Database+Statements.swift */; };
|
||||
566B910D1FA4C3970012D5B0 /* Database+Statements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91081FA4C3960012D5B0 /* Database+Statements.swift */; };
|
||||
566B910E1FA4C3970012D5B0 /* Database+Statements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91081FA4C3960012D5B0 /* Database+Statements.swift */; };
|
||||
566B910F1FA4C3970012D5B0 /* Database+Statements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91081FA4C3960012D5B0 /* Database+Statements.swift */; };
|
||||
566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */; };
|
||||
566B91141FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */; };
|
||||
566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */; };
|
||||
566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */; };
|
||||
566B91171FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */; };
|
||||
566B91181FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */; };
|
||||
566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */; };
|
||||
566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91221FA4CF810012D5B0 /* Database+Schema.swift */; };
|
||||
566B91241FA4CF810012D5B0 /* Database+Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91221FA4CF810012D5B0 /* Database+Schema.swift */; };
|
||||
566B91251FA4CF810012D5B0 /* Database+Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91221FA4CF810012D5B0 /* Database+Schema.swift */; };
|
||||
566B91261FA4CF810012D5B0 /* Database+Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91221FA4CF810012D5B0 /* Database+Schema.swift */; };
|
||||
566B91271FA4CF810012D5B0 /* Database+Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91221FA4CF810012D5B0 /* Database+Schema.swift */; };
|
||||
566B91281FA4CF810012D5B0 /* Database+Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91221FA4CF810012D5B0 /* Database+Schema.swift */; };
|
||||
566B91291FA4CF810012D5B0 /* Database+Schema.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91221FA4CF810012D5B0 /* Database+Schema.swift */; };
|
||||
566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
|
||||
566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
|
||||
566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
|
||||
566B912E1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
|
||||
566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
|
||||
566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
|
||||
566B91311FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; };
|
||||
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; };
|
||||
567156141CB141D0007DC145 /* DatabaseQueueInMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */; };
|
||||
567156171CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; };
|
||||
567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; };
|
||||
@@ -1827,34 +1862,6 @@
|
||||
remoteGlobalIDString = 56AFC9EE1CB1A8BB00F48B96;
|
||||
remoteInfo = GRDBCipheriOS;
|
||||
};
|
||||
56B14E8C1D4DAE54000BF4A3 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 560FC5501CB004AD0014AA8E /* sqlcipher.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 4C0041981BFC382400ED2AD5;
|
||||
remoteInfo = "SQLCipher iOS";
|
||||
};
|
||||
56B14E8E1D4DAE54000BF4A3 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 560FC5501CB004AD0014AA8E /* sqlcipher.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 4C0041B11BFC3B2200ED2AD5;
|
||||
remoteInfo = "SQLCipher OSX";
|
||||
};
|
||||
56B14E901D4DAE54000BF4A3 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 560FC5501CB004AD0014AA8E /* sqlcipher.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 4C0041C31BFC3CC000ED2AD5;
|
||||
remoteInfo = "SQLCipher tvOS";
|
||||
};
|
||||
56B14E921D4DAE54000BF4A3 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 560FC5501CB004AD0014AA8E /* sqlcipher.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 4C0041D61BFC3E2500ED2AD5;
|
||||
remoteInfo = "SQLCipher watchOS";
|
||||
};
|
||||
56B15D041CD4C33A00A24C8B /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */;
|
||||
@@ -2058,6 +2065,11 @@
|
||||
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLOperators.swift; sourceTree = "<group>"; };
|
||||
566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = "<group>"; };
|
||||
566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = "<group>"; };
|
||||
566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = "<group>"; };
|
||||
566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseCollation.swift; sourceTree = "<group>"; };
|
||||
566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = "<group>"; };
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = "<group>"; };
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = "<group>"; };
|
||||
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
5671566C1CB16729007DC145 /* GRDBCipherOSXEncryptedTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipherOSXEncryptedTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = "<group>"; };
|
||||
@@ -2521,10 +2533,6 @@
|
||||
560FC5511CB004AD0014AA8E /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B14E8D1D4DAE54000BF4A3 /* SQLCipher.framework */,
|
||||
56B14E8F1D4DAE54000BF4A3 /* SQLCipher.framework */,
|
||||
56B14E911D4DAE54000BF4A3 /* SQLCipher.framework */,
|
||||
56B14E931D4DAE54000BF4A3 /* SQLCipher.framework */,
|
||||
560FC5561CB004AD0014AA8E /* libsqlcipher.a */,
|
||||
);
|
||||
name = Products;
|
||||
@@ -2864,6 +2872,9 @@
|
||||
56A238701B9C75030082EB20 /* Configuration.swift */,
|
||||
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */,
|
||||
56A238711B9C75030082EB20 /* Database.swift */,
|
||||
566B91221FA4CF810012D5B0 /* Database+Schema.swift */,
|
||||
566B91081FA4C3960012D5B0 /* Database+Statements.swift */,
|
||||
566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */,
|
||||
56A238731B9C75030082EB20 /* DatabaseError.swift */,
|
||||
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */,
|
||||
560A37A31C8F625000949E71 /* DatabasePool.swift */,
|
||||
@@ -2879,7 +2890,9 @@
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
|
||||
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
|
||||
56A238781B9C75030082EB20 /* Statement.swift */,
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
|
||||
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
);
|
||||
path = Core;
|
||||
@@ -3682,34 +3695,6 @@
|
||||
remoteRef = 560FC5551CB004AD0014AA8E /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B14E8D1D4DAE54000BF4A3 /* SQLCipher.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = SQLCipher.framework;
|
||||
remoteRef = 56B14E8C1D4DAE54000BF4A3 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B14E8F1D4DAE54000BF4A3 /* SQLCipher.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = SQLCipher.framework;
|
||||
remoteRef = 56B14E8E1D4DAE54000BF4A3 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B14E911D4DAE54000BF4A3 /* SQLCipher.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = SQLCipher.framework;
|
||||
remoteRef = 56B14E901D4DAE54000BF4A3 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B14E931D4DAE54000BF4A3 /* SQLCipher.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = SQLCipher.framework;
|
||||
remoteRef = 56B14E921D4DAE54000BF4A3 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56B15D051CD4C33A00A24C8B /* SQLite.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
@@ -3971,16 +3956,20 @@
|
||||
56BF6D3E1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */,
|
||||
5636E9BD1D22574100B9B05F /* Request.swift in Sources */,
|
||||
56BB6EAA1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
566B910A1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
566B91241FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
|
||||
56CEB5121EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
|
||||
5659F4911EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
56CEB4F21EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */,
|
||||
560FC51C1CB003810014AA8E /* QueryInterfaceRequest.swift in Sources */,
|
||||
560FC51D1CB003810014AA8E /* SQLCollatedExpression.swift in Sources */,
|
||||
566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
56D1215B1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */,
|
||||
566475D41D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
56CEB5621EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
|
||||
56CEB4FB1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
5698AD361DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
566B91141FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
560FC51F1CB003810014AA8E /* CGFloat.swift in Sources */,
|
||||
5674A7091F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
5659F4A11EA8D997004A4992 /* Result.swift in Sources */,
|
||||
@@ -4021,6 +4010,7 @@
|
||||
560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */,
|
||||
560FC5331CB003810014AA8E /* Migration.swift in Sources */,
|
||||
560FC5341CB003810014AA8E /* QueryInterfaceSelectQueryDefinition.swift in Sources */,
|
||||
566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
|
||||
560FC5351CB003810014AA8E /* Statement.swift in Sources */,
|
||||
5690C3411D23E82A00E59934 /* Data.swift in Sources */,
|
||||
5659F4891EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
@@ -4252,6 +4242,7 @@
|
||||
5698AC7E1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
|
||||
5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
|
||||
565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */,
|
||||
566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
|
||||
5674A6FF1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */,
|
||||
56E06F181E85906E008AE2A4 /* Fixits-0.102.0.swift in Sources */,
|
||||
@@ -4273,9 +4264,11 @@
|
||||
56BF6D431DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */,
|
||||
565490C01D5AE236005622CB /* DatabaseWriter.swift in Sources */,
|
||||
565490C41D5AE236005622CB /* SchedulingWatchdog.swift in Sources */,
|
||||
566B91311FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
|
||||
56CEB54B1EAA359A00BFAF62 /* Column.swift in Sources */,
|
||||
565490CC1D5AE252005622CB /* (null) in Sources */,
|
||||
56BF6D351DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */,
|
||||
566B91291FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
|
||||
5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */,
|
||||
@@ -4290,10 +4283,12 @@
|
||||
565490E11D5AE252005622CB /* Persistable.swift in Sources */,
|
||||
56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */,
|
||||
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
565490C81D5AE252005622CB /* CGFloat.swift in Sources */,
|
||||
56F5ABDC1D814330001F60CB /* URL.swift in Sources */,
|
||||
565490D31D5AE252005622CB /* (null) in Sources */,
|
||||
566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
566B910F1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
565490DE1D5AE252005622CB /* QueryInterfaceSelectQueryDefinition.swift in Sources */,
|
||||
56F5ABDD1D814330001F60CB /* UUID.swift in Sources */,
|
||||
565490CB1D5AE252005622CB /* (null) in Sources */,
|
||||
@@ -4471,16 +4466,20 @@
|
||||
56BF6D411DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */,
|
||||
5636E9C01D22574100B9B05F /* Request.swift in Sources */,
|
||||
56BB6EAD1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
566B910D1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
566B91271FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
|
||||
56CEB5151EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
|
||||
5659F4941EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
56CEB4F51EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */,
|
||||
56AFC9F11CB1A8BB00F48B96 /* QueryInterfaceRequest.swift in Sources */,
|
||||
56AFC9F21CB1A8BB00F48B96 /* SQLCollatedExpression.swift in Sources */,
|
||||
566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
56D1215E1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */,
|
||||
566475D71D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
56CEB5651EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
|
||||
56CEB4FE1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
5698AD391DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
566B91171FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
56AFC9F31CB1A8BB00F48B96 /* Database.swift in Sources */,
|
||||
5674A7061F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
5659F4A41EA8D997004A4992 /* Result.swift in Sources */,
|
||||
@@ -4521,6 +4520,7 @@
|
||||
56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */,
|
||||
56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */,
|
||||
56AFCA091CB1A8BB00F48B96 /* QueryInterfaceSelectQueryDefinition.swift in Sources */,
|
||||
566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
|
||||
56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */,
|
||||
5690C3441D23E82A00E59934 /* Data.swift in Sources */,
|
||||
5659F48C1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
@@ -4849,6 +4849,7 @@
|
||||
5605F15A1C672E4000235C62 /* CGFloat.swift in Sources */,
|
||||
56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */,
|
||||
5605F1641C672E4000235C62 /* Date.swift in Sources */,
|
||||
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
|
||||
566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
@@ -4865,6 +4866,7 @@
|
||||
56CEB54F1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
|
||||
5605F16A1C672E4000235C62 /* NSString.swift in Sources */,
|
||||
566B910C1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
56A8C2331D1914540096E9D4 /* UUID.swift in Sources */,
|
||||
56BF6D321DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */,
|
||||
560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
|
||||
@@ -4886,6 +4888,7 @@
|
||||
5690C3431D23E82A00E59934 /* Data.swift in Sources */,
|
||||
5674A7001F307F600095F066 /* RowConvertible+Decodable.swift in Sources */,
|
||||
5674A6E91F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
56A238881B9C75030082EB20 /* Row.swift in Sources */,
|
||||
56CEB4F41EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */,
|
||||
@@ -4912,6 +4915,8 @@
|
||||
31A778841C6A4E0600F507F6 /* FetchedRecordsController.swift in Sources */,
|
||||
56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */,
|
||||
56CEB55D1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */,
|
||||
566B91261FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
|
||||
566B912E1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
|
||||
56CEB5641EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
|
||||
56873BEF1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */,
|
||||
564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */,
|
||||
@@ -5206,16 +5211,20 @@
|
||||
56BF6D3D1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */,
|
||||
5636E9BC1D22574100B9B05F /* Request.swift in Sources */,
|
||||
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
|
||||
56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
|
||||
5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
56CEB4F11EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */,
|
||||
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
|
||||
5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */,
|
||||
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
56D1215A1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */,
|
||||
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
56CEB5611EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
|
||||
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
5605F1591C672E4000235C62 /* CGFloat.swift in Sources */,
|
||||
5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
5659F4A01EA8D997004A4992 /* Result.swift in Sources */,
|
||||
@@ -5256,6 +5265,7 @@
|
||||
560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */,
|
||||
56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */,
|
||||
5605F1931C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */,
|
||||
566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
|
||||
56A2388B1B9C75030082EB20 /* Statement.swift in Sources */,
|
||||
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
|
||||
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
@@ -5296,16 +5306,20 @@
|
||||
56BF6D421DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */,
|
||||
5636E9C11D22574100B9B05F /* Request.swift in Sources */,
|
||||
F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */,
|
||||
566B910E1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
566B91281FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
|
||||
56CEB5161EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
|
||||
5659F4951EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
56CEB4F61EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */,
|
||||
56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */,
|
||||
566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
56D1215F1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */,
|
||||
566475D81D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
56CEB5661EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
|
||||
56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
566B91181FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
F3BA80181CFB2876003DC1BA /* SerializedDatabase.swift in Sources */,
|
||||
5674A7051F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
5659F4A51EA8D997004A4992 /* Result.swift in Sources */,
|
||||
@@ -5346,6 +5360,7 @@
|
||||
5657AB141D10899D006283EF /* URL.swift in Sources */,
|
||||
56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */,
|
||||
F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */,
|
||||
566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
|
||||
F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */,
|
||||
F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */,
|
||||
5659F48D1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
@@ -5525,16 +5540,20 @@
|
||||
56BF6D3F1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */,
|
||||
5636E9BE1D22574100B9B05F /* Request.swift in Sources */,
|
||||
F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */,
|
||||
566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
566B91251FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
|
||||
56CEB5131EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */,
|
||||
5659F4921EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
56CEB4F31EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */,
|
||||
56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */,
|
||||
566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
56D1215C1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */,
|
||||
566475D51D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
56CEB5631EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
|
||||
56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */,
|
||||
5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
5659F4A21EA8D997004A4992 /* Result.swift in Sources */,
|
||||
@@ -5575,6 +5594,7 @@
|
||||
5657AB111D10899D006283EF /* URL.swift in Sources */,
|
||||
56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */,
|
||||
F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */,
|
||||
566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
|
||||
F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */,
|
||||
F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */,
|
||||
5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
|
||||
@@ -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) {
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
+772
-2596
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
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import Foundation
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible {
|
||||
public struct ResultCode : RawRepresentable {
|
||||
public let rawValue: Int32
|
||||
|
||||
public init(rawValue: Int32) {
|
||||
@@ -25,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,
|
||||
@@ -155,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.
|
||||
@@ -221,7 +224,6 @@ public struct DatabaseError : Error {
|
||||
}
|
||||
|
||||
extension DatabaseError: CustomStringConvertible {
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
var description = "SQLite error \(resultCode.rawValue)"
|
||||
if let sql = sql {
|
||||
|
||||
@@ -10,8 +10,25 @@ import Foundation
|
||||
|
||||
/// 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*.
|
||||
///
|
||||
@@ -91,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
|
||||
@@ -121,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.
|
||||
@@ -155,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
|
||||
@@ -183,24 +194,12 @@ public final class DatabasePool {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
// MARK: - Not public
|
||||
|
||||
private let writer: SerializedDatabase
|
||||
private var readerConfig: Configuration
|
||||
private var readerPool: Pool<SerializedDatabase>! = nil // var and nil-initialized so that we can use `self` when creating readerPool in DatabasePool.init()
|
||||
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
private 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 {
|
||||
@@ -212,14 +211,10 @@ 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.
|
||||
///
|
||||
@@ -355,7 +350,6 @@ extension DatabasePool : DatabaseReader {
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -387,7 +381,6 @@ extension DatabasePool : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
@@ -417,10 +410,6 @@ extension DatabasePool : DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// =========================================================================
|
||||
// MARK: - DatabaseWriter
|
||||
|
||||
extension DatabasePool : DatabaseWriter {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
@@ -510,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,
|
||||
|
||||
@@ -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,23 +66,12 @@ 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.
|
||||
///
|
||||
@@ -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:
|
||||
private 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,14 +186,10 @@ 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.
|
||||
///
|
||||
@@ -261,7 +237,6 @@ extension DatabaseQueue : DatabaseReader {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -285,7 +260,6 @@ extension DatabaseQueue : DatabaseReader {
|
||||
inDatabase { $0.remove(function: function) }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
/// Add or redefine a collation.
|
||||
@@ -307,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)
|
||||
@@ -356,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)
|
||||
}
|
||||
|
||||
|
||||
@@ -221,6 +221,8 @@ public final class AnyDatabaseReader : DatabaseReader {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.read(block)
|
||||
}
|
||||
@@ -233,6 +235,8 @@ public final class AnyDatabaseReader : DatabaseReader {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
}
|
||||
@@ -241,6 +245,8 @@ public final class AnyDatabaseReader : DatabaseReader {
|
||||
base.remove(function: function)
|
||||
}
|
||||
|
||||
// MARK: - Collations
|
||||
|
||||
public func add(collation: DatabaseCollation) {
|
||||
base.add(collation: collation)
|
||||
}
|
||||
|
||||
@@ -11,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 {
|
||||
@@ -62,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.
|
||||
@@ -78,7 +77,6 @@ public struct DatabaseValue {
|
||||
self = convertible.databaseValue
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Extracting Value
|
||||
|
||||
/// Returns true if databaseValue is NULL.
|
||||
@@ -91,7 +89,6 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Not Public
|
||||
|
||||
init(storage: Storage) {
|
||||
@@ -147,10 +144,8 @@ public struct DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Hashable & Equatable
|
||||
|
||||
/// DatabaseValue adopts Hashable.
|
||||
extension DatabaseValue : Hashable {
|
||||
|
||||
/// The hash value
|
||||
@@ -207,7 +202,6 @@ extension DatabaseValue : Hashable {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Lossless conversions
|
||||
|
||||
extension DatabaseValue {
|
||||
@@ -286,10 +280,6 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - DatabaseValueConvertible & SQLExpressible & SQLExpression
|
||||
|
||||
/// DatabaseValue adopts DatabaseValueConvertible.
|
||||
extension DatabaseValue : DatabaseValueConvertible {
|
||||
/// Returns self
|
||||
public var databaseValue: DatabaseValue {
|
||||
@@ -303,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 {
|
||||
@@ -355,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:
|
||||
|
||||
@@ -30,9 +30,7 @@ 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
|
||||
@@ -132,7 +130,6 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
|
||||
@@ -136,6 +136,8 @@ public final class AnyDatabaseWriter : DatabaseWriter {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try base.read(block)
|
||||
}
|
||||
@@ -148,21 +150,11 @@ public final class AnyDatabaseWriter : DatabaseWriter {
|
||||
return try base.unsafeReentrantRead(block)
|
||||
}
|
||||
|
||||
public func add(function: DatabaseFunction) {
|
||||
base.add(function: function)
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
|
||||
try base.readFromCurrentState(block)
|
||||
}
|
||||
|
||||
public func remove(function: DatabaseFunction) {
|
||||
base.remove(function: function)
|
||||
}
|
||||
|
||||
public func add(collation: DatabaseCollation) {
|
||||
base.add(collation: collation)
|
||||
}
|
||||
|
||||
public func remove(collation: DatabaseCollation) {
|
||||
base.remove(collation: collation)
|
||||
}
|
||||
// MARK: - Writing in Database
|
||||
|
||||
public func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try base.write(block)
|
||||
@@ -171,8 +163,24 @@ public final class AnyDatabaseWriter : DatabaseWriter {
|
||||
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
return try base.unsafeReentrantWrite(block)
|
||||
}
|
||||
|
||||
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
|
||||
try base.readFromCurrentState(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)
|
||||
}
|
||||
}
|
||||
+22
-7
@@ -141,7 +141,7 @@ public struct SQLRequest : Request {
|
||||
public let sql: String
|
||||
public let arguments: StatementArguments?
|
||||
public let adapter: RowAdapter?
|
||||
private let statementCacheName: Database.StatementCacheName?
|
||||
private let cache: Cache?
|
||||
|
||||
/// Creates a new request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
@@ -157,7 +157,7 @@ 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
|
||||
@@ -172,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
|
||||
@@ -185,16 +185,31 @@ 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)
|
||||
}
|
||||
return (statement, adapter)
|
||||
}
|
||||
|
||||
/// There are two statement caches: one for statements generated by the
|
||||
/// user, and one for the statements generated by GRDB. Those are separated
|
||||
/// so that GRDB has no opportunity to inadvertently modify the arguments of
|
||||
/// user's cached statements.
|
||||
enum Cache {
|
||||
/// The public cache, for library user
|
||||
case `public`
|
||||
|
||||
/// The internal cache, for grdb
|
||||
case `internal`
|
||||
}
|
||||
}
|
||||
|
||||
/// The protocol for requests that know how to decode database rows.
|
||||
|
||||
+15
-16
@@ -7,6 +7,21 @@ import Foundation
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -51,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 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?
|
||||
|
||||
deinit {
|
||||
statementRef?.release()
|
||||
}
|
||||
@@ -830,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
|
||||
|
||||
+82
-60
@@ -12,6 +12,16 @@ public typealias SQLiteStatement = OpaquePointer
|
||||
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*,
|
||||
@@ -42,7 +52,12 @@ public class Statement {
|
||||
/// 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 {
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32) throws
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
@@ -135,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() {
|
||||
@@ -156,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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,13 +221,6 @@ public class Statement {
|
||||
try! validate(arguments: self.arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// Utility function for cursors
|
||||
func cursorReset(arguments: StatementArguments? = nil) {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
prepare(withArguments: arguments)
|
||||
reset()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -227,7 +235,7 @@ public class Statement {
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
/// }
|
||||
public final class SelectStatement : Statement {
|
||||
public final class SelectStatement : Statement, AuthorizedStatement {
|
||||
/// Information about the table and columns read by a SelectStatement
|
||||
public private(set) var selectionInfo: SelectionInfo
|
||||
|
||||
@@ -243,29 +251,38 @@ public final class SelectStatement : Statement {
|
||||
/// - 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 {
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
self.selectionInfo = SelectionInfo()
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags)
|
||||
Database.preconditionValidSelectStatement(sql: sql, authorizer: authorizer)
|
||||
|
||||
GRDBPrecondition(authorizer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
GRDBPrecondition(authorizer.transactionEffect == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
|
||||
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(
|
||||
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
@@ -284,9 +301,31 @@ public final class SelectStatement : Statement {
|
||||
func cursor(arguments: StatementArguments? = nil) -> StatementCursor {
|
||||
return StatementCursor(statement: self, 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 {
|
||||
/// 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)
|
||||
}
|
||||
@@ -311,24 +350,10 @@ public final class SelectStatement : Statement {
|
||||
self.init(isUnknown: false)
|
||||
}
|
||||
|
||||
static func unknown() -> SelectionInfo {
|
||||
return self.init(isUnknown: true)
|
||||
}
|
||||
|
||||
/// If true, selection is unknown
|
||||
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> = []
|
||||
|
||||
private init(isUnknown: Bool) {
|
||||
self.isUnknown = isUnknown
|
||||
}
|
||||
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
if isUnknown {
|
||||
return "unknown"
|
||||
@@ -394,22 +419,14 @@ public final class StatementCursor: Cursor {
|
||||
/// 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
|
||||
@@ -420,7 +437,7 @@ public final class UpdateStatement : Statement {
|
||||
/// when executed
|
||||
private(set) var needsTruncateOptimizationPreventionDuringExecution: Bool
|
||||
|
||||
private(set) var transactionStatementInfo: TransactionStatementInfo?
|
||||
private(set) var transactionEffect: TransactionEffect?
|
||||
private(set) var databaseEventKinds: [DatabaseEventKind]
|
||||
|
||||
/// Creates a prepared statement.
|
||||
@@ -435,7 +452,13 @@ public final class UpdateStatement : Statement {
|
||||
/// - 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 {
|
||||
init(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
self.invalidatesDatabaseSchemaCache = false
|
||||
self.needsTruncateOptimizationPreventionDuringExecution = false
|
||||
self.databaseEventKinds = []
|
||||
@@ -446,7 +469,7 @@ public final class UpdateStatement : Statement {
|
||||
prepFlags: prepFlags)
|
||||
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
|
||||
self.needsTruncateOptimizationPreventionDuringExecution = authorizer.needsTruncateOptimizationPreventionDuringExecution
|
||||
self.transactionStatementInfo = authorizer.transactionStatementInfo
|
||||
self.transactionEffect = authorizer.transactionEffect
|
||||
self.databaseEventKinds = authorizer.databaseEventKinds
|
||||
}
|
||||
|
||||
@@ -878,7 +901,6 @@ extension StatementArguments : ExpressibleByDictionaryLiteral {
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -38,7 +38,7 @@
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Custom FTS5 Tokenizers
|
||||
// MARK: - FTS5
|
||||
|
||||
private class FTS5TokenizerConstructor {
|
||||
let db: Database
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -39,7 +39,7 @@ public protocol VirtualTableModule {
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Schema: Virtual Table
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// Creates a virtual database table.
|
||||
///
|
||||
|
||||
@@ -1004,8 +1004,6 @@ public enum FetchedRecordChange {
|
||||
}
|
||||
|
||||
extension FetchedRecordChange: CustomStringConvertible {
|
||||
|
||||
/// A textual representation of `self`.
|
||||
public var description: String {
|
||||
switch self {
|
||||
case .insertion(let indexPath):
|
||||
|
||||
@@ -21,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):
|
||||
@@ -824,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
|
||||
}
|
||||
@@ -870,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
|
||||
}
|
||||
@@ -887,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
|
||||
}
|
||||
@@ -904,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
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDBCipher'
|
||||
s.version = '2.1.0'
|
||||
s.version = '2.2.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
|
||||
@@ -292,10 +292,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/v2.1.0 \
|
||||
--module-version 2.1 \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v2.2.0 \
|
||||
--module-version 2.2 \
|
||||
--module GRDB \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/2.1/ \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/2.2/ \
|
||||
--output Documentation/Reference \
|
||||
--podspec GRDB.swift.podspec
|
||||
else
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
GRDB 2.0 [](https://developer.apple.com/swift/) [](https://developer.apple.com/swift/) [](/LICENSE) [](https://travis-ci.org/groue/GRDB.swift)
|
||||
GRDB 2 [](https://developer.apple.com/swift/) [](https://developer.apple.com/swift/) [](/LICENSE) [](https://travis-ci.org/groue/GRDB.swift)
|
||||
==========
|
||||
|
||||
### A toolkit for SQLite databases, with a focus on application development
|
||||
|
||||
**Latest release**: October 24, 2017 • version 2.1.0 • [CHANGELOG](CHANGELOG.md)
|
||||
**Latest release**: October 31, 2017 • version 2.2.0 • [CHANGELOG](CHANGELOG.md)
|
||||
|
||||
**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Swift 4.0 / Xcode 9+
|
||||
|
||||
@@ -14,7 +14,7 @@ GRDB 2.0 [](
|
||||
| Swift 3 | [v1.0](https://github.com/groue/GRDB.swift/tree/v1.0) |
|
||||
| Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
|
||||
| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
|
||||
| **Swift 4** | **v2.1.0** |
|
||||
| **Swift 4** | **v2.2.0** |
|
||||
|
||||
Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips.
|
||||
|
||||
@@ -197,7 +197,7 @@ Documentation
|
||||
|
||||
**Reference**
|
||||
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/2.1/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/2.2/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
|
||||
**Getting Started**
|
||||
|
||||
@@ -265,7 +265,7 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di
|
||||
```swift
|
||||
let package = Package(
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.1.0")
|
||||
.package(url: "https://github.com/groue/GRDB.swift.git", from: "2.2.0")
|
||||
]
|
||||
)
|
||||
```
|
||||
@@ -282,7 +282,7 @@ If you decide to use Carthage despite this warning, and get any Carthage-related
|
||||
|
||||
## Manually
|
||||
|
||||
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.1.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.1.0` command.
|
||||
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.2.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.2.0` command.
|
||||
|
||||
2. Embed the `GRDB.xcodeproj` project in your own project.
|
||||
|
||||
@@ -379,7 +379,7 @@ let dbQueue = try DatabaseQueue(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.1/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.2/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
## Database Pools
|
||||
@@ -460,7 +460,7 @@ let dbPool = try DatabasePool(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.1/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/2.2/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
|
||||
@@ -650,7 +650,7 @@ Both arrays and cursors can iterate over database results. How do you choose one
|
||||
- Cursors can not be used on any thread: you must consume them in a protected database queue.
|
||||
- Cursors iterate database results in a lazy fashion, and don't consume much memory.
|
||||
- Cursors can be iterated only one time.
|
||||
- Cursors are granted with direct access to SQLite: you can especially expect the best performance from cursors of raw database rows and some primitive types like `Int`, `String`, or `Bool` that adopt the [StatementColumnConvertible](http://groue.github.io/GRDB.swift/docs/2.1/Protocols/StatementColumnConvertible.html) protocol.
|
||||
- Cursors are granted with direct access to SQLite: you can especially expect the best performance from cursors of raw database rows and some primitive types like `Int`, `String`, or `Bool` that adopt the [StatementColumnConvertible](http://groue.github.io/GRDB.swift/docs/2.2/Protocols/StatementColumnConvertible.html) protocol.
|
||||
|
||||
If you don't see, or don't care about the difference, use arrays. If you care about memory and performance, use cursors when appropriate.
|
||||
|
||||
@@ -663,7 +663,7 @@ Date.fetchCursor(...) // DatabaseValueCursor<Date>
|
||||
Player.fetchCursor(...) // RecordCursor<Player>
|
||||
```
|
||||
|
||||
All cursor types adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.1/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift. As such, cursors come with many methods: `contains`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `map`, `reduce`:
|
||||
All cursor types adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.2/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift. As such, cursors come with many methods: `contains`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `map`, `reduce`:
|
||||
|
||||
```swift
|
||||
// Iterate all Github links
|
||||
@@ -734,7 +734,7 @@ let rows = try Row.fetchAll(db,
|
||||
arguments: ["name": "Arthur"])
|
||||
```
|
||||
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.2/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
|
||||
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
|
||||
|
||||
@@ -1005,7 +1005,7 @@ GRDB ships with built-in support for the following value types:
|
||||
|
||||
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
|
||||
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html):
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/2.2/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let url: URL = ...
|
||||
@@ -1397,7 +1397,7 @@ try dbQueue.inDatabase { db in
|
||||
}
|
||||
```
|
||||
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.2/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
|
||||
```swift
|
||||
updateStatement.arguments = ["name": "Arthur", "score": 1000]
|
||||
@@ -1659,7 +1659,7 @@ row["consumed"] // "Hello"
|
||||
row["produced"] // nil
|
||||
```
|
||||
|
||||
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/2.1/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters:
|
||||
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/2.2/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters:
|
||||
|
||||
|
||||
### ColumnMapping
|
||||
@@ -1786,8 +1786,8 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used
|
||||
- `sqlite3_aggregate_context`, `sqlite3_create_function_v2`, `sqlite3_result_blob`, `sqlite3_result_double`, `sqlite3_result_error`, `sqlite3_result_error_code`, `sqlite3_result_int64`, `sqlite3_result_null`, `sqlite3_result_text`, `sqlite3_user_data`, `sqlite3_value_blob`, `sqlite3_value_bytes`, `sqlite3_value_double`, `sqlite3_value_int64`, `sqlite3_value_text`, `sqlite3_value_type`: see [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates)
|
||||
- `sqlite3_backup_finish`, `sqlite3_backup_init`, `sqlite3_backup_step`: see [Backup](#backup)
|
||||
- `sqlite3_bind_blob`, `sqlite3_bind_double`, `sqlite3_bind_int64`, `sqlite3_bind_null`, `sqlite3_bind_parameter_count`, `sqlite3_bind_parameter_name`, `sqlite3_bind_text`, `sqlite3_clear_bindings`, `sqlite3_column_blob`, `sqlite3_column_bytes`, `sqlite3_column_count`, `sqlite3_column_double`, `sqlite3_column_int64`, `sqlite3_column_name`, `sqlite3_column_text`, `sqlite3_column_type`, `sqlite3_exec`, `sqlite3_finalize`, `sqlite3_prepare_v2`, `sqlite3_reset`, `sqlite3_step`: see [Executing Updates](#executing-updates), [Fetch Queries](#fetch-queries), [Prepared Statements](#prepared-statements), [Values](#values)
|
||||
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.1/Structs/Configuration.html)
|
||||
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.1/Classes/Database.html)
|
||||
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.2/Structs/Configuration.html)
|
||||
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.2/Classes/Database.html)
|
||||
- `sqlite3_close`, `sqlite3_close_v2`, `sqlite3_next_stmt`, `sqlite3_open_v2`: see [Database Connections](#database-connections)
|
||||
- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [FetchedRecordsController](#fetchedrecordscontroller)
|
||||
- `sqlite3_config`: see [Error Log](#error-log)
|
||||
@@ -1798,9 +1798,9 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used
|
||||
- `sqlite3_last_insert_rowid`: see [Executing Updates](#executing-updates)
|
||||
- `sqlite3_preupdate_count`, `sqlite3_preupdate_depth`, `sqlite3_preupdate_hook`, `sqlite3_preupdate_new`, `sqlite3_preupdate_old`: see [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks)
|
||||
- `sqlite3_set_authorizer`: **reserved by GRDB**
|
||||
- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/2.1/Classes/Statement.html)
|
||||
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.1/Structs/Configuration.html)
|
||||
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.1/Classes/DatabasePool.html)
|
||||
- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/2.2/Classes/Statement.html)
|
||||
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.2/Structs/Configuration.html)
|
||||
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.2/Classes/DatabasePool.html)
|
||||
|
||||
|
||||
Records
|
||||
@@ -2125,7 +2125,7 @@ try Place.fetchAll(db, "SELECT ...", arguments:...) // [Place]
|
||||
try Place.fetchOne(db, "SELECT ...", arguments:...) // Place?
|
||||
```
|
||||
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.2/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
|
||||
|
||||
## TableMapping Protocol
|
||||
@@ -3181,7 +3181,7 @@ Player // SELECT * FROM players
|
||||
```
|
||||
|
||||
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html):
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.2/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
// SELECT DATE(creationDate), COUNT(*) FROM players WHERE name = 'Arthur' GROUP BY date(creationDate)
|
||||
@@ -3650,9 +3650,9 @@ try request.fetchOne(db) // Player?
|
||||
|
||||
**To build custom requests**, you can create your own type that adopts the protocols, or derive requests from other requests, or use one of the built-in concrete types:
|
||||
|
||||
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.1/Structs/SQLRequest.html): a Request built from raw SQL
|
||||
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.1/Structs/AnyRequest.html): a type-erased Request
|
||||
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.1/Structs/AnyTypedRequest.html): a type-erased TypedRequest
|
||||
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.2/Structs/SQLRequest.html): a Request built from raw SQL
|
||||
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.2/Structs/AnyRequest.html): a type-erased Request
|
||||
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.2/Structs/AnyTypedRequest.html): a type-erased TypedRequest
|
||||
|
||||
Use the `asRequest(of:)` method to define the type fetched by the request:
|
||||
|
||||
@@ -4082,7 +4082,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.2/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -4295,7 +4295,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.2/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -4496,6 +4496,19 @@ try dbQueue.inTransaction { db in
|
||||
}
|
||||
```
|
||||
|
||||
> :point_up: **Note**: for SQLite, empty [deferred](#transaction-kinds) transactions are no transaction at all. In this case, the transaction callback is never executed:
|
||||
>
|
||||
> ```swift
|
||||
> // Empty deferred transaction
|
||||
> dbQueue.inTransaction { db in
|
||||
> db.afterNextTransactionCommit { db in
|
||||
> // Never executed
|
||||
> print("success")
|
||||
> }
|
||||
> return .commit
|
||||
> }
|
||||
> ```
|
||||
|
||||
|
||||
### TransactionObserver Protocol
|
||||
|
||||
@@ -4614,6 +4627,16 @@ do {
|
||||
> :point_up: **Note**: all callbacks are called in a protected dispatch queue, and serialized with all database updates.
|
||||
>
|
||||
> :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument.
|
||||
>
|
||||
> :point_up: **Note**: for SQLite, empty [deferred](#transaction-kinds) transactions are no transaction at all. In this case, transaction observers are not notified:
|
||||
>
|
||||
> ```swift
|
||||
> // Empty deferred transaction does not notify transaction observers
|
||||
> dbQueue.inTransaction { db in
|
||||
> return .commit
|
||||
> }
|
||||
> ```
|
||||
|
||||
|
||||
[FetchedRecordsController](#fetchedrecordscontroller) and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) are based on the TransactionObserver protocol.
|
||||
|
||||
@@ -4714,6 +4737,16 @@ dbQueue.inDatabase { db in
|
||||
|
||||
- `.databaseLifetime` has the database retain and notify the observer until the database connection is closed.
|
||||
|
||||
> :point_up: **Note**: for SQLite, empty [deferred](#transaction-kinds) transactions are no transaction at all. In this case, an observer added with the `.nextTransaction` extent is never notified of any transaction:
|
||||
>
|
||||
> ```swift
|
||||
> // Empty deferred transaction
|
||||
> dbQueue.inTransaction { db in
|
||||
> // Observer is never notified of any transaction
|
||||
> db.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
> return .commit
|
||||
> }
|
||||
> ```
|
||||
|
||||
#### Support for SQLite Pre-Update Hooks
|
||||
|
||||
@@ -5085,7 +5118,7 @@ Alternatively, perform a manual installation of GRDB and SQLCipher:
|
||||
|
||||
```sh
|
||||
cd [GRDB directory]
|
||||
git checkout v2.1.0
|
||||
git checkout v2.2.0
|
||||
git submodule update --init SQLCipher/src
|
||||
```
|
||||
|
||||
@@ -5192,7 +5225,7 @@ DROP TABLE students;
|
||||
--' WHERE id = 1
|
||||
```
|
||||
|
||||
To avoid those problems, **never embed raw values in your SQL queries**. The only correct technique is to provide [arguments](http://groue.github.io/GRDB.swift/docs/2.1/Structs/StatementArguments.html) to your SQL queries:
|
||||
To avoid those problems, **never embed raw values in your SQL queries**. The only correct technique is to provide [arguments](http://groue.github.io/GRDB.swift/docs/2.2/Structs/StatementArguments.html) to your SQL queries:
|
||||
|
||||
```swift
|
||||
// Good
|
||||
@@ -5771,7 +5804,7 @@ try dbPool.write { db in
|
||||
|
||||
### DatabaseWriter and DatabaseReader Protocols
|
||||
|
||||
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.1/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.1/Protocols/DatabaseWriter.html) protocols.
|
||||
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.2/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.2/Protocols/DatabaseWriter.html) protocols.
|
||||
|
||||
These protocols provide a unified API that lets you write safe concurrent code that targets both classes.
|
||||
|
||||
@@ -5779,7 +5812,7 @@ However, database queues are not database pools, and DatabaseReader and Database
|
||||
|
||||
- Pools are less forgiving than queues when one overlooks a transaction (see [concurrency rule 3](#guarantees-and-rules)).
|
||||
- DatabaseWriter.readFromCurrentState is synchronous, or asynchronous, depending on whether it is run by a queue or a pool (see [advanced DatabasePool](#advanced-databasepool)). It thus requires higher libDispatch skills, and more complex synchronization code.
|
||||
- The definition of "current state" in DatabaseWriter.readFromCurrentState is [delicate](http://groue.github.io/GRDB.swift/docs/2.1/Protocols/DatabaseWriter.html#/s:FP4GRDB14DatabaseWriter20readFromCurrentStateFzFCS_8DatabaseT_T_).
|
||||
- The definition of "current state" in DatabaseWriter.readFromCurrentState is [delicate](http://groue.github.io/GRDB.swift/docs/2.2/Protocols/DatabaseWriter.html#/s:FP4GRDB14DatabaseWriter20readFromCurrentStateFzFCS_8DatabaseT_T_).
|
||||
|
||||
DatabaseReader and DatabaseWriter are not a tool for applications that hesitate between DatabaseQueue and DatabasePool, and look for a common API. As seen above, the protocols actually make applications harder to write correctly. Instead, they target generic code that has *both* queues and pools in mind. The built-in AnyDatabaseReader and AnyDatabaseWriter type erasers serve the same purpose.
|
||||
|
||||
@@ -5866,7 +5899,7 @@ If you absolutely need multiple connections, then:
|
||||
- Read about [isolation in SQLite](https://www.sqlite.org/isolation.html)
|
||||
- Learn about [locks and transactions](https://www.sqlite.org/lang_transaction.html)
|
||||
- Become a master of the [WAL mode](https://www.sqlite.org/wal.html)
|
||||
- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.1/Structs/Configuration.html)
|
||||
- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.2/Structs/Configuration.html)
|
||||
- [Ask questions](https://github.com/groue/GRDB.swift/issues)
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>2.1.0</string>
|
||||
<string>2.2.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -28,15 +28,52 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
|
||||
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
|
||||
try db.inTransaction { .commit }
|
||||
try db.inTransaction {
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(transactionCount, 1)
|
||||
XCTAssertNil(deallocationWitness)
|
||||
|
||||
try db.inTransaction { .commit }
|
||||
try db.inTransaction {
|
||||
try db.execute("DROP TABLE t")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(transactionCount, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseAfterNextTransactionWithEmptyDeferredTransaction() throws {
|
||||
class Witness { }
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
var transactionCount = 0
|
||||
weak var deallocationWitness: Witness? = nil
|
||||
do {
|
||||
let witness = Witness()
|
||||
deallocationWitness = witness
|
||||
db.afterNextTransactionCommit { _ in
|
||||
// use witness
|
||||
withExtendedLifetime(witness, { })
|
||||
transactionCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
|
||||
try db.inTransaction(.deferred) { .commit }
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
XCTAssertNil(deallocationWitness)
|
||||
|
||||
try db.inTransaction {
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseAfterNextTransactionCommitWithRollback() throws {
|
||||
class Witness { }
|
||||
|
||||
@@ -56,11 +93,17 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
|
||||
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
|
||||
try db.inTransaction { .rollback }
|
||||
try db.inTransaction {
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
return .rollback
|
||||
}
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
XCTAssertNil(deallocationWitness)
|
||||
|
||||
try db.inTransaction { .commit }
|
||||
try db.inTransaction {
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(transactionCount, 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -961,8 +961,91 @@ class TransactionObserverTests: GRDBTestCase {
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
func testEmptyDeferredTransaction() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let observer = Observer()
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
try dbQueue.inTransaction(.deferred) { _ in .commit }
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer.willChangeCount, 0)
|
||||
#endif
|
||||
XCTAssertEqual(observer.didChangeCount, 0)
|
||||
XCTAssertEqual(observer.willCommitCount, 0)
|
||||
XCTAssertEqual(observer.didCommitCount, 0)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
}
|
||||
|
||||
func testEmptyDeferredTransactionRollback() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let observer = Observer()
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
try dbQueue.inTransaction(.deferred) { _ in .rollback }
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer.willChangeCount, 0)
|
||||
#endif
|
||||
XCTAssertEqual(observer.didChangeCount, 0)
|
||||
XCTAssertEqual(observer.willCommitCount, 0)
|
||||
XCTAssertEqual(observer.didCommitCount, 0)
|
||||
XCTAssertEqual(observer.didRollbackCount, 1)
|
||||
}
|
||||
|
||||
func testEmptyImmediateTransaction() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let observer = Observer()
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
try dbQueue.inTransaction(.immediate) { _ in .commit }
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer.willChangeCount, 0)
|
||||
#endif
|
||||
XCTAssertEqual(observer.didChangeCount, 0)
|
||||
XCTAssertEqual(observer.willCommitCount, 1)
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
}
|
||||
|
||||
func testEmptyImmediateTransactionRollback() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let observer = Observer()
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
try dbQueue.inTransaction(.immediate) { _ in .rollback }
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer.willChangeCount, 0)
|
||||
#endif
|
||||
XCTAssertEqual(observer.didChangeCount, 0)
|
||||
XCTAssertEqual(observer.willCommitCount, 0)
|
||||
XCTAssertEqual(observer.didCommitCount, 0)
|
||||
XCTAssertEqual(observer.didRollbackCount, 1)
|
||||
}
|
||||
|
||||
func testEmptyExclusiveTransaction() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let observer = Observer()
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
try dbQueue.inTransaction(.exclusive) { _ in .commit }
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer.willChangeCount, 0)
|
||||
#endif
|
||||
XCTAssertEqual(observer.didChangeCount, 0)
|
||||
XCTAssertEqual(observer.willCommitCount, 1)
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
XCTAssertEqual(observer.didRollbackCount, 0)
|
||||
}
|
||||
|
||||
func testEmptyExclusiveTransactionRollback() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let observer = Observer()
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
try dbQueue.inTransaction(.exclusive) { _ in .rollback }
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer.willChangeCount, 0)
|
||||
#endif
|
||||
XCTAssertEqual(observer.didChangeCount, 0)
|
||||
XCTAssertEqual(observer.willCommitCount, 0)
|
||||
XCTAssertEqual(observer.didCommitCount, 0)
|
||||
XCTAssertEqual(observer.didRollbackCount, 1)
|
||||
}
|
||||
|
||||
// MARK: - Multiple observers
|
||||
|
||||
func testInsertEventIsNotifiedToAllObservers() throws {
|
||||
@@ -1070,6 +1153,107 @@ class TransactionObserverTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testEmptyDeferredTransactionRollbackCausedBySecondTransactionObserverOutOfThree() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let observer = Observer()
|
||||
observer.commitError = NSError(domain: "foo", code: 0, userInfo: nil)
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
|
||||
do {
|
||||
try dbQueue.inTransaction(.deferred) { _ in .commit }
|
||||
} catch {
|
||||
XCTFail("Unexpected Error: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
func testEmptyImmediateTransactionRollbackCausedBySecondTransactionObserverOutOfThree() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let observer1 = Observer()
|
||||
let observer2 = Observer()
|
||||
let observer3 = Observer()
|
||||
observer2.commitError = NSError(domain: "foo", code: 0, userInfo: nil)
|
||||
|
||||
dbQueue.add(transactionObserver: observer1)
|
||||
dbQueue.add(transactionObserver: observer2)
|
||||
dbQueue.add(transactionObserver: observer3)
|
||||
|
||||
do {
|
||||
try dbQueue.inTransaction(.immediate) { _ in .commit }
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as NSError {
|
||||
XCTAssertEqual(error.domain, "foo")
|
||||
XCTAssertEqual(error.code, 0)
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer1.willChangeCount, 0)
|
||||
#endif
|
||||
XCTAssertEqual(observer1.didChangeCount, 0)
|
||||
XCTAssertEqual(observer1.willCommitCount, 1)
|
||||
XCTAssertEqual(observer1.didCommitCount, 0)
|
||||
XCTAssertEqual(observer1.didRollbackCount, 1)
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer2.willChangeCount, 0)
|
||||
#endif
|
||||
XCTAssertEqual(observer2.didChangeCount, 0)
|
||||
XCTAssertEqual(observer2.willCommitCount, 1)
|
||||
XCTAssertEqual(observer2.didCommitCount, 0)
|
||||
XCTAssertEqual(observer2.didRollbackCount, 1)
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer3.willChangeCount, 0)
|
||||
#endif
|
||||
XCTAssertEqual(observer3.didChangeCount, 0)
|
||||
XCTAssertEqual(observer3.willCommitCount, 0)
|
||||
XCTAssertEqual(observer3.didCommitCount, 0)
|
||||
XCTAssertEqual(observer3.didRollbackCount, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testEmptyExclusiveTransactionRollbackCausedBySecondTransactionObserverOutOfThree() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let observer1 = Observer()
|
||||
let observer2 = Observer()
|
||||
let observer3 = Observer()
|
||||
observer2.commitError = NSError(domain: "foo", code: 0, userInfo: nil)
|
||||
|
||||
dbQueue.add(transactionObserver: observer1)
|
||||
dbQueue.add(transactionObserver: observer2)
|
||||
dbQueue.add(transactionObserver: observer3)
|
||||
|
||||
do {
|
||||
try dbQueue.inTransaction(.immediate) { _ in .commit }
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as NSError {
|
||||
XCTAssertEqual(error.domain, "foo")
|
||||
XCTAssertEqual(error.code, 0)
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer1.willChangeCount, 0)
|
||||
#endif
|
||||
XCTAssertEqual(observer1.didChangeCount, 0)
|
||||
XCTAssertEqual(observer1.willCommitCount, 1)
|
||||
XCTAssertEqual(observer1.didCommitCount, 0)
|
||||
XCTAssertEqual(observer1.didRollbackCount, 1)
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer2.willChangeCount, 0)
|
||||
#endif
|
||||
XCTAssertEqual(observer2.didChangeCount, 0)
|
||||
XCTAssertEqual(observer2.willCommitCount, 1)
|
||||
XCTAssertEqual(observer2.didCommitCount, 0)
|
||||
XCTAssertEqual(observer2.didRollbackCount, 1)
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
XCTAssertEqual(observer3.willChangeCount, 0)
|
||||
#endif
|
||||
XCTAssertEqual(observer3.didChangeCount, 0)
|
||||
XCTAssertEqual(observer3.willCommitCount, 0)
|
||||
XCTAssertEqual(observer3.didCommitCount, 0)
|
||||
XCTAssertEqual(observer3.didRollbackCount, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testTransactionObserverAddAndRemove() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let observer = Observer()
|
||||
@@ -1232,9 +1416,15 @@ class TransactionObserverTests: GRDBTestCase {
|
||||
weakObserver = observer
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
|
||||
try dbQueue.inTransaction { _ in .commit }
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
try dbQueue.inTransaction { _ in .commit }
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("DROP TABLE t")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 2)
|
||||
}
|
||||
XCTAssert(weakObserver == nil)
|
||||
@@ -1248,9 +1438,15 @@ class TransactionObserverTests: GRDBTestCase {
|
||||
weakObserver = observer
|
||||
dbQueue.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
|
||||
try dbQueue.inTransaction { _ in .commit }
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
try dbQueue.inTransaction { _ in .commit }
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("DROP TABLE t")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 2)
|
||||
}
|
||||
XCTAssert(weakObserver == nil)
|
||||
@@ -1265,7 +1461,10 @@ class TransactionObserverTests: GRDBTestCase {
|
||||
dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
}
|
||||
if let observer = weakObserver {
|
||||
try dbQueue.inTransaction { _ in .commit }
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
} else {
|
||||
XCTFail("observer should not be deallocated until next transaction")
|
||||
@@ -1295,9 +1494,15 @@ class TransactionObserverTests: GRDBTestCase {
|
||||
let observer = Observer()
|
||||
dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
|
||||
try dbQueue.inTransaction { _ in .commit }
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
try dbQueue.inTransaction { _ in .commit }
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("DROP TABLE t")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
}
|
||||
|
||||
@@ -1305,15 +1510,25 @@ class TransactionObserverTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let witness = Observer()
|
||||
let observer = Observer(didCommitBlock: { db in
|
||||
try! db.inTransaction { .commit }
|
||||
try! db.inTransaction {
|
||||
try db.execute("CREATE TABLE t2(a)")
|
||||
try db.execute("DROP TABLE t2")
|
||||
return .commit
|
||||
}
|
||||
})
|
||||
dbQueue.add(transactionObserver: witness)
|
||||
dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
|
||||
try dbQueue.inTransaction { _ in .commit }
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
XCTAssertEqual(witness.didCommitCount, 2)
|
||||
try dbQueue.inTransaction { _ in .commit }
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("DROP TABLE t")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
XCTAssertEqual(witness.didCommitCount, 3)
|
||||
}
|
||||
@@ -1323,15 +1538,51 @@ class TransactionObserverTests: GRDBTestCase {
|
||||
let observer = Observer()
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
db.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
return .commit
|
||||
}
|
||||
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
try dbQueue.inTransaction { _ in .commit }
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("DROP TABLE t")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
}
|
||||
|
||||
func testObservationExtentUntilNextTransactionWithEmptyDeferredTransaction() throws {
|
||||
weak var weakObserver: Observer? = nil
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
do {
|
||||
let observer = Observer()
|
||||
weakObserver = observer
|
||||
dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
}
|
||||
if let observer = weakObserver {
|
||||
try dbQueue.inTransaction(.deferred) { _ in .commit }
|
||||
XCTAssertEqual(observer.didCommitCount, 0)
|
||||
} else {
|
||||
XCTFail("observer should not be deallocated until next transaction")
|
||||
}
|
||||
XCTAssert(weakObserver == nil)
|
||||
}
|
||||
|
||||
func testObservationExtentUntilNextTransactionWithEmptyDeferredTransactionAndRetainedObserver() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let observer = Observer()
|
||||
dbQueue.add(transactionObserver: observer, extent: .nextTransaction)
|
||||
|
||||
try dbQueue.inTransaction(.deferred) { _ in .commit }
|
||||
XCTAssertEqual(observer.didCommitCount, 0)
|
||||
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 0)
|
||||
}
|
||||
|
||||
func testObservationExtentDatabaseLifetime() throws {
|
||||
// Observer deallocation happens concurrently with database deallocation:
|
||||
//
|
||||
@@ -1355,14 +1606,20 @@ class TransactionObserverTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
if let observer = weakObserver {
|
||||
try dbQueue.inTransaction { _ in .commit }
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 1)
|
||||
} else {
|
||||
XCTFail("observer should not be deallocated until database is closed")
|
||||
}
|
||||
|
||||
if let observer = weakObserver {
|
||||
try dbQueue.inTransaction { _ in .commit }
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute("DROP TABLE t")
|
||||
return .commit
|
||||
}
|
||||
XCTAssertEqual(observer.didCommitCount, 2)
|
||||
} else {
|
||||
XCTFail("observer should not be deallocated until database is closed")
|
||||
|
||||
@@ -123,6 +123,7 @@ class TruncateOptimizationTests: GRDBTestCase {
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
try db.execute("INSERT INTO t VALUES (NULL)")
|
||||
try XCTAssertTrue(db.tableExists("t"))
|
||||
try db.execute("DROP TABLE t") // compile + execute
|
||||
try XCTAssertFalse(db.tableExists("t"))
|
||||
}
|
||||
@@ -133,6 +134,7 @@ class TruncateOptimizationTests: GRDBTestCase {
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
try db.execute("INSERT INTO t VALUES (NULL)")
|
||||
try XCTAssertTrue(db.tableExists("t"))
|
||||
let dropStatement = try db.makeUpdateStatement("DROP TABLE t") // compile...
|
||||
try dropStatement.execute() // ... then execute
|
||||
try XCTAssertFalse(db.tableExists("t"))
|
||||
@@ -144,6 +146,7 @@ class TruncateOptimizationTests: GRDBTestCase {
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TEMPORARY TABLE t(a)")
|
||||
try db.execute("INSERT INTO t VALUES (NULL)")
|
||||
try XCTAssertTrue(db.tableExists("t"))
|
||||
try db.execute("DROP TABLE t") // compile + execute
|
||||
try XCTAssertFalse(db.tableExists("t"))
|
||||
}
|
||||
@@ -154,6 +157,7 @@ class TruncateOptimizationTests: GRDBTestCase {
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TEMPORARY TABLE t(a)")
|
||||
try db.execute("INSERT INTO t VALUES (NULL)")
|
||||
try XCTAssertTrue(db.tableExists("t"))
|
||||
let dropStatement = try db.makeUpdateStatement("DROP TABLE t") // compile...
|
||||
try dropStatement.execute() // ... then execute
|
||||
try XCTAssertFalse(db.tableExists("t"))
|
||||
@@ -165,6 +169,7 @@ class TruncateOptimizationTests: GRDBTestCase {
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)")
|
||||
try db.execute("INSERT INTO t VALUES (NULL)")
|
||||
try XCTAssertTrue(db.tableExists("t"))
|
||||
try db.execute("DROP TABLE t") // compile + execute
|
||||
try XCTAssertFalse(db.tableExists("t"))
|
||||
}
|
||||
@@ -175,9 +180,154 @@ class TruncateOptimizationTests: GRDBTestCase {
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)")
|
||||
try db.execute("INSERT INTO t VALUES (NULL)")
|
||||
try XCTAssertTrue(db.tableExists("t"))
|
||||
let dropStatement = try db.makeUpdateStatement("DROP TABLE t") // compile...
|
||||
try dropStatement.execute() // ... then execute
|
||||
try XCTAssertFalse(db.tableExists("t"))
|
||||
}
|
||||
}
|
||||
|
||||
func testDropView() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
try db.execute("CREATE VIEW v AS SELECT * FROM t")
|
||||
try db.execute("INSERT INTO t VALUES (NULL)")
|
||||
try XCTAssertTrue(db.viewExists("v"))
|
||||
try db.execute("DROP VIEW v") // compile + execute
|
||||
try XCTAssertFalse(db.viewExists("v"))
|
||||
}
|
||||
}
|
||||
|
||||
func testDropViewWithPreparedStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
try db.execute("CREATE VIEW v AS SELECT * FROM t")
|
||||
try db.execute("INSERT INTO t VALUES (NULL)")
|
||||
try XCTAssertTrue(db.viewExists("v"))
|
||||
let dropStatement = try db.makeUpdateStatement("DROP VIEW v") // compile...
|
||||
try dropStatement.execute() // ... then execute
|
||||
try XCTAssertFalse(db.viewExists("v"))
|
||||
}
|
||||
}
|
||||
|
||||
func testDropTemporaryView() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
try db.execute("CREATE TEMPORARY VIEW v AS SELECT * FROM t")
|
||||
try db.execute("INSERT INTO t VALUES (NULL)")
|
||||
try XCTAssertTrue(db.viewExists("v"))
|
||||
try db.execute("DROP VIEW v") // compile + execute
|
||||
try XCTAssertFalse(db.viewExists("v"))
|
||||
}
|
||||
}
|
||||
|
||||
func testDropTemporaryViewWithPreparedStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
try db.execute("CREATE TEMPORARY VIEW v AS SELECT * FROM t")
|
||||
try db.execute("INSERT INTO t VALUES (NULL)")
|
||||
try XCTAssertTrue(db.viewExists("v"))
|
||||
let dropStatement = try db.makeUpdateStatement("DROP VIEW v") // compile...
|
||||
try dropStatement.execute() // ... then execute
|
||||
try XCTAssertFalse(db.viewExists("v"))
|
||||
}
|
||||
}
|
||||
|
||||
func testDropIndex() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
try db.execute("CREATE INDEX i ON t(a)")
|
||||
try XCTAssertFalse(db.indexes(on: "t").isEmpty)
|
||||
try db.execute("DROP INDEX i") // compile + execute
|
||||
try XCTAssertTrue(db.indexes(on: "t").isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
func testDropIndexViewWithPreparedStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
try db.execute("CREATE INDEX i ON t(a)")
|
||||
try db.execute("INSERT INTO t VALUES (1)")
|
||||
try XCTAssertFalse(db.indexes(on: "t").isEmpty)
|
||||
let dropStatement = try db.makeUpdateStatement("DROP INDEX i") // compile...
|
||||
try dropStatement.execute() // ... then execute
|
||||
try XCTAssertTrue(db.indexes(on: "t").isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
func testDropTemporaryIndex() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TEMPORARY TABLE t(a)")
|
||||
try db.execute("CREATE INDEX i ON t(a)")
|
||||
try XCTAssertFalse(db.indexes(on: "t").isEmpty)
|
||||
try db.execute("DROP INDEX i") // compile + execute
|
||||
try XCTAssertTrue(db.indexes(on: "t").isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
func testDropTemporaryIndexViewWithPreparedStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TEMPORARY TABLE t(a)")
|
||||
try db.execute("CREATE INDEX i ON t(a)")
|
||||
try db.execute("INSERT INTO t VALUES (1)")
|
||||
try XCTAssertFalse(db.indexes(on: "t").isEmpty)
|
||||
let dropStatement = try db.makeUpdateStatement("DROP INDEX i") // compile...
|
||||
try dropStatement.execute() // ... then execute
|
||||
try XCTAssertTrue(db.indexes(on: "t").isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
func testDropTrigger() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
try db.execute("CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END")
|
||||
try XCTAssertTrue(db.triggerExists("r"))
|
||||
try db.execute("DROP TRIGGER r") // compile + execute
|
||||
try XCTAssertFalse(db.triggerExists("r"))
|
||||
}
|
||||
}
|
||||
|
||||
func testDropTriggerWithPreparedStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
try db.execute("CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END")
|
||||
try XCTAssertTrue(db.triggerExists("r"))
|
||||
let dropStatement = try db.makeUpdateStatement("DROP TRIGGER r") // compile...
|
||||
try dropStatement.execute() // ... then execute
|
||||
try XCTAssertFalse(db.triggerExists("r"))
|
||||
}
|
||||
}
|
||||
|
||||
func testDropTemporaryTrigger() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
try db.execute("CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END")
|
||||
try XCTAssertTrue(db.triggerExists("r"))
|
||||
try db.execute("DROP TRIGGER r") // compile + execute
|
||||
try XCTAssertFalse(db.triggerExists("r"))
|
||||
}
|
||||
}
|
||||
|
||||
func testDropTemporaryTriggerWithPreparedStatement() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE t(a)")
|
||||
try db.execute("CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END")
|
||||
try XCTAssertTrue(db.triggerExists("r"))
|
||||
let dropStatement = try db.makeUpdateStatement("DROP TRIGGER r") // compile...
|
||||
try dropStatement.execute() // ... then execute
|
||||
try XCTAssertFalse(db.triggerExists("r"))
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user