mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-05 05:18:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ebeb7bc969 | ||
|
|
6ccac5f69c | ||
|
|
cc41b8b259 | ||
|
|
db1a3456b7 | ||
|
|
1b9305c073 | ||
|
|
a33814ef40 | ||
|
|
581bc9f27c | ||
|
|
40cff0053f | ||
|
|
cc33b12b0d | ||
|
|
2add1c68ea | ||
|
|
380b6676a6 | ||
|
|
f133a36477 | ||
|
|
5f2d6f8e2f | ||
|
|
a72c207ec5 | ||
|
|
ae3c28dee1 | ||
|
|
bd919e5209 | ||
|
|
d1697756e9 | ||
|
|
83c3745165 | ||
|
|
56a4a964b7 | ||
|
|
c9a02faf08 | ||
|
|
e59388738e | ||
|
|
c8368d98eb | ||
|
|
d12dad2e34 | ||
|
|
1ee8c73562 | ||
|
|
ad8de84257 |
No files matched your search
+1
-1
@@ -1 +1 @@
|
||||
3.0
|
||||
3.1
|
||||
+161
@@ -1,6 +1,167 @@
|
||||
Release Notes
|
||||
=============
|
||||
|
||||
## 1.2
|
||||
|
||||
Released July 13, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- Record types that do not provide values for all table columns in their `encode(to:)` method are now supported.
|
||||
|
||||
- The table creation API has been enhanced:
|
||||
|
||||
- SQLite supports untyped columns:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
// CREATE TABLE t(a, b)
|
||||
try db.create(table: "t") { t in
|
||||
t.column("a")
|
||||
t.column("b")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Untyped columns behave like decimal, boolean, date columns, and generally all columns with [NUMERIC type affinity](https://sqlite.org/datatype3.html#type_affinity).
|
||||
|
||||
This feature addresses [#169](https://github.com/groue/GRDB.swift/issues/169).
|
||||
|
||||
- The `indexed()` methods lets you create a non-unique index on a table column:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
// CREATE TABLE rounds(score INTEGER)
|
||||
// CREATE INDEX rounds_on_score ON rounds(score)
|
||||
try db.create(table: "rounds") { t in
|
||||
t.column("score", .integer).indexed()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- It is now possible to define references to tables without any explicit primary key. The generated SQL then uses the `rowid` hidden primary key column:
|
||||
|
||||
```swift
|
||||
try dbQueue.inDatabase { db in
|
||||
// CREATE TABLE nodes(
|
||||
// name TEXT,
|
||||
// parentId INTEGER REFERENCES nodes(rowid)
|
||||
// )
|
||||
try db.create(table: "nodes") { t in
|
||||
t.column("name", .text)
|
||||
t.column("parentId", .integer).references("nodes")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `DatabaseQueue`, `DatabasePool` and their common protocol `DatabaseReader` can now perform "unsafe reentrant reads" ([documentation](https://github.com/groue/GRDB.swift#unsafe-concurrency-apis)):
|
||||
|
||||
```swift
|
||||
try dbPool.read { db in
|
||||
// This is allowed
|
||||
try dbPool.unsafeReentrantRead { db in
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
**Fixed**
|
||||
|
||||
- `DatabasePool.read`, and `DatabasePool.unsafeRead` now raise a fatal error when used in a reentrant way:
|
||||
|
||||
```swift
|
||||
try dbPool.read { db in
|
||||
// fatal error: "Database methods are not reentrant."
|
||||
try dbPool.read { db in
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
While this change may appear as a breaking change, it is really a fix: reentrant reads deadlock as soon as the maximum number of readers has been reached.
|
||||
|
||||
|
||||
**API diff**
|
||||
|
||||
```diff
|
||||
final class ColumnDefinition {
|
||||
+ @discardableResult func indexed() -> Self
|
||||
}
|
||||
|
||||
final class TableDefinition {
|
||||
- func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition
|
||||
+ func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition
|
||||
}
|
||||
|
||||
protocol DatabaseReader {
|
||||
+ func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 1.1
|
||||
|
||||
Released July 1, 2017
|
||||
|
||||
**New**
|
||||
|
||||
- `DatabaseAggregate` is the protocol for custom aggregate functions (fixes [#236](https://github.com/groue/GRDB.swift/issues/236), [documentation](https://github.com/groue/GRDB.swift#custom-aggregates)):
|
||||
|
||||
```swift
|
||||
struct MySum : DatabaseAggregate {
|
||||
var sum: Int = 0
|
||||
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
sum += int
|
||||
}
|
||||
}
|
||||
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return sum
|
||||
}
|
||||
}
|
||||
|
||||
let dbQueue = DatabaseQueue()
|
||||
let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute("CREATE TABLE test(i)")
|
||||
try db.execute("INSERT INTO test(i) VALUES (1)")
|
||||
try db.execute("INSERT INTO test(i) VALUES (2)")
|
||||
try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
|
||||
}
|
||||
```
|
||||
|
||||
**Fixed**
|
||||
|
||||
- `QueryInterfaceRequest.order(_:)` clears the eventual reversed flag, and better reflects the documentation of this method: "Any previous ordering is replaced."
|
||||
|
||||
**Deprecated**
|
||||
|
||||
- `TableMapping.primaryKeyRowComparator` is deprecated, without any replacement.
|
||||
|
||||
**API diff**
|
||||
|
||||
```diff
|
||||
final class DatabaseFunction {
|
||||
+ init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type)
|
||||
}
|
||||
|
||||
+protocol DatabaseAggregate {
|
||||
+ init()
|
||||
+ mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
+ func finalize() throws -> DatabaseValueConvertible?
|
||||
+}
|
||||
|
||||
extension TableMapping {
|
||||
+ @available(*, deprecated)
|
||||
static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## 1.0 :tada:
|
||||
|
||||
Released June 20, 2017
|
||||
|
||||
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
```sh
|
||||
cd [GRDB.swift directory]
|
||||
git checkout v1.0
|
||||
git checkout v1.2
|
||||
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/1.0/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/1.0/Functions.html) functions:
|
||||
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/1.2/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/1.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/1.0/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/1.2/Protocols/SQLExpression.html) protocol.
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '1.0'
|
||||
s.version = '1.2'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
|
||||
@@ -329,6 +329,21 @@
|
||||
564448891EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
|
||||
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
|
||||
564F9C1F1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
|
||||
564F9C201F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
|
||||
564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
|
||||
564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
|
||||
564F9C231F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
|
||||
564F9C241F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
|
||||
564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
|
||||
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
|
||||
564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
|
||||
564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
|
||||
564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
|
||||
564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
|
||||
564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
|
||||
564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; };
|
||||
565029C81E914DB700615A2C /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565029C71E914DB700615A2C /* TableMappingTests.swift */; };
|
||||
565029C91E914DB700615A2C /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565029C71E914DB700615A2C /* TableMappingTests.swift */; };
|
||||
565029CA1E914DB700615A2C /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565029C71E914DB700615A2C /* TableMappingTests.swift */; };
|
||||
@@ -1903,6 +1918,8 @@
|
||||
5636E9BB1D22574100B9B05F /* Request.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = "<group>"; };
|
||||
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
|
||||
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
|
||||
565029C71E914DB700615A2C /* TableMappingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMappingTests.swift; sourceTree = "<group>"; };
|
||||
565490A01D5A4798005622CB /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
565490E51D5AE282005622CB /* libsqlite3.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libsqlite3.tbd; path = Platforms/WatchOS.platform/Developer/SDKs/WatchOS2.2.sdk/usr/lib/libsqlite3.tbd; sourceTree = DEVELOPER_DIR; };
|
||||
@@ -2636,6 +2653,7 @@
|
||||
children = (
|
||||
56DAA2C41DE99D8D006E10C8 /* Cursor */,
|
||||
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */,
|
||||
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */,
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */,
|
||||
56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */,
|
||||
560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */,
|
||||
@@ -2726,6 +2744,7 @@
|
||||
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */,
|
||||
56A238711B9C75030082EB20 /* Database.swift */,
|
||||
56A238731B9C75030082EB20 /* DatabaseError.swift */,
|
||||
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */,
|
||||
560A37A31C8F625000949E71 /* DatabasePool.swift */,
|
||||
56A238741B9C75030082EB20 /* DatabaseQueue.swift */,
|
||||
563363BF1C942C04000BE133 /* DatabaseReader.swift */,
|
||||
@@ -3834,6 +3853,7 @@
|
||||
560FC5231CB003810014AA8E /* Configuration.swift in Sources */,
|
||||
566475CD1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
5698AC381D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
|
||||
564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */,
|
||||
5659F4991EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
56CEB54D1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
5664759B1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
|
||||
@@ -3988,6 +4008,7 @@
|
||||
560FC5961CB00B880014AA8E /* DatabaseValueConvertibleFetchTests.swift in Sources */,
|
||||
560FC5971CB00B880014AA8E /* DatabaseErrorTests.swift in Sources */,
|
||||
560FC5991CB00B880014AA8E /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
|
||||
564F9C1F1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
562393731DEE104400A6B01F /* MapCursorTests.swift in Sources */,
|
||||
5698AC9F1DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
|
||||
56176C621EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
|
||||
@@ -4042,6 +4063,7 @@
|
||||
56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */,
|
||||
56D121601ED34978001347D2 /* Fixits-0.109.0.swift in Sources */,
|
||||
564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */,
|
||||
566475A81D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
|
||||
5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
@@ -4223,6 +4245,7 @@
|
||||
565EFAF01D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */,
|
||||
567156551CB16729007DC145 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
|
||||
567156561CB16729007DC145 /* DatabaseErrorTests.swift in Sources */,
|
||||
564F9C201F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
562393741DEE104400A6B01F /* MapCursorTests.swift in Sources */,
|
||||
5698ACA01DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
|
||||
56176C681EACCCC8000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
|
||||
@@ -4284,6 +4307,7 @@
|
||||
56AFC9F71CB1A8BB00F48B96 /* RawRepresentable.swift in Sources */,
|
||||
566475D01D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
5698AC3B1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
|
||||
564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */,
|
||||
5659F49C1EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
56CEB5501EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
5664759E1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
|
||||
@@ -4438,6 +4462,7 @@
|
||||
56AFCA641CB1AA9900F48B96 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
|
||||
56A8C24A1D1918F10096E9D4 /* FoundationUUIDTests.swift in Sources */,
|
||||
56AFCA651CB1AA9900F48B96 /* DatabaseErrorTests.swift in Sources */,
|
||||
564F9C231F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
5690C32B1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
5623936E1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
|
||||
56176C741EACCCCA000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
|
||||
@@ -4568,6 +4593,7 @@
|
||||
56AFCAB91CB1ABC800F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
56AFCABA1CB1ABC800F48B96 /* RecordEditedTests.swift in Sources */,
|
||||
56AFCABB1CB1ABC800F48B96 /* DatabasePoolSchemaCacheTests.swift in Sources */,
|
||||
564F9C241F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
56AFCABC1CB1ABC800F48B96 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
|
||||
5623936F1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
|
||||
56176C7A1EACCCCB000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
|
||||
@@ -4684,6 +4710,7 @@
|
||||
56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */,
|
||||
56CEB55D1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */,
|
||||
56CEB5641EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
|
||||
564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */,
|
||||
56B964A01DA51B4C0002DA19 /* FTS5.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -4782,6 +4809,7 @@
|
||||
5698ACA21DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
|
||||
56A2385C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
|
||||
56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
|
||||
564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */,
|
||||
56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */,
|
||||
5690C32A1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
@@ -4912,6 +4940,7 @@
|
||||
56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */,
|
||||
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
|
||||
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */,
|
||||
56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */,
|
||||
56B021C91D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */,
|
||||
@@ -4973,6 +5002,7 @@
|
||||
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
|
||||
566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
|
||||
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
|
||||
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
|
||||
@@ -5058,6 +5088,7 @@
|
||||
F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */,
|
||||
F3BA80161CFB2876003DC1BA /* Row.swift in Sources */,
|
||||
F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */,
|
||||
564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */,
|
||||
5659F49D1EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
56CEB5511EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
|
||||
@@ -5212,6 +5243,7 @@
|
||||
5698ACA51DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
|
||||
F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */,
|
||||
56A8C24E1D1918F30096E9D4 /* FoundationUUIDTests.swift in Sources */,
|
||||
564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
5657AB3D1D108BA9006283EF /* FoundationDataTests.swift in Sources */,
|
||||
5690C32D1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
562393791DEE104400A6B01F /* MapCursorTests.swift in Sources */,
|
||||
@@ -5273,6 +5305,7 @@
|
||||
F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */,
|
||||
F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */,
|
||||
F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */,
|
||||
564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */,
|
||||
5659F49A1EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
56CEB54E1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */,
|
||||
5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
|
||||
@@ -5427,6 +5460,7 @@
|
||||
5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
|
||||
F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */,
|
||||
5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */,
|
||||
564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
F3BA80ED1CFB3017003DC1BA /* RowFromDictionaryTests.swift in Sources */,
|
||||
5690C3291D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
5657AB391D108BA9006283EF /* FoundationDataTests.swift in Sources */,
|
||||
|
||||
+2
-105
@@ -872,116 +872,13 @@ extension Database {
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
|
||||
public func add(function: DatabaseFunction) {
|
||||
functions.update(with: function)
|
||||
let functionPointer = unsafeBitCast(function, to: UnsafeMutableRawPointer.self)
|
||||
let code = sqlite3_create_function_v2(
|
||||
sqliteConnection,
|
||||
function.name,
|
||||
function.argumentCount,
|
||||
SQLITE_UTF8 | function.eTextRep,
|
||||
functionPointer,
|
||||
{ (context, argc, argv) in
|
||||
let function = unsafeBitCast(sqlite3_user_data(context), to: DatabaseFunction.self)
|
||||
do {
|
||||
let result = try function.function(argc, argv)
|
||||
switch result.storage {
|
||||
case .null:
|
||||
sqlite3_result_null(context)
|
||||
case .int64(let int64):
|
||||
sqlite3_result_int64(context, int64)
|
||||
case .double(let double):
|
||||
sqlite3_result_double(context, double)
|
||||
case .string(let string):
|
||||
sqlite3_result_text(context, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes { bytes in
|
||||
sqlite3_result_blob(context, bytes, Int32(data.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
} catch let error as DatabaseError {
|
||||
if let message = error.message {
|
||||
sqlite3_result_error(context, message, -1)
|
||||
}
|
||||
sqlite3_result_error_code(context, error.extendedResultCode.rawValue)
|
||||
} catch {
|
||||
sqlite3_result_error(context, "\(error)", -1)
|
||||
}
|
||||
}, nil, nil, nil)
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
|
||||
}
|
||||
function.install(in: self)
|
||||
}
|
||||
|
||||
/// Remove an SQL function.
|
||||
public func remove(function: DatabaseFunction) {
|
||||
functions.remove(function)
|
||||
let code = sqlite3_create_function_v2(
|
||||
sqliteConnection,
|
||||
function.name,
|
||||
function.argumentCount,
|
||||
SQLITE_UTF8 | function.eTextRep,
|
||||
nil, nil, nil, nil, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// An SQL function.
|
||||
public final class DatabaseFunction {
|
||||
public let name: String
|
||||
let argumentCount: Int32
|
||||
let pure: Bool
|
||||
let function: (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValue
|
||||
var eTextRep: Int32 { return pure ? SQLITE_DETERMINISTIC : 0 }
|
||||
|
||||
/// Returns an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// db.add(function: fn)
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - argumentCount: The number of arguments of the function. If
|
||||
/// omitted, or nil, the function accepts any number of arguments.
|
||||
/// - pure: Whether the function is "pure", which means that its results
|
||||
/// only depends on its inputs. When a function is pure, SQLite has
|
||||
/// the opportunity to perform additional optimizations. Default value
|
||||
/// is false.
|
||||
/// - function: A function that takes an array of DatabaseValue
|
||||
/// arguments, and returns an optional DatabaseValueConvertible such
|
||||
/// as Int, String, NSDate, etc. The array is guaranteed to have
|
||||
/// exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// not nil.
|
||||
public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) {
|
||||
self.name = name
|
||||
self.argumentCount = argumentCount ?? -1
|
||||
self.pure = pure
|
||||
self.function = { (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!) }
|
||||
return try function(arguments)?.databaseValue ?? .null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseFunction : Hashable {
|
||||
/// The hash value
|
||||
public var hashValue: Int {
|
||||
return name.hashValue ^ argumentCount.hashValue
|
||||
}
|
||||
|
||||
/// Two functions are equal if they share the same name and argumentCount.
|
||||
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
|
||||
return lhs.name == rhs.name && lhs.argumentCount == rhs.argumentCount
|
||||
function.uninstall(in: self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,369 @@
|
||||
#if SWIFT_PACKAGE
|
||||
import CSQLite
|
||||
#endif
|
||||
|
||||
/// An SQL function or aggregate.
|
||||
public final class DatabaseFunction {
|
||||
public let name: String
|
||||
let argumentCount: Int32?
|
||||
let pure: Bool
|
||||
private let kind: Kind
|
||||
fileprivate var nArg: Int32 { return argumentCount ?? -1 }
|
||||
fileprivate var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
|
||||
/// Returns an SQL function.
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// db.add(function: fn)
|
||||
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - argumentCount: The number of arguments of the function. If
|
||||
/// omitted, or nil, the function accepts any number of arguments.
|
||||
/// - pure: Whether the function is "pure", which means that its results
|
||||
/// only depends on its inputs. When a function is pure, SQLite has
|
||||
/// the opportunity to perform additional optimizations. Default value
|
||||
/// is false.
|
||||
/// - function: A function that takes an array of DatabaseValue
|
||||
/// arguments, and returns an optional DatabaseValueConvertible such
|
||||
/// as Int, String, NSDate, etc. The array is guaranteed to have
|
||||
/// exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// not nil.
|
||||
public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) {
|
||||
self.name = name
|
||||
self.argumentCount = argumentCount
|
||||
self.pure = pure
|
||||
self.kind = .function{ (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
}
|
||||
return try function(arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an SQL aggregate function.
|
||||
///
|
||||
/// struct MySum : DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
///
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> DatabaseValueConvertible? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.execute("CREATE TABLE test(i)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - argumentCount: The number of arguments of the aggregate. If
|
||||
/// omitted, or nil, the aggregate accepts any number of arguments.
|
||||
/// - pure: Whether the aggregate is "pure", which means that its
|
||||
/// results only depends on its inputs. When an aggregate is pure,
|
||||
/// SQLite has the opportunity to perform additional optimizations.
|
||||
/// Default value is false.
|
||||
/// - aggregate: A type that implements the DatabaseAggregate protocol.
|
||||
/// For each step of the aggregation, its `step` method is called with
|
||||
/// an array of DatabaseValue arguments. The array is guaranteed to
|
||||
/// have exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// not nil.
|
||||
public init<Aggregate: DatabaseAggregate>(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) {
|
||||
self.name = name
|
||||
self.argumentCount = argumentCount
|
||||
self.pure = pure
|
||||
self.kind = .aggregate { return Aggregate() }
|
||||
}
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See https://sqlite.org/c3ref/create_function.html
|
||||
func install(in db: Database) {
|
||||
// Retain the function definition
|
||||
let definition = kind.definition
|
||||
let definitionP = Unmanaged.passRetained(definition).toOpaque()
|
||||
|
||||
let code = sqlite3_create_function_v2(
|
||||
db.sqliteConnection,
|
||||
name,
|
||||
nArg,
|
||||
eTextRep,
|
||||
definitionP,
|
||||
kind.xFunc,
|
||||
kind.xStep,
|
||||
kind.xFinal,
|
||||
{ definitionP in
|
||||
// Release the function definition
|
||||
Unmanaged<AnyObject>.fromOpaque(definitionP!).release()
|
||||
})
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See https://sqlite.org/c3ref/create_function.html
|
||||
func uninstall(in db: Database) {
|
||||
let code = sqlite3_create_function_v2(
|
||||
db.sqliteConnection,
|
||||
name,
|
||||
nArg,
|
||||
eTextRep,
|
||||
nil, nil, nil, nil, nil)
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
|
||||
}
|
||||
}
|
||||
|
||||
/// The way to compute the result of a function.
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
private class FunctionDefinition {
|
||||
let compute: (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?
|
||||
init(compute: @escaping (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?) {
|
||||
self.compute = compute
|
||||
}
|
||||
}
|
||||
|
||||
/// The way to start an aggregate.
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
private class AggregateDefinition {
|
||||
let makeAggregate: () -> DatabaseAggregate
|
||||
init(makeAggregate: @escaping () -> DatabaseAggregate) {
|
||||
self.makeAggregate = makeAggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// The current state of an aggregate, storable in SQLite
|
||||
private class AggregateContext {
|
||||
var aggregate: DatabaseAggregate
|
||||
var hasErrored = false
|
||||
init(aggregate: DatabaseAggregate) {
|
||||
self.aggregate = aggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// A function kind: an "SQL function" or an "aggregate".
|
||||
/// See http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
private enum Kind {
|
||||
/// A regular function: SELECT f(1)
|
||||
case function((Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?)
|
||||
|
||||
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
|
||||
case aggregate(() -> DatabaseAggregate)
|
||||
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
var definition: AnyObject {
|
||||
switch self {
|
||||
case .function(let compute):
|
||||
return FunctionDefinition(compute: compute)
|
||||
case .aggregate(let makeAggregate):
|
||||
return AggregateDefinition(makeAggregate: makeAggregate)
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .function = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
let definition = Unmanaged<FunctionDefinition>.fromOpaque(sqlite3_user_data(sqliteContext)).takeUnretainedValue()
|
||||
do {
|
||||
try DatabaseFunction.report(
|
||||
result: definition.compute(argc, argv),
|
||||
in: sqliteContext)
|
||||
} catch {
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xStep` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .aggregate = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
|
||||
let aggregateContext = aggregateContextU.takeUnretainedValue()
|
||||
assert(!aggregateContext.hasErrored)
|
||||
do {
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
}
|
||||
try aggregateContext.aggregate.step(arguments)
|
||||
} catch {
|
||||
aggregateContext.hasErrored = true
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xFinal` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
var xFinal: (@convention(c) (OpaquePointer?) -> Void)? {
|
||||
guard case .aggregate = self else { return nil }
|
||||
return { (sqliteContext) in
|
||||
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
|
||||
let aggregateContext = aggregateContextU.takeUnretainedValue()
|
||||
aggregateContextU.release()
|
||||
|
||||
guard !aggregateContext.hasErrored else {
|
||||
return
|
||||
}
|
||||
|
||||
do {
|
||||
try DatabaseFunction.report(
|
||||
result: aggregateContext.aggregate.finalize(),
|
||||
in: sqliteContext)
|
||||
} catch {
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper function that extracts the current state of an aggregate from an
|
||||
/// sqlite function execution context.
|
||||
///
|
||||
/// The result must be released when the aggregate concludes.
|
||||
///
|
||||
/// See https://sqlite.org/c3ref/context.html
|
||||
/// See https://sqlite.org/c3ref/aggregate_context.html
|
||||
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
|
||||
// The current aggregate buffer
|
||||
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
|
||||
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride)
|
||||
|
||||
if aggregateContextBufferP.contains(where: { $0 != 0 }) {
|
||||
// Buffer contains non-null pointer: load aggregate context
|
||||
let aggregateContextP = aggregateContextBufferP.baseAddress!.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
|
||||
return aggregateContextP.pointee
|
||||
} else {
|
||||
// Buffer contains null pointer: create aggregate context...
|
||||
let aggregate = Unmanaged<AggregateDefinition>.fromOpaque(sqlite3_user_data(sqliteContext))
|
||||
.takeUnretainedValue()
|
||||
.makeAggregate()
|
||||
let aggregateContext = AggregateContext(aggregate: aggregate)
|
||||
|
||||
// retain and store in SQLite's buffer
|
||||
let aggregateContextU = Unmanaged.passRetained(aggregateContext)
|
||||
var aggregateContextP = aggregateContextU.toOpaque()
|
||||
withUnsafeBytes(of: &aggregateContextP) {
|
||||
aggregateContextBufferP.copyBytes(from: $0)
|
||||
}
|
||||
return aggregateContextU
|
||||
}
|
||||
}
|
||||
|
||||
private static func report(result: DatabaseValueConvertible?, in sqliteContext: OpaquePointer?) {
|
||||
switch result?.databaseValue.storage ?? .null {
|
||||
case .null:
|
||||
sqlite3_result_null(sqliteContext)
|
||||
case .int64(let int64):
|
||||
sqlite3_result_int64(sqliteContext, int64)
|
||||
case .double(let double):
|
||||
sqlite3_result_double(sqliteContext, double)
|
||||
case .string(let string):
|
||||
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes { bytes in
|
||||
sqlite3_result_blob(sqliteContext, bytes, Int32(data.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func report(error: Error, in sqliteContext: OpaquePointer?) {
|
||||
if let error = error as? DatabaseError {
|
||||
if let message = error.message {
|
||||
sqlite3_result_error(sqliteContext, message, -1)
|
||||
}
|
||||
sqlite3_result_error_code(sqliteContext, error.extendedResultCode.rawValue)
|
||||
} else {
|
||||
sqlite3_result_error(sqliteContext, "\(error)", -1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseFunction : Hashable {
|
||||
/// The hash value
|
||||
public var hashValue: Int {
|
||||
return name.hashValue ^ nArg.hashValue
|
||||
}
|
||||
|
||||
/// Two functions are equal if they share the same name and arity.
|
||||
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
|
||||
return lhs.name == rhs.name && lhs.nArg == rhs.nArg
|
||||
}
|
||||
}
|
||||
|
||||
/// The protocol for custom SQLite aggregates.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct MySum : DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
///
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> DatabaseValueConvertible? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// dbQueue.add(function: fn)
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.execute("CREATE TABLE test(i)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute("INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
public protocol DatabaseAggregate {
|
||||
/// Creates an aggregate.
|
||||
init()
|
||||
|
||||
/// This method is called at each step of the aggregation.
|
||||
///
|
||||
/// The dbValues argument contains as many values as given to the SQL
|
||||
/// aggregate function.
|
||||
///
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM persons
|
||||
///
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM persons
|
||||
///
|
||||
/// This method is never called after the finalize() method has been called.
|
||||
mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
|
||||
/// Returns the final result
|
||||
func finalize() throws -> DatabaseValueConvertible?
|
||||
}
|
||||
@@ -62,10 +62,8 @@ public final class DatabasePool {
|
||||
// Readers
|
||||
readerConfig = configuration
|
||||
readerConfig.readonly = true
|
||||
readerConfig.defaultTransactionKind = .deferred // Make it the default. Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
|
||||
readerPool = Pool<SerializedDatabase>(maximumCount: configuration.maximumReaderCount)
|
||||
readerPool.makeElement = { [unowned self] in
|
||||
readerConfig.defaultTransactionKind = .deferred // Make it the default for readers. Other transaction kinds are forbidden by SQLite in read-only connections.
|
||||
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
|
||||
let reader = try SerializedDatabase(
|
||||
path: path,
|
||||
configuration: self.readerConfig,
|
||||
@@ -81,7 +79,7 @@ public final class DatabasePool {
|
||||
}
|
||||
|
||||
return reader
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
@@ -191,7 +189,7 @@ public final class DatabasePool {
|
||||
|
||||
fileprivate let writer: SerializedDatabase
|
||||
fileprivate var readerConfig: Configuration
|
||||
fileprivate let readerPool: Pool<SerializedDatabase>
|
||||
fileprivate var readerPool: Pool<SerializedDatabase>! = nil // var and nil-initialized so that we can use `self` when creating readerPool in DatabasePool.init()
|
||||
|
||||
fileprivate var functions = Set<DatabaseFunction>()
|
||||
fileprivate var collations = Set<DatabaseCollation>()
|
||||
@@ -250,11 +248,12 @@ extension DatabasePool : DatabaseReader {
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func read<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync { db in
|
||||
var result: T? = nil
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
// See DatabasePoolTests.testReadMethodIsolationOfBlock().
|
||||
try db.inTransaction(.deferred) {
|
||||
result = try block(db)
|
||||
return .commit
|
||||
@@ -291,11 +290,71 @@ extension DatabasePool : DatabaseReader {
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync(block)
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes a read-only block in a protected dispatch queue,
|
||||
/// and returns its result.
|
||||
///
|
||||
/// The block argument is not isolated: eventual concurrent database updates
|
||||
/// are visible inside the block:
|
||||
///
|
||||
/// try dbPool.unsafeReentrantRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iteration is safe, though:
|
||||
///
|
||||
/// try dbPool.unsafeReentrantRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync(block)
|
||||
} else {
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync(block)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
var readers: [SerializedDatabase] = []
|
||||
readerPool.forEach { reader in
|
||||
// We can't check for reader.onValidQueue here because
|
||||
// Pool.forEach() runs its closure argument in some arbitrary
|
||||
// dispatch queue. We thus extract the reader so that we can query
|
||||
// it below.
|
||||
readers.append(reader)
|
||||
}
|
||||
|
||||
// Now the readers array contains some readers. The pool readers may
|
||||
// already be different, because some other thread may have started
|
||||
// a new read, for example.
|
||||
//
|
||||
// This doesn't matter: the reader we are looking for is already on
|
||||
// its own dispatch queue. If it exists, is still in use, thus still
|
||||
// in the pool, and thus still relevant for our check:
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
|
||||
@@ -248,6 +248,19 @@ extension DatabaseQueue : DatabaseReader {
|
||||
return try inDatabase(block)
|
||||
}
|
||||
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// try dbQueue.unsafeReentrantRead { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
return try serializedDatabase.reentrantSync(block)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
@@ -332,7 +345,7 @@ extension DatabaseQueue : DatabaseWriter {
|
||||
/// Synchronously executes a block in a protected dispatch queue, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// let persons = try dbQueue.unsafeReentrantWrite { db in
|
||||
/// try dbQueue.unsafeReentrantWrite { db in
|
||||
/// try db.execute(...)
|
||||
/// }
|
||||
///
|
||||
|
||||
@@ -79,6 +79,40 @@ public protocol DatabaseReader : class {
|
||||
/// happen while establishing the read access to the database.
|
||||
func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Synchronously executes a block that takes a database connection, and
|
||||
/// returns its result.
|
||||
///
|
||||
/// The two guarantees of the safe `read` method are lifted:
|
||||
///
|
||||
/// The block argument is not isolated: eventual concurrent database updates
|
||||
/// are visible inside the block:
|
||||
///
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // Those two values may be different because some other thread
|
||||
/// // may have inserted or deleted a wine between the two requests:
|
||||
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
|
||||
/// }
|
||||
///
|
||||
/// Cursor iterations are isolated, though:
|
||||
///
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // No concurrent update can mess with this iteration:
|
||||
/// let rows = try Row.fetchCursor(db, "SELECT ...")
|
||||
/// while let row = try rows.next() { ... }
|
||||
/// }
|
||||
///
|
||||
/// The block argument is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `unsafeReentrantRead`).
|
||||
///
|
||||
/// - parameter block: A block that accesses the database.
|
||||
/// - throws: The error thrown by the block, or any DatabaseError that would
|
||||
/// happen while establishing the read access to the database.
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
|
||||
+4
-11
@@ -219,8 +219,7 @@ public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
adaptedRequest = AdaptedRequest(base, adapter)
|
||||
}
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
@@ -228,23 +227,17 @@ public struct AdaptedTypedRequest<Base: TypedRequest> : TypedRequest {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
let (statement, baseAdapter) = try base.prepare(db)
|
||||
if let baseAdapter = baseAdapter {
|
||||
return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db)))
|
||||
} else {
|
||||
return try (statement, adapter(db))
|
||||
}
|
||||
return try adaptedRequest.prepare(db)
|
||||
}
|
||||
|
||||
/// The number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
return try base.fetchCount(db)
|
||||
return try adaptedRequest.fetchCount(db)
|
||||
}
|
||||
|
||||
private let base: Base
|
||||
private let adapter: (Database) throws -> RowAdapter
|
||||
private let adaptedRequest: AdaptedRequest<Base>
|
||||
}
|
||||
|
||||
/// A type-erased TypedRequest.
|
||||
|
||||
@@ -149,14 +149,10 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an optional database connection. If not nil, the caller is
|
||||
/// executing on the serialized dispatch queue.
|
||||
var availableDatabaseConnection: Database? {
|
||||
guard let watchdog = SchedulingWatchdog.current else { return nil }
|
||||
guard watchdog.allows(db) else { return nil }
|
||||
return db
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
return SchedulingWatchdog.allows(db)
|
||||
}
|
||||
|
||||
|
||||
/// Executes the block in the current queue.
|
||||
///
|
||||
|
||||
@@ -18,7 +18,9 @@ public class Statement {
|
||||
|
||||
/// The SQL query
|
||||
public var sql: String {
|
||||
// trim white space and semicolumn for homogeneous output
|
||||
return String(cString: sqlite3_sql(sqliteStatement))
|
||||
.trimmingCharacters(in: CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines))
|
||||
}
|
||||
|
||||
/// The database
|
||||
|
||||
@@ -169,6 +169,7 @@ extension QueryInterfaceRequest {
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// request
|
||||
/// .order(Column("email"))
|
||||
/// .reversed()
|
||||
/// .order(Column("name"))
|
||||
public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<T> {
|
||||
return order(orderings)
|
||||
@@ -185,10 +186,12 @@ extension QueryInterfaceRequest {
|
||||
/// // SELECT * FROM persons ORDER BY name
|
||||
/// request
|
||||
/// .order([Column("email")])
|
||||
/// .reversed()
|
||||
/// .order([Column("name")])
|
||||
public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<T> {
|
||||
var query = self.query
|
||||
query.orderings = orderings
|
||||
query.isReversed = false
|
||||
return QueryInterfaceRequest(query: query)
|
||||
}
|
||||
|
||||
|
||||
@@ -251,11 +251,11 @@ public final class TableDefinition {
|
||||
/// See https://www.sqlite.org/lang_createtable.html#tablecoldef
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
/// - parameter type: the column type.
|
||||
/// - parameter type: the eventual column type.
|
||||
/// - returns: An ColumnDefinition that allows you to refine the
|
||||
/// column definition.
|
||||
@discardableResult
|
||||
public func column(_ name: String, _ type: Database.ColumnType) -> ColumnDefinition {
|
||||
public func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition {
|
||||
let column = ColumnDefinition(name: name, type: type)
|
||||
columns.append(column)
|
||||
return column
|
||||
@@ -358,95 +358,111 @@ public final class TableDefinition {
|
||||
}
|
||||
|
||||
fileprivate func sql(_ db: Database) throws -> String {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CREATE")
|
||||
if temporary {
|
||||
chunks.append("TEMPORARY")
|
||||
}
|
||||
chunks.append("TABLE")
|
||||
if ifNotExists {
|
||||
chunks.append("IF NOT EXISTS")
|
||||
}
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
|
||||
let primaryKeyColumns: [String]
|
||||
if let (columns, _) = primaryKeyConstraint {
|
||||
primaryKeyColumns = columns
|
||||
} else if let index = columns.index(where: { $0.primaryKey != nil }) {
|
||||
primaryKeyColumns = [columns[index].name]
|
||||
} else {
|
||||
primaryKeyColumns = []
|
||||
}
|
||||
var statements: [String] = []
|
||||
|
||||
do {
|
||||
var items: [String] = []
|
||||
try items.append(contentsOf: columns.map { try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) })
|
||||
var chunks: [String] = []
|
||||
chunks.append("CREATE")
|
||||
if temporary {
|
||||
chunks.append("TEMPORARY")
|
||||
}
|
||||
chunks.append("TABLE")
|
||||
if ifNotExists {
|
||||
chunks.append("IF NOT EXISTS")
|
||||
}
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
|
||||
if let (columns, conflictResolution) = primaryKeyConstraint {
|
||||
var chunks: [String] = []
|
||||
chunks.append("PRIMARY KEY")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
let primaryKeyColumns: [String]
|
||||
if let (columns, _) = primaryKeyConstraint {
|
||||
primaryKeyColumns = columns
|
||||
} else if let index = columns.index(where: { $0.primaryKey != nil }) {
|
||||
primaryKeyColumns = [columns[index].name]
|
||||
} else {
|
||||
// WITHOUT ROWID optimization requires a primary key. If the
|
||||
// user sets withoutRowID, but does not define a primary key,
|
||||
// this is undefined behavior.
|
||||
//
|
||||
// We thus can use the rowId column even when the withoutRowID
|
||||
// flag is set ;-)
|
||||
primaryKeyColumns = [Column.rowID.name]
|
||||
}
|
||||
|
||||
for (columns, conflictResolution) in uniqueKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("UNIQUE")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
do {
|
||||
var items: [String] = []
|
||||
try items.append(contentsOf: columns.map { try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) })
|
||||
|
||||
if let (columns, conflictResolution) = primaryKeyConstraint {
|
||||
var chunks: [String] = []
|
||||
chunks.append("PRIMARY KEY")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
|
||||
for (columns, conflictResolution) in uniqueKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("UNIQUE")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
if let conflictResolution = conflictResolution {
|
||||
chunks.append("ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("FOREIGN KEY")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
chunks.append("REFERENCES")
|
||||
if let destinationColumns = destinationColumns {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if table == name {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if let primaryKey = try db.primaryKey(table) {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else {
|
||||
// Programmer error
|
||||
fatalError("explicit referenced column(s) required, since table \(table) has no primary key")
|
||||
}
|
||||
if let deleteAction = deleteAction {
|
||||
chunks.append("ON DELETE")
|
||||
chunks.append(deleteAction.rawValue)
|
||||
}
|
||||
if let updateAction = updateAction {
|
||||
chunks.append("ON UPDATE")
|
||||
chunks.append(updateAction.rawValue)
|
||||
}
|
||||
if deferred {
|
||||
chunks.append("DEFERRABLE INITIALLY DEFERRED")
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
for checkExpression in checkConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CHECK")
|
||||
chunks.append("(" + checkExpression.sql + ")")
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
chunks.append("(\(items.joined(separator: ", ")))")
|
||||
}
|
||||
|
||||
for (columns, table, destinationColumns, deleteAction, updateAction, deferred) in foreignKeyConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("FOREIGN KEY")
|
||||
chunks.append("(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
chunks.append("REFERENCES")
|
||||
if let destinationColumns = destinationColumns {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((destinationColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if table == name {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if let primaryKey = try db.primaryKey(table) {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else {
|
||||
// Programmer error
|
||||
fatalError("explicit referenced column(s) required, since table \(table) has no primary key")
|
||||
}
|
||||
if let deleteAction = deleteAction {
|
||||
chunks.append("ON DELETE")
|
||||
chunks.append(deleteAction.rawValue)
|
||||
}
|
||||
if let updateAction = updateAction {
|
||||
chunks.append("ON UPDATE")
|
||||
chunks.append(updateAction.rawValue)
|
||||
}
|
||||
if deferred {
|
||||
chunks.append("DEFERRABLE INITIALLY DEFERRED")
|
||||
}
|
||||
items.append(chunks.joined(separator: " "))
|
||||
if withoutRowID {
|
||||
chunks.append("WITHOUT ROWID")
|
||||
}
|
||||
|
||||
for checkExpression in checkConstraints {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CHECK")
|
||||
chunks.append("(" + checkExpression.sql + ")")
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
chunks.append("(\(items.joined(separator: ", ")))")
|
||||
statements.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
if withoutRowID {
|
||||
chunks.append("WITHOUT ROWID")
|
||||
}
|
||||
return chunks.joined(separator: " ")
|
||||
let indexStatements = columns
|
||||
.flatMap { $0.indexDefinition(in: name) }
|
||||
.map { $0.sql() }
|
||||
statements.append(contentsOf: indexStatements)
|
||||
return statements.joined(separator: "; ")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -495,9 +511,13 @@ public final class TableAlteration {
|
||||
chunks.append("ALTER TABLE")
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
chunks.append("ADD COLUMN")
|
||||
try chunks.append(column.sql(db, tableName: nil, primaryKeyColumns: nil))
|
||||
try chunks.append(column.sql(db, tableName: name, primaryKeyColumns: nil))
|
||||
let statement = chunks.joined(separator: " ")
|
||||
statements.append(statement)
|
||||
|
||||
if let indexDefinition = column.indexDefinition(in: name) {
|
||||
statements.append(indexDefinition.sql())
|
||||
}
|
||||
}
|
||||
|
||||
return statements.joined(separator: "; ")
|
||||
@@ -519,17 +539,22 @@ public final class TableAlteration {
|
||||
/// See https://www.sqlite.org/lang_createtable.html and
|
||||
/// https://www.sqlite.org/lang_altertable.html
|
||||
public final class ColumnDefinition {
|
||||
enum Index {
|
||||
case none
|
||||
case index
|
||||
case unique(Database.ConflictResolution)
|
||||
}
|
||||
fileprivate let name: String
|
||||
private let type: Database.ColumnType
|
||||
private let type: Database.ColumnType?
|
||||
fileprivate var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)?
|
||||
private var index: Index = .none
|
||||
private var notNullConflictResolution: Database.ConflictResolution?
|
||||
private var uniqueConflictResolution: Database.ConflictResolution?
|
||||
private var checkConstraints: [SQLExpression] = []
|
||||
private var foreignKeyConstraints: [(table: String, column: String?, deleteAction: Database.ForeignKeyAction?, updateAction: Database.ForeignKeyAction?, deferred: Bool)] = []
|
||||
private var defaultExpression: SQLExpression?
|
||||
private var collationName: String?
|
||||
|
||||
init(name: String, type: Database.ColumnType) {
|
||||
init(name: String, type: Database.ColumnType?) {
|
||||
self.name = name
|
||||
self.type = type
|
||||
}
|
||||
@@ -584,7 +609,24 @@ public final class ColumnDefinition {
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
|
||||
uniqueConflictResolution = conflictResolution ?? .abort
|
||||
index = .unique(conflictResolution ?? .abort)
|
||||
return self
|
||||
}
|
||||
|
||||
/// Adds an index of the column.
|
||||
///
|
||||
/// try db.create(table: "persons") { t in
|
||||
/// t.column("email", .text).indexed()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#uniqueconst
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
public func indexed() -> Self {
|
||||
if case .none = index {
|
||||
self.index = .index
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
@@ -708,10 +750,12 @@ public final class ColumnDefinition {
|
||||
return self
|
||||
}
|
||||
|
||||
fileprivate func sql(_ db: Database, tableName: String?, primaryKeyColumns: [String]?) throws -> String {
|
||||
fileprivate func sql(_ db: Database, tableName: String, primaryKeyColumns: [String]?) throws -> String {
|
||||
var chunks: [String] = []
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
chunks.append(type.rawValue)
|
||||
if let type = type {
|
||||
chunks.append(type.rawValue)
|
||||
}
|
||||
|
||||
if let (conflictResolution, autoincrement) = primaryKey {
|
||||
chunks.append("PRIMARY KEY")
|
||||
@@ -734,14 +778,19 @@ public final class ColumnDefinition {
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
|
||||
switch uniqueConflictResolution {
|
||||
switch index {
|
||||
case .none:
|
||||
break
|
||||
case .abort?:
|
||||
chunks.append("UNIQUE")
|
||||
case let conflictResolution?:
|
||||
chunks.append("UNIQUE ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
case .unique(let conflictResolution):
|
||||
switch conflictResolution {
|
||||
case .abort:
|
||||
chunks.append("UNIQUE")
|
||||
default:
|
||||
chunks.append("UNIQUE ON CONFLICT")
|
||||
chunks.append(conflictResolution.rawValue)
|
||||
}
|
||||
case .index:
|
||||
break
|
||||
}
|
||||
|
||||
for checkConstraint in checkConstraints {
|
||||
@@ -762,14 +811,16 @@ public final class ColumnDefinition {
|
||||
for (table, column, deleteAction, updateAction, deferred) in foreignKeyConstraints {
|
||||
chunks.append("REFERENCES")
|
||||
if let column = column {
|
||||
// explicit reference
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))")
|
||||
} else if let tableName = tableName, let primaryKeyColumns = primaryKeyColumns, table == tableName {
|
||||
} else if table.lowercased() == tableName.lowercased() {
|
||||
// implicit autoreference
|
||||
let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(table)?.columns ?? [Column.rowID.name]
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else if let primaryKey = try db.primaryKey(table) {
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKey.columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
} else {
|
||||
// Programmer error
|
||||
fatalError("explicit referenced column required, since table \(table) has no primary key")
|
||||
// implicit external reference
|
||||
let primaryKeyColumns = try db.primaryKey(table)?.columns ?? [Column.rowID.name]
|
||||
chunks.append("\(table.quotedDatabaseIdentifier)(\((primaryKeyColumns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
|
||||
}
|
||||
if let deleteAction = deleteAction {
|
||||
chunks.append("ON DELETE")
|
||||
@@ -786,6 +837,21 @@ public final class ColumnDefinition {
|
||||
|
||||
return chunks.joined(separator: " ")
|
||||
}
|
||||
|
||||
fileprivate func indexDefinition(in table: String) -> IndexDefinition? {
|
||||
switch index {
|
||||
case .none: return nil
|
||||
case .unique: return nil
|
||||
case .index:
|
||||
return IndexDefinition(
|
||||
name: "\(table)_on_\(name)",
|
||||
table: table,
|
||||
columns: [name],
|
||||
unique: false,
|
||||
ifNotExists: false,
|
||||
condition: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct IndexDefinition {
|
||||
|
||||
@@ -37,8 +37,19 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
///
|
||||
/// This function should return true if the two records have the
|
||||
/// same identity. For example, they have the same id.
|
||||
public convenience init(_ databaseWriter: DatabaseWriter, sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, queue: DispatchQueue = .main, isSameRecord: ((Record, Record) -> Bool)? = nil) throws {
|
||||
try self.init(databaseWriter, request: SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self), queue: queue, isSameRecord: isSameRecord)
|
||||
public convenience init(
|
||||
_ databaseWriter: DatabaseWriter,
|
||||
sql: String,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil,
|
||||
queue: DispatchQueue = .main,
|
||||
isSameRecord: ((Record, Record) -> Bool)? = nil) throws
|
||||
{
|
||||
try self.init(
|
||||
databaseWriter,
|
||||
request: SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self),
|
||||
queue: queue,
|
||||
isSameRecord: isSameRecord)
|
||||
}
|
||||
|
||||
/// Creates a fetched records controller initialized from a fetch request
|
||||
@@ -63,18 +74,40 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
///
|
||||
/// This function should return true if the two records have the
|
||||
/// same identity. For example, they have the same id.
|
||||
public convenience init<Request>(_ databaseWriter: DatabaseWriter, request: Request, queue: DispatchQueue = .main, isSameRecord: ((Record, Record) -> Bool)? = nil) throws where Request: TypedRequest, Request.RowDecoder == Record {
|
||||
public convenience init<Request>(
|
||||
_ databaseWriter: DatabaseWriter,
|
||||
request: Request,
|
||||
queue: DispatchQueue = .main,
|
||||
isSameRecord: ((Record, Record) -> Bool)? = nil) throws
|
||||
where Request: TypedRequest, Request.RowDecoder == Record
|
||||
{
|
||||
let itemsAreIdenticalFactory: ItemComparatorFactory<Record>
|
||||
if let isSameRecord = isSameRecord {
|
||||
try self.init(databaseWriter, request: request, queue: queue, itemsAreIdentical: { isSameRecord($0.record, $1.record) })
|
||||
itemsAreIdenticalFactory = { _ in { isSameRecord($0.record, $1.record) } }
|
||||
} else {
|
||||
try self.init(databaseWriter, request: request, queue: queue, itemsAreIdentical: { _ in false })
|
||||
itemsAreIdenticalFactory = { _ in { _ in false } }
|
||||
}
|
||||
|
||||
try self.init(
|
||||
databaseWriter,
|
||||
request: request,
|
||||
queue: queue,
|
||||
itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
}
|
||||
|
||||
fileprivate init<Request>(_ databaseWriter: DatabaseWriter, request: Request, queue: DispatchQueue, itemsAreIdentical: @escaping ItemComparator<Record>) throws where Request: TypedRequest, Request.RowDecoder == Record {
|
||||
self.request = try databaseWriter.unsafeRead { db in try ObservedRequest(db, request: request) }
|
||||
fileprivate init<Request>(
|
||||
_ databaseWriter: DatabaseWriter,
|
||||
request: Request,
|
||||
queue: DispatchQueue,
|
||||
itemsAreIdenticalFactory: @escaping ItemComparatorFactory<Record>) throws
|
||||
where Request: TypedRequest, Request.RowDecoder == Record
|
||||
{
|
||||
self.itemsAreIdenticalFactory = itemsAreIdenticalFactory
|
||||
self.request = request
|
||||
(self.selectionInfo, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
|
||||
try FetchedRecordsController.fetchSelectionInfoAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
}
|
||||
self.databaseWriter = databaseWriter
|
||||
self.itemsAreIdentical = itemsAreIdentical
|
||||
self.queue = queue
|
||||
}
|
||||
|
||||
@@ -97,10 +130,10 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
// observer is added on the same serialized queue as transaction
|
||||
// callbacks.
|
||||
try databaseWriter.write { db in
|
||||
let initialItems = try request.fetchAll(db)
|
||||
let initialItems = try Item<Record>.fetchAll(db, request)
|
||||
fetchedItems = initialItems
|
||||
if let fetchAndNotifyChanges = fetchAndNotifyChanges {
|
||||
let observer = FetchedRecordsObserver(selectionInfo: request.selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
let observer = FetchedRecordsObserver(selectionInfo: self.selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
self.observer = observer
|
||||
observer.items = initialItems
|
||||
db.add(transactionObserver: observer)
|
||||
@@ -128,7 +161,10 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
/// This method must be used from the controller's dispatch queue (the
|
||||
/// main queue unless stated otherwise in the controller's initializer).
|
||||
public func setRequest<Request>(_ request: Request) throws where Request: TypedRequest, Request.RowDecoder == Record {
|
||||
self.request = try databaseWriter.unsafeRead { db in try ObservedRequest(db, request: request) }
|
||||
self.request = request
|
||||
(self.selectionInfo, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
|
||||
try FetchedRecordsController.fetchSelectionInfoAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
}
|
||||
|
||||
// No observer: don't look for changes
|
||||
guard let observer = observer else { return }
|
||||
@@ -143,7 +179,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
// and notify eventual changes
|
||||
let initialItems = fetchedItems
|
||||
databaseWriter.write { db in
|
||||
let observer = FetchedRecordsObserver(selectionInfo: self.request.selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
let observer = FetchedRecordsObserver(selectionInfo: selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
self.observer = observer
|
||||
observer.items = initialItems
|
||||
db.add(transactionObserver: observer)
|
||||
@@ -241,7 +277,7 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
onChange: onChange,
|
||||
didChange: didChange,
|
||||
didProcessTransaction: didProcessTransaction)
|
||||
let observer = FetchedRecordsObserver(selectionInfo: request.selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
let observer = FetchedRecordsObserver(selectionInfo: selectionInfo, fetchAndNotifyChanges: fetchAndNotifyChanges)
|
||||
self.observer = observer
|
||||
if let initialItems = initialItems {
|
||||
observer.items = initialItems
|
||||
@@ -313,31 +349,32 @@ public final class FetchedRecordsController<Record: RowConvertible> {
|
||||
|
||||
/// The record comparator
|
||||
fileprivate var itemsAreIdentical: ItemComparator<Record>
|
||||
|
||||
/// The record comparator factory (support for request change)
|
||||
fileprivate let itemsAreIdenticalFactory: ItemComparatorFactory<Record>
|
||||
|
||||
/// The request
|
||||
fileprivate var request: ObservedRequest<Record>
|
||||
fileprivate var request: Request
|
||||
|
||||
/// The observed selection info
|
||||
fileprivate var selectionInfo : SelectStatement.SelectionInfo
|
||||
|
||||
/// The eventual current database observer
|
||||
private var observer: FetchedRecordsObserver<Record>?
|
||||
|
||||
/// The eventual error handler
|
||||
fileprivate var errorHandler: ((FetchedRecordsController<Record>, Error) -> ())?
|
||||
}
|
||||
|
||||
fileprivate struct ObservedRequest<Record: RowConvertible> : TypedRequest {
|
||||
/// The type that can convert raw database rows to fetched values
|
||||
typealias RowDecoder = Item<Record>
|
||||
let request: Request
|
||||
let selectionInfo: SelectStatement.SelectionInfo
|
||||
|
||||
init(_ db: Database, request: Request) throws {
|
||||
private static func fetchSelectionInfoAndComparator(
|
||||
_ db: Database,
|
||||
request: Request,
|
||||
itemsAreIdenticalFactory: ItemComparatorFactory<Record>) throws
|
||||
-> (SelectStatement.SelectionInfo, ItemComparator<Record>)
|
||||
{
|
||||
let (statement, _) = try request.prepare(db)
|
||||
self.request = request
|
||||
self.selectionInfo = statement.selectionInfo
|
||||
}
|
||||
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
return try request.prepare(db)
|
||||
let selectionInfo = statement.selectionInfo
|
||||
let itemsAreIdentical = try itemsAreIdenticalFactory(db)
|
||||
return (selectionInfo, itemsAreIdentical)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -374,8 +411,17 @@ extension FetchedRecordsController where Record: TableMapping {
|
||||
/// The fetched records controller tracking callbacks will be
|
||||
/// notified of changes in this queue. The controller itself must be
|
||||
/// used from this queue.
|
||||
public convenience init(_ databaseWriter: DatabaseWriter, sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, queue: DispatchQueue = .main) throws {
|
||||
try self.init(databaseWriter, request: SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self), queue: queue)
|
||||
public convenience init(
|
||||
_ databaseWriter: DatabaseWriter,
|
||||
sql: String,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil,
|
||||
queue: DispatchQueue = .main) throws
|
||||
{
|
||||
try self.init(
|
||||
databaseWriter,
|
||||
request: SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self),
|
||||
queue: queue)
|
||||
}
|
||||
|
||||
/// Creates a fetched records controller initialized from a fetch request
|
||||
@@ -404,9 +450,47 @@ extension FetchedRecordsController where Record: TableMapping {
|
||||
/// The fetched records controller tracking callbacks will be
|
||||
/// notified of changes in this queue. The controller itself must be
|
||||
/// used from this queue.
|
||||
public convenience init<Request>(_ databaseWriter: DatabaseWriter, request: Request, queue: DispatchQueue = .main) throws where Request: TypedRequest, Request.RowDecoder == Record {
|
||||
let rowComparator = try databaseWriter.unsafeRead { db in try Record.primaryKeyRowComparator(db) }
|
||||
try self.init(databaseWriter, request: request, queue: queue, itemsAreIdentical: { rowComparator($0.row, $1.row) })
|
||||
public convenience init<Request>(
|
||||
_ databaseWriter: DatabaseWriter,
|
||||
request: Request,
|
||||
queue: DispatchQueue = .main) throws
|
||||
where Request: TypedRequest, Request.RowDecoder == Record
|
||||
{
|
||||
// Builds a function that returns true if and only if two items
|
||||
// have the same primary key and primary keys contain at least one
|
||||
// non-null value.
|
||||
let itemsAreIdenticalFactory: ItemComparatorFactory<Record> = { db in
|
||||
// Extract primary key columns from database table
|
||||
let columns: [String]
|
||||
if let primaryKey = try db.primaryKey(Record.databaseTableName) {
|
||||
columns = primaryKey.columns
|
||||
} else if Record.selectsRowID {
|
||||
columns = [Column.rowID.name]
|
||||
} else {
|
||||
// No primary key => can't compare rows
|
||||
return { _ in false }
|
||||
}
|
||||
|
||||
// Compare primary keys
|
||||
assert(!columns.isEmpty)
|
||||
return { (lItem, rItem) in
|
||||
for column in columns {
|
||||
let lValue: DatabaseValue = lItem.row.value(named: column)
|
||||
let rValue: DatabaseValue = rItem.row.value(named: column)
|
||||
if lValue != rValue {
|
||||
// different primary keys
|
||||
return false
|
||||
}
|
||||
}
|
||||
// identical primary keys
|
||||
return true
|
||||
}
|
||||
}
|
||||
try self.init(
|
||||
databaseWriter,
|
||||
request: request,
|
||||
queue: queue,
|
||||
itemsAreIdenticalFactory: itemsAreIdenticalFactory)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -524,7 +608,7 @@ fileprivate func makeFetchFunction<Record, T>(
|
||||
do {
|
||||
try databaseWriter.readFromCurrentState { db in
|
||||
result = Result { try (
|
||||
fetchedItems: request.fetchAll(db),
|
||||
fetchedItems: Item<Record>.fetchAll(db, request),
|
||||
fetchedAlongside: fetchAlongside(db)) }
|
||||
semaphore.signal()
|
||||
}
|
||||
@@ -772,6 +856,7 @@ fileprivate func identicalItemArrays<Record>(_ lhs: [Item<Record>], _ rhs: [Item
|
||||
// MARK: - UITableView Support
|
||||
|
||||
fileprivate typealias ItemComparator<Record: RowConvertible> = (Item<Record>, Item<Record>) -> Bool
|
||||
fileprivate typealias ItemComparatorFactory<Record: RowConvertible> = (Database) throws -> ItemComparator<Record>
|
||||
|
||||
extension FetchedRecordsController {
|
||||
|
||||
|
||||
@@ -715,8 +715,8 @@ final class DAO {
|
||||
var updatedColumns: [String] = []
|
||||
for column in columns {
|
||||
let lowercaseColumn = column.lowercased()
|
||||
// Make sure the requested column is present in persistenceContainer
|
||||
GRDBPrecondition(lowercasePersistentColumns.contains(lowercaseColumn), "column \(column) can't be updated because it is missing from persistence container")
|
||||
// Don't update columns that are not present in the persistenceContainer
|
||||
guard lowercasePersistentColumns.contains(lowercaseColumn) else { continue }
|
||||
// Don't update primary key columns
|
||||
guard !lowercasePrimaryKeyColumns.contains(lowercaseColumn) else { continue }
|
||||
updatedColumns.append(column)
|
||||
|
||||
@@ -249,6 +249,9 @@ extension TableMapping {
|
||||
/// }
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
/// - attention: This method is deprecated. It will be removed is the next
|
||||
/// major version of the library, without any replacement.
|
||||
@available(*, deprecated)
|
||||
public static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool {
|
||||
let primaryKey = try rowPrimaryKey(db)
|
||||
return { (lhs, rhs) in
|
||||
|
||||
+28
-27
@@ -36,30 +36,39 @@ import Dispatch
|
||||
/// got 1
|
||||
/// got 3
|
||||
final class Pool<T> {
|
||||
var makeElement: (() throws -> T)?
|
||||
private var items: [PoolItem<T>] = []
|
||||
private let queue: DispatchQueue // protects items
|
||||
private class Item {
|
||||
let element: T
|
||||
var available: Bool
|
||||
|
||||
init(element: T, available: Bool) {
|
||||
self.element = element
|
||||
self.available = available
|
||||
}
|
||||
}
|
||||
|
||||
private let makeElement: () throws -> T
|
||||
private var items: ReadWriteBox<[Item]> = ReadWriteBox([])
|
||||
private let semaphore: DispatchSemaphore // limits the number of elements
|
||||
|
||||
init(maximumCount: Int, makeElement: (() throws -> T)? = nil) {
|
||||
init(maximumCount: Int, makeElement: @escaping () throws -> T) {
|
||||
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
|
||||
self.makeElement = makeElement
|
||||
self.queue = DispatchQueue(label: "GRDB.Pool")
|
||||
self.semaphore = DispatchSemaphore(value: maximumCount)
|
||||
}
|
||||
|
||||
/// Returns a tuple (element, releaseElement())
|
||||
/// Client MUST call releaseElement() after the element has been used.
|
||||
/// Returns a tuple (element, release)
|
||||
/// Client MUST call release() after the element has been used.
|
||||
func get() throws -> (T, () -> ()) {
|
||||
var item: PoolItem<T>! = nil
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
var item: Item! = nil
|
||||
do {
|
||||
try queue.sync {
|
||||
try items.write { items in
|
||||
if let availableItem = items.first(where: { $0.available }) {
|
||||
item = availableItem
|
||||
item.available = false
|
||||
} else {
|
||||
item = try PoolItem(element: makeElement!(), available: false)
|
||||
let element = try makeElement()
|
||||
item = Item(element: element, available: false)
|
||||
items.append(item)
|
||||
}
|
||||
}
|
||||
@@ -67,13 +76,15 @@ final class Pool<T> {
|
||||
semaphore.signal()
|
||||
throw error
|
||||
}
|
||||
let unlock = {
|
||||
self.queue.sync {
|
||||
let release = {
|
||||
self.items.write { _ in
|
||||
// This is why Item is a class, not a struct: so that we can
|
||||
// release it without having to find in it the items array.
|
||||
item.available = true
|
||||
}
|
||||
self.semaphore.signal()
|
||||
}
|
||||
return (item.element, unlock)
|
||||
return (item.element, release)
|
||||
}
|
||||
|
||||
/// Performs a synchronous block with an element. The element turns
|
||||
@@ -85,9 +96,9 @@ final class Pool<T> {
|
||||
}
|
||||
|
||||
/// Performs a block on each pool element, available or not.
|
||||
/// The block is run is some arbitrary queue.
|
||||
/// The block is run is some arbitrary dispatch queue.
|
||||
func forEach(_ body: (T) throws -> ()) rethrows {
|
||||
try queue.sync {
|
||||
try items.read { items in
|
||||
for item in items {
|
||||
try body(item.element)
|
||||
}
|
||||
@@ -102,19 +113,9 @@ final class Pool<T> {
|
||||
/// Empty the pool. Currently used items won't be reused.
|
||||
/// Eventual block is executed before any other element is dequeued.
|
||||
func clear(andThen block: () throws -> ()) rethrows {
|
||||
try queue.sync {
|
||||
items = []
|
||||
try items.write { items in
|
||||
items.removeAll()
|
||||
try block()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class PoolItem<T> {
|
||||
let element: T
|
||||
var available: Bool
|
||||
|
||||
init(element: T, available: Bool) {
|
||||
self.element = element
|
||||
self.available = available
|
||||
}
|
||||
}
|
||||
@@ -12,17 +12,15 @@ final class ReadWriteBox<T> {
|
||||
self.queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent])
|
||||
}
|
||||
|
||||
func read<U>(_ block: (T) -> U) -> U {
|
||||
var result: U? = nil
|
||||
queue.sync {
|
||||
result = block(self._value)
|
||||
func read<U>(_ block: (T) throws -> U) rethrows -> U {
|
||||
return try queue.sync {
|
||||
try block(_value)
|
||||
}
|
||||
return result!
|
||||
}
|
||||
|
||||
func write(_ block: (inout T) -> Void) {
|
||||
queue.sync(flags: [.barrier]) {
|
||||
block(&self._value)
|
||||
func write(_ block: (inout T) throws -> Void) rethrows {
|
||||
try queue.sync(flags: [.barrier]) {
|
||||
try block(&_value)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDBCipher'
|
||||
s.version = '1.0'
|
||||
s.version = '1.2'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A Swift application toolkit for SQLite databases.'
|
||||
|
||||
@@ -46,41 +46,43 @@ TEST_ACTIONS = clean build build-for-testing test-without-building
|
||||
# xcodebuild destination to run tests on iOS 8.1 (requires a pre-installed simulator)
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=8.1"
|
||||
|
||||
ifeq ($(XCODEVERSION),8.3)
|
||||
# xcodebuild destination to run tests on latest iOS (Xcode 8.3.3)
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 7,OS=10.3.1"
|
||||
ifeq ($(XCODEVERSION),9.0)
|
||||
# xcodebuild destination to run tests on latest iOS (Xcode 9.0)
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 7,OS=11.0"
|
||||
else ifeq ($(XCODEVERSION),8.3)
|
||||
# xcodebuild destination to run tests on latest iOS (Xcode 8.3.3)
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 7,OS=10.3.1"
|
||||
else
|
||||
# Xcode < 8.3 is not supported
|
||||
echo "Makefile does not explicitly support Xcode $(XCODEVERSION) ($(XCODEVERSION_FULL))."
|
||||
# Xcode < 8.3 is not supported
|
||||
endif
|
||||
|
||||
# If xcpretty is available, use it for xcodebuild output
|
||||
XCPRETTY =
|
||||
ifdef XCPRETTY_PATH
|
||||
XCPRETTY = | xcpretty -c
|
||||
|
||||
# On Travis-CI, use xcpretty-travis-formatter
|
||||
ifeq ($(TRAVIS),true)
|
||||
XCPRETTY += -f `xcpretty-travis-formatter`
|
||||
endif
|
||||
XCPRETTY = | xcpretty -c
|
||||
|
||||
# On Travis-CI, use xcpretty-travis-formatter
|
||||
ifeq ($(TRAVIS),true)
|
||||
XCPRETTY += -f `xcpretty-travis-formatter`
|
||||
endif
|
||||
endif
|
||||
|
||||
ifdef TOOLCHAIN
|
||||
# If TOOLCHAIN is specified, add xcodebuild parameter
|
||||
XCODEBUILD += -toolchain $(TOOLCHAIN)
|
||||
|
||||
# If TOOLCHAIN is specified, get the location of the toolchain’s SWIFT
|
||||
TOOLCHAINSWIFT = $(shell $(XCRUN) --toolchain '$(TOOLCHAIN)' --find swift 2> /dev/null)
|
||||
ifdef TOOLCHAINSWIFT
|
||||
# Update the SWIFT path to the toolchain’s SWIFT
|
||||
SWIFT = $(TOOLCHAINSWIFT)
|
||||
else
|
||||
@echo Cannot find `swift` for specified toolchain.
|
||||
@exit 1
|
||||
endif
|
||||
# If TOOLCHAIN is specified, add xcodebuild parameter
|
||||
XCODEBUILD += -toolchain $(TOOLCHAIN)
|
||||
|
||||
# If TOOLCHAIN is specified, get the location of the toolchain’s SWIFT
|
||||
TOOLCHAINSWIFT = $(shell $(XCRUN) --toolchain '$(TOOLCHAIN)' --find swift 2> /dev/null)
|
||||
ifdef TOOLCHAINSWIFT
|
||||
# Update the SWIFT path to the toolchain’s SWIFT
|
||||
SWIFT = $(TOOLCHAINSWIFT)
|
||||
else
|
||||
@echo Cannot find `swift` for specified toolchain.
|
||||
@exit 1
|
||||
endif
|
||||
else
|
||||
# If TOOLCHAIN is not specified, use standard Swift
|
||||
SWIFT = $(shell $(XCRUN) --find swift 2> /dev/null)
|
||||
# If TOOLCHAIN is not specified, use standard Swift
|
||||
SWIFT = $(shell $(XCRUN) --find swift 2> /dev/null)
|
||||
endif
|
||||
|
||||
# We test framework test suites, and if GRBD can be installed in an application:
|
||||
@@ -286,10 +288,10 @@ ifdef JAZZY
|
||||
--author 'Gwendal Roué' \
|
||||
--author_url https://github.com/groue \
|
||||
--github_url https://github.com/groue/GRDB.swift \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v1.0 \
|
||||
--module-version 1.0 \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v1.2 \
|
||||
--module-version 1.2 \
|
||||
--module GRDB \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/1.0/ \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/1.2/ \
|
||||
--output Documentation/Reference \
|
||||
--podspec GRDB.swift.podspec
|
||||
else
|
||||
|
||||
@@ -3,14 +3,15 @@ GRDB.swift [
|
||||
**Latest release**: July 13, 2017 • version 1.2 • [CHANGELOG](CHANGELOG.md)
|
||||
|
||||
**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Xcode 8.3+ • Swift 3.1
|
||||
|
||||
- Swift 2.2: use [version 0.80.2](https://github.com/groue/GRDB.swift/tree/v0.80.2)
|
||||
- Swift 2.3: use [version 0.81.2](https://github.com/groue/GRDB.swift/tree/v0.81.2)
|
||||
- Swift 3.0: use [version 1.0](https://github.com/groue/GRDB.swift/tree/v1.0)
|
||||
- Xcode 9 beta 1 with Swift 3 compatibility mode: use the master branch
|
||||
- Xcode 9 beta, Swift 3.2: use the master branch
|
||||
- Xcode 9 beta, Swift 4: use the [Swift4](https://github.com/groue/GRDB.swift/tree/Swift4) branch
|
||||
|
||||
Follow [@groue](http://twitter.com/groue) on Twitter for release announcements and usage tips.
|
||||
|
||||
@@ -188,7 +189,7 @@ Documentation
|
||||
|
||||
**Reference**
|
||||
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/1.0/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/1.2/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
|
||||
**Getting Started**
|
||||
|
||||
@@ -241,7 +242,7 @@ See [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) for the installa
|
||||
|
||||
## CocoaPods
|
||||
|
||||
[CocoaPods](http://cocoapods.org/) is a dependency manager for Xcode projects. To use GRDB.swift with CocoaPods (version 1.1 or higher), specify in your `Podfile`:
|
||||
[CocoaPods](http://cocoapods.org/) is a dependency manager for Xcode projects. To use GRDB.swift with CocoaPods (version 1.2 or higher), specify in your `Podfile`:
|
||||
|
||||
```ruby
|
||||
use_frameworks!
|
||||
@@ -274,7 +275,7 @@ Any pull request that has the `make test_CarthageBuild` command successfully com
|
||||
|
||||
## Manually
|
||||
|
||||
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/1.0) a copy of GRDB.swift, or clone its repository and make sure you use the latest tagged version with the `git checkout v1.0` command.
|
||||
1. [Download](https://github.com/groue/GRDB.swift/releases/tag/1.2) a copy of GRDB.swift, or clone its repository and make sure you use the latest tagged version with the `git checkout v1.2` command.
|
||||
|
||||
2. Embed the `GRDB.xcodeproj` project in your own project.
|
||||
|
||||
@@ -373,7 +374,7 @@ let dbQueue = try DatabaseQueue(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/1.0/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/1.2/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
## Database Pools
|
||||
@@ -452,7 +453,7 @@ let dbPool = try DatabasePool(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/1.0/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/1.2/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
|
||||
@@ -479,7 +480,7 @@ Advanced topics:
|
||||
|
||||
- [Custom Value Types](#custom-value-types)
|
||||
- [Prepared Statements](#prepared-statements)
|
||||
- [Custom SQL Functions](#custom-sql-functions)
|
||||
- [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates)
|
||||
- [Database Schema Introspection](#database-schema-introspection)
|
||||
- [Row Adapters](#row-adapters)
|
||||
- [Raw SQLite Pointers](#raw-sqlite-pointers)
|
||||
@@ -700,7 +701,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/1.0/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/1.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:
|
||||
|
||||
@@ -938,7 +939,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/1.0/Structs/StatementArguments.html):
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/1.2/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let url: URL = ...
|
||||
@@ -1330,7 +1331,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/1.0/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/1.2/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
|
||||
```swift
|
||||
updateStatement.arguments = ["name": "Arthur", "age": 41]
|
||||
@@ -1381,14 +1382,25 @@ let selectStatement = try db.cachedSelectStatement(sql)
|
||||
Should a cached prepared statement throw an error, don't reuse it (it is a programmer error). Instead, reload it from the cache.
|
||||
|
||||
|
||||
## Custom SQL Functions
|
||||
## Custom SQL Functions and Aggregates
|
||||
|
||||
**SQLite lets you define SQL functions.**
|
||||
**SQLite lets you define SQL functions and aggregates.**
|
||||
|
||||
A custom SQL function extends SQLite. It can be used in raw SQL queries. And when SQLite needs to evaluate it, it calls your custom code.
|
||||
A custom SQL function or aggregate extends SQLite:
|
||||
|
||||
```sql
|
||||
SELECT reverse(name) FROM persons; -- custom function
|
||||
SELECT maxLength(name) FROM persons; -- custom aggregate
|
||||
```
|
||||
|
||||
- [Custom SQL Functions](#custom-sql-functions)
|
||||
- [Custom Aggregates](#custom-aggregates)
|
||||
|
||||
|
||||
### Custom SQL Functions
|
||||
|
||||
```swift
|
||||
let reverseString = DatabaseFunction("reverseString", argumentCount: 1, pure: true) { (values: [DatabaseValue]) in
|
||||
let reverse = DatabaseFunction("reverse", argumentCount: 1, pure: true) { (values: [DatabaseValue]) in
|
||||
// Extract string value, if any...
|
||||
guard let string = String.fromDatabaseValue(values[0]) else {
|
||||
return nil
|
||||
@@ -1396,11 +1408,11 @@ let reverseString = DatabaseFunction("reverseString", argumentCount: 1, pure: tr
|
||||
// ... and return reversed string:
|
||||
return String(string.characters.reversed())
|
||||
}
|
||||
dbQueue.add(function: reverseString) // Or dbPool.add(function: ...)
|
||||
dbQueue.add(function: reverse) // Or dbPool.add(function: ...)
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
// "oof"
|
||||
try String.fetchOne(db, "SELECT reverseString('foo')")!
|
||||
try String.fetchOne(db, "SELECT reverse('foo')")!
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1459,6 +1471,77 @@ Person.select(reverseString.apply(nameColumn))
|
||||
**GRDB ships with built-in SQL functions that perform unicode-aware string transformations.** See [Unicode](#unicode).
|
||||
|
||||
|
||||
### Custom Aggregates
|
||||
|
||||
Before registering a custom aggregate, you need to define a type that adopts the `DatabaseAggregate` protocol:
|
||||
|
||||
```swift
|
||||
protocol DatabaseAggregate {
|
||||
// Initializes an aggregate
|
||||
init()
|
||||
|
||||
// Called at each step of the aggregation
|
||||
mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
|
||||
// Returns the final result
|
||||
func finalize() throws -> DatabaseValueConvertible?
|
||||
}
|
||||
```
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
struct MaxLength : DatabaseAggregate {
|
||||
var maxLength: Int = 0
|
||||
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
// At each step, extract string value, if any...
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
return
|
||||
}
|
||||
// ... and update the result
|
||||
let length = string.characters.count
|
||||
if length > maxLength {
|
||||
maxLength = length
|
||||
}
|
||||
}
|
||||
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return maxLength
|
||||
}
|
||||
}
|
||||
|
||||
let maxLength = DatabaseFunction(
|
||||
"maxLength",
|
||||
argumentCount: 1,
|
||||
pure: true,
|
||||
aggregate: MaxLength.self)
|
||||
|
||||
dbQueue.add(function: maxLength) // Or dbPool.add(function: ...)
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
// Some Int
|
||||
try Int.fetchOne(db, "SELECT maxLength(name) FROM persons")!
|
||||
}
|
||||
```
|
||||
|
||||
The `step` method of the aggregate takes an array of [DatabaseValue](#databasevalue). This array contains as many values as the *argumentCount* parameter (or any number of values, when *argumentCount* is omitted).
|
||||
|
||||
The `finalize` method of the aggregate returns the final aggregated [value](#values) (Bool, Int, String, Date, Swift enums, etc.).
|
||||
|
||||
SQLite has the opportunity to perform additional optimizations when aggregates are "pure", which means that their result only depends on their inputs. So make sure to set the *pure* argument to true when possible.
|
||||
|
||||
|
||||
**Use custom aggregates in the [query interface](#the-query-interface):**
|
||||
|
||||
```swift
|
||||
// SELECT maxLength("name") FROM persons
|
||||
Person.select(maxLength.apply(nameColumn))
|
||||
.asRequest(of: Int.self)
|
||||
.fetchOne(db) // Int?
|
||||
```
|
||||
|
||||
|
||||
## Database Schema Introspection
|
||||
|
||||
**SQLite provides database schema introspection tools**, such as the [sqlite_master](https://www.sqlite.org/faq.html#q7) table, and the pragma [table_info](https://www.sqlite.org/pragma.html#pragma_table_info):
|
||||
@@ -1546,7 +1629,7 @@ row.value(named: "consumed") // "Hello"
|
||||
row.value(named: "produced") // nil
|
||||
```
|
||||
|
||||
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/1.0/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/1.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
|
||||
@@ -1671,24 +1754,24 @@ try dbQueue.inDatabase { db in
|
||||
|
||||
Before jumping in the low-level wagon, here is the list of all SQLite APIs used by GRDB:
|
||||
|
||||
- `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/1.0/Structs/Configuration.html)
|
||||
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/1.0/Classes/Database.html)
|
||||
- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/1.2/Structs/Configuration.html)
|
||||
- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/1.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)
|
||||
- `sqlite3_create_collation_v2`: see [String Comparison](#string-comparison)
|
||||
- `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](#custom-sql-functions)
|
||||
- `sqlite3_db_release_memory`: see [Memory Management](#memory-management)
|
||||
- `sqlite3_errcode`, `sqlite3_errmsg`, `sqlite3_errstr`, `sqlite3_extended_result_codes`: see [Error Handling](#error-handling)
|
||||
- `sqlite3_key`, `sqlite3_rekey`: see [Encryption](#encryption)
|
||||
- `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/1.0/Classes/Statement.html)
|
||||
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/1.0/Structs/Configuration.html)
|
||||
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/1.0/Classes/DatabasePool.html)
|
||||
- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/1.2/Classes/Statement.html)
|
||||
- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/1.2/Structs/Configuration.html)
|
||||
- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/1.2/Classes/DatabasePool.html)
|
||||
|
||||
|
||||
Records
|
||||
@@ -1899,7 +1982,7 @@ try PointOfInterest.fetchAll(db, "SELECT ...", arguments:...) // [PointOfInte
|
||||
try PointOfInterest.fetchOne(db, "SELECT ...", arguments:...) // PointOfInterest?
|
||||
```
|
||||
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/1.0/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/1.2/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
|
||||
|
||||
### RowConvertible and Row Adapters
|
||||
@@ -2614,11 +2697,15 @@ try db.create(table: "example") { t in ... }
|
||||
try db.create(table: "example", temporary: true, ifNotExists: true) { t in
|
||||
```
|
||||
|
||||
**Add regular columns** with their name and type (text, integer, double, numeric, boolean, blob, date and datetime) - see [SQLite data types](https://www.sqlite.org/datatype3.html):
|
||||
**Add regular columns** with their name and eventual type (text, integer, double, numeric, boolean, blob, date and datetime) - see [SQLite data types](https://www.sqlite.org/datatype3.html):
|
||||
|
||||
```swift
|
||||
// name TEXT,
|
||||
// creationDate DATETIME,
|
||||
// CREATE TABLE example (
|
||||
// a,
|
||||
// name TEXT,
|
||||
// creationDate DATETIME,
|
||||
try db.create(table: "example") { t in ... }
|
||||
t.column("a")
|
||||
t.column("name", .text)
|
||||
t.column("creationDate", .datetime)
|
||||
```
|
||||
@@ -2646,6 +2733,14 @@ Use an individual column as **primary**, **unique**, or **foreign key**. When de
|
||||
t.column("countryCode", .text).references("countries", onDelete: .cascade)
|
||||
```
|
||||
|
||||
**Create an index** on the column:
|
||||
|
||||
```swift
|
||||
t.column("score", .integer).indexed()
|
||||
```
|
||||
|
||||
For extra index options, see [Create Indexes](#create-indexes) below.
|
||||
|
||||
**Perform integrity checks** on individual columns, and SQLite will only let conforming rows in. In the example below, the `$0` closure variable is a column which lets you build any SQL [expression](#expressions).
|
||||
|
||||
```swift
|
||||
@@ -2867,7 +2962,7 @@ Person // SELECT * FROM persons
|
||||
```
|
||||
|
||||
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/1.0/Structs/StatementArguments.html):
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/1.2/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
// SELECT DATE(creationDate), COUNT(*) FROM persons WHERE name = 'Arthur' GROUP BY date(creationDate)
|
||||
@@ -3039,9 +3134,9 @@ Feed [requests](#requests) with SQL expressions built from your Swift code:
|
||||
> nameColumn.collating(.caseInsensitiveCompare) == name
|
||||
> ```
|
||||
|
||||
- Custom SQL functions
|
||||
- Custom SQL functions and aggregates
|
||||
|
||||
You can apply your own [custom SQL functions](#custom-sql-functions):
|
||||
You can apply your own [custom SQL functions and aggregates](#custom-functions-):
|
||||
|
||||
```swift
|
||||
let f = DatabaseFunction("f", ...)
|
||||
@@ -3220,10 +3315,10 @@ Those requests of type `QueryInterfaceRequest` can fetch, count, and delete reco
|
||||
|
||||
```swift
|
||||
try request.fetchCursor(db) // DatabaseCursor<Person>
|
||||
try request.fetchAll() // [Person]
|
||||
try request.fetchOne() // Person?
|
||||
try request.fetchCount() // Int
|
||||
try request.deleteAll()
|
||||
try request.fetchAll(db) // [Person]
|
||||
try request.fetchOne(db) // Person?
|
||||
try request.fetchCount(db) // Int
|
||||
try request.deleteAll(db)
|
||||
```
|
||||
|
||||
**When the query interface can not generate the SQL you need**, you can still fallback to [raw SQL](#fetch-queries):
|
||||
@@ -3276,7 +3371,7 @@ try String.fetchAll(db, request) // [String]
|
||||
try Person.fetchOne(db, request) // Person?
|
||||
```
|
||||
|
||||
A TypedRequest knows exactly what it has to do when its RowDecoder associated type can decode database rows ([Row](#fetching-rows) itself, [values](#value-queries), or [records](#records)):
|
||||
On top of that, a TypedRequest knows exactly what it has to do when its RowDecoder associated type can decode database rows ([Row](#fetching-rows) itself, [values](#value-queries), or [records](#records)):
|
||||
|
||||
```swift
|
||||
let request = ... // Some TypedRequest that fetches Person
|
||||
@@ -3290,11 +3385,9 @@ try request.fetchOne(db) // Person?
|
||||
|
||||
**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:
|
||||
|
||||
- [Request](http://groue.github.io/GRDB.swift/docs/1.0/Protocols/Request.html): the protocol for all requests
|
||||
- [TypedRequest](http://groue.github.io/GRDB.swift/docs/1.0/Protocols/TypedRequest.html): the protocol for all typed requests
|
||||
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/1.0/Structs/SQLRequest.html): a Request built from raw SQL
|
||||
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/1.0/Structs/AnyRequest.html): a type-erased Request
|
||||
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/1.0/Structs/AnyTypedRequest.html): a type-erased TypedRequest
|
||||
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/1.2/Structs/SQLRequest.html): a Request built from raw SQL
|
||||
- [AnyRequest](http://groue.github.io/GRDB.swift/docs/1.2/Structs/AnyRequest.html): a type-erased Request
|
||||
- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/1.2/Structs/AnyTypedRequest.html): a type-erased TypedRequest
|
||||
|
||||
Use the `asRequest(of:)` method to define the type fetched by the request:
|
||||
|
||||
@@ -3723,7 +3816,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/1.0/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/1.2/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -3936,7 +4029,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/1.0/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/1.2/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -4705,7 +4798,7 @@ try controller.performFetch()
|
||||
|
||||
**GRDB can encrypt your database with [SQLCipher](http://sqlcipher.net) v3.4.1.**
|
||||
|
||||
You can use [CocoaPods](http://cocoapods.org/) (version 1.1 or higher), and specify in your `Podfile`:
|
||||
You can use [CocoaPods](http://cocoapods.org/) (version 1.2 or higher), and specify in your `Podfile`:
|
||||
|
||||
```ruby
|
||||
use_frameworks!
|
||||
@@ -4718,7 +4811,7 @@ Alternatively, perform a manual installation of GRDB and SQLCipher:
|
||||
|
||||
```sh
|
||||
cd [GRDB.swift directory]
|
||||
git checkout v1.0
|
||||
git checkout v1.2
|
||||
git submodule update --init SQLCipher/src
|
||||
```
|
||||
|
||||
@@ -4825,7 +4918,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/1.0/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/1.2/Structs/StatementArguments.html) to your SQL queries:
|
||||
|
||||
```swift
|
||||
// Good
|
||||
@@ -5078,7 +5171,7 @@ The `UPPER` and `LOWER` built-in SQLite functions are not unicode-aware:
|
||||
try String.fetchOne(db, "SELECT UPPER('Jérôme')")
|
||||
```
|
||||
|
||||
GRDB extends SQLite with [SQL functions](#custom-sql-functions) that call the Swift built-in string functions `capitalized`, `lowercased`, `uppercased`, `localizedCapitalized`, `localizedLowercased` and `localizedUppercased`:
|
||||
GRDB extends SQLite with [SQL functions](#custom-sql-functions-and-aggregates) that call the Swift built-in string functions `capitalized`, `lowercased`, `uppercased`, `localizedCapitalized`, `localizedLowercased` and `localizedUppercased`:
|
||||
|
||||
```swift
|
||||
// "JÉRÔME"
|
||||
@@ -5213,6 +5306,7 @@ You can catch those errors and wait for [UIApplicationDelegate.applicationProtec
|
||||
- [Guarantees and Rules](#guarantees-and-rules)
|
||||
- [Advanced DatabasePool](#advanced-databasepool)
|
||||
- [DatabaseWriter and DatabaseReader Protocols](#databasewriter-and-databasereader-protocols)
|
||||
- [Unsafe Concurrency APIs](#unsafe-concurrency-apis)
|
||||
- [Dealing with External Connections](#dealing-with-external-connections)
|
||||
|
||||
|
||||
@@ -5399,7 +5493,7 @@ try dbPool.write { db in
|
||||
|
||||
### DatabaseWriter and DatabaseReader Protocols
|
||||
|
||||
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/1.0/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/1.0/Protocols/DatabaseWriter.html) protocols.
|
||||
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/1.2/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/1.2/Protocols/DatabaseWriter.html) protocols.
|
||||
|
||||
These protocols provide a unified API that lets you write safe concurrent code that targets both classes.
|
||||
|
||||
@@ -5407,11 +5501,73 @@ 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/1.0/Protocols/DatabaseWriter.html#/s:FP4GRDB14DatabaseWriter20readFromCurrentStateFzFCS_8DatabaseT_T_).
|
||||
- The definition of "current state" in DatabaseWriter.readFromCurrentState is [delicate](http://groue.github.io/GRDB.swift/docs/1.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 reusable agnostic code that has *both* queues and pools in mind. For example, GRDB uses those protocols for [migrations](#migrations) and [FetchedRecordsController](#fetchedrecordscontroller), two tools that accept both queues and pools.
|
||||
|
||||
|
||||
### Unsafe Concurrency APIs
|
||||
|
||||
**Database queues, pools, as well as their common protocols `DatabaseReader` and `DatabaseWriter` provide *unsafe* APIs.** Unsafe APIs lift [concurrency guarantees](#guarantees-and-rules), and allow advanced yet unsafe patterns.
|
||||
|
||||
- **`unsafeRead`**
|
||||
|
||||
The `unsafeRead` method is synchronous, and blocks the current thread until your database statements are executed in a protected dispatch queue. GRDB does just the bare minimum to provide a database connection that can read.
|
||||
|
||||
When used on a database pool, reads are no longer isolated:
|
||||
|
||||
```swift
|
||||
dbPool.unsafeRead { db in
|
||||
// Those two values may be different because some other thread
|
||||
// may have inserted or deleted a person between the two requests:
|
||||
let count1 = try Person.fetchCount(db)
|
||||
let count2 = try Person.fetchCount(db)
|
||||
}
|
||||
```
|
||||
|
||||
When used on a datase queue, the closure argument is allowed to write in the database.
|
||||
|
||||
- **`unsafeReentrantRead`**
|
||||
|
||||
The `unsafeReentrantRead` behaves just as `unsafeRead` (see above), and allows reentrant calls:
|
||||
|
||||
```swift
|
||||
dbPool.read { db1 in
|
||||
// No "Database methods are not reentrant" fatal error:
|
||||
dbPool.unsafeReentrantRead { db2 in
|
||||
dbPool.unsafeReentrantRead { db3 in
|
||||
...
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Reentrant database accesses make it very easy to break the second [safety rule](#guarantees-and-rules), which says: "group related statements within a single call to a DatabaseQueue or DatabasePool database access method.". Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring.
|
||||
|
||||
Reentrant methods have been introduced in order to support [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), a set of reactive extensions to GRDB based on [RxSwift](https://github.com/ReactiveX/RxSwift) that need precise scheduling.
|
||||
|
||||
- **`unsafeReentrantWrite`**
|
||||
|
||||
The `unsafeReentrantWrite` method is synchronous, and blocks the current thread until your database statements are executed in a protected dispatch queue. Writes are serialized: eventual concurrent database updates are postponed until the block has executed.
|
||||
|
||||
Reentrant calls are allowed:
|
||||
|
||||
```swift
|
||||
dbQueue.inDatabase { db1 in
|
||||
// No "Database methods are not reentrant" fatal error:
|
||||
dbQueue.unsafeReentrantWrite { db2 in
|
||||
dbQueue.unsafeReentrantWrite { db3 in
|
||||
...
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Reentrant database accesses make it very easy to break the second [safety rule](#guarantees-and-rules), which says: "group related statements within a single call to a DatabaseQueue or DatabasePool database access method.". Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring.
|
||||
|
||||
Reentrant methods have been introduced in order to support [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), a set of reactive extensions to GRDB based on [RxSwift](https://github.com/ReactiveX/RxSwift) that need precise scheduling.
|
||||
|
||||
|
||||
### Dealing with External Connections
|
||||
|
||||
The first rule of GRDB is:
|
||||
@@ -5426,7 +5582,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/1.0/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/1.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>1.0</string>
|
||||
<string>1.2</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
- [ ] REGEXP https://www.sqlite.org/lang_expr.html
|
||||
- [ ] CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END https://www.sqlite.org/lang_expr.html
|
||||
- [ ] See how we can use [sqlite3_get_autocommit](https://www.sqlite.org/capi3ref.html#sqlite3_get_autocommit)
|
||||
- [ ] ColumnDefinition.indexed()
|
||||
- [ ] Write regression tests for #156 and #157
|
||||
|
||||
Not sure
|
||||
|
||||
@@ -0,0 +1,671 @@
|
||||
import XCTest
|
||||
#if GRDBCIPHER
|
||||
import GRDBCipher
|
||||
#elseif GRDBCUSTOMSQLITE
|
||||
import GRDBCustomSQLite
|
||||
#else
|
||||
import GRDB
|
||||
#endif
|
||||
|
||||
private struct CustomValueType : DatabaseValueConvertible {
|
||||
var databaseValue: DatabaseValue {
|
||||
return "CustomValueType".databaseValue
|
||||
}
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> CustomValueType? {
|
||||
guard let string = String.fromDatabaseValue(dbValue), string == "CustomValueType" else {
|
||||
return nil
|
||||
}
|
||||
return CustomValueType()
|
||||
}
|
||||
}
|
||||
|
||||
class DatabaseAggregateTests: GRDBTestCase {
|
||||
|
||||
// MARK: - Return values
|
||||
|
||||
func testAggregateReturningNull() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ values: [DatabaseValue]) { }
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try DatabaseValue.fetchOne(db, "SELECT f()")!.isNull)
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateReturningInt64() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ values: [DatabaseValue]) { }
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return Int64(1)
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try Int64.fetchOne(db, "SELECT f()")!, Int64(1))
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateReturningDouble() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ values: [DatabaseValue]) { }
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return 1e100
|
||||
}
|
||||
}
|
||||
let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try Double.fetchOne(db, "SELECT f()")!, 1e100)
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateReturningString() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ values: [DatabaseValue]) { }
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return "foo"
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try String.fetchOne(db, "SELECT f()")!, "foo")
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateReturningData() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ values: [DatabaseValue]) { }
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return "foo".data(using: .utf8)
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try Data.fetchOne(db, "SELECT f()")!, "foo".data(using: .utf8))
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateReturningCustomValueType() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ values: [DatabaseValue]) { }
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return CustomValueType()
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try CustomValueType.fetchOne(db, "SELECT f()") != nil)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Argument values
|
||||
|
||||
func testAggregateArgumentNil() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = dbValues[0].isNull
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return result
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try Bool.fetchOne(db, "SELECT f(NULL)")!)
|
||||
XCTAssertFalse(try Bool.fetchOne(db, "SELECT f(1)")!)
|
||||
XCTAssertFalse(try Bool.fetchOne(db, "SELECT f(1.1)")!)
|
||||
XCTAssertFalse(try Bool.fetchOne(db, "SELECT f('foo')")!)
|
||||
XCTAssertFalse(try Bool.fetchOne(db, "SELECT f(?)", arguments: ["foo".data(using: .utf8)])!)
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateArgumentInt64() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = Int64.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return result
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try Int64.fetchOne(db, "SELECT f(NULL)") == nil)
|
||||
XCTAssertEqual(try Int64.fetchOne(db, "SELECT f(1)")!, 1)
|
||||
XCTAssertEqual(try Int64.fetchOne(db, "SELECT f(1.1)")!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateArgumentDouble() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = Double.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return result
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try Double.fetchOne(db, "SELECT f(NULL)") == nil)
|
||||
XCTAssertEqual(try Double.fetchOne(db, "SELECT f(1)")!, 1.0)
|
||||
XCTAssertEqual(try Double.fetchOne(db, "SELECT f(1.1)")!, 1.1)
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateArgumentString() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = String.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return result
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try String.fetchOne(db, "SELECT f(NULL)") == nil)
|
||||
XCTAssertEqual(try String.fetchOne(db, "SELECT f('foo')")!, "foo")
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateArgumentBlob() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = Data.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return result
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try Data.fetchOne(db, "SELECT f(NULL)") == nil)
|
||||
XCTAssertEqual(try Data.fetchOne(db, "SELECT f(?)", arguments: ["foo".data(using: .utf8)])!, "foo".data(using: .utf8))
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateArgumentCustomValueType() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = CustomValueType.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return result
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try CustomValueType.fetchOne(db, "SELECT f(NULL)") == nil)
|
||||
XCTAssertTrue(try CustomValueType.fetchOne(db, "SELECT f('CustomValueType')") != nil)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Argument count
|
||||
|
||||
func testAggregateWithoutArgument() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ dbValues: [DatabaseValue]) { }
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return "foo"
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try String.fetchOne(db, "SELECT f()")!, "foo")
|
||||
do {
|
||||
try db.execute("SELECT f(1)")
|
||||
XCTFail("Expected error")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message!, "wrong number of arguments to function f()")
|
||||
XCTAssertEqual(error.sql!, "SELECT f(1)")
|
||||
XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT f(1)`: wrong number of arguments to function f()")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateOfOneArgument() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = String.fromDatabaseValue(dbValues[0]).map { $0.uppercased() }
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return result
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try String.fetchOne(db, "SELECT upper(?)", arguments: ["Roué"])!, "ROUé")
|
||||
XCTAssertEqual(try String.fetchOne(db, "SELECT f(?)", arguments: ["Roué"])!, "ROUÉ")
|
||||
XCTAssertTrue(try String.fetchOne(db, "SELECT f(NULL)") == nil)
|
||||
do {
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected error")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message!, "wrong number of arguments to function f()")
|
||||
XCTAssertEqual(error.sql!, "SELECT f()")
|
||||
XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT f()`: wrong number of arguments to function f()")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateOfTwoArguments() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
let ints = dbValues.flatMap { Int.fromDatabaseValue($0) }
|
||||
result = ints.reduce(0, +)
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return result
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 2, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try Int.fetchOne(db, "SELECT f(1, 2)")!, 3)
|
||||
do {
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected error")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message!, "wrong number of arguments to function f()")
|
||||
XCTAssertEqual(error.sql!, "SELECT f()")
|
||||
XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT f()`: wrong number of arguments to function f()")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testVariadicFunction() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = dbValues.count
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return result
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try Int.fetchOne(db, "SELECT f()")!, 0)
|
||||
XCTAssertEqual(try Int.fetchOne(db, "SELECT f(1)")!, 1)
|
||||
XCTAssertEqual(try Int.fetchOne(db, "SELECT f(1, 1)")!, 2)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Step Errors
|
||||
|
||||
func testAggregateStepThrowingDatabaseErrorWithMessage() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ dbValues: [DatabaseValue]) throws {
|
||||
throw DatabaseError(message: "custom error message")
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message, "custom error message")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateStepThrowingDatabaseErrorWithCode() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ dbValues: [DatabaseValue]) throws {
|
||||
throw DatabaseError(resultCode: ResultCode(rawValue: 123))
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode.rawValue, 123)
|
||||
XCTAssertEqual(error.message, "unknown error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateStepThrowingDatabaseErrorWithMessageAndCode() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ dbValues: [DatabaseValue]) throws {
|
||||
throw DatabaseError(resultCode: ResultCode(rawValue: 123), message: "custom error message")
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode.rawValue, 123)
|
||||
XCTAssertEqual(error.message, "custom error message")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateStepThrowingCustomError() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ dbValues: [DatabaseValue]) throws {
|
||||
throw NSError(domain: "CustomErrorDomain", code: 123, userInfo: [NSString(string: NSLocalizedDescriptionKey): "custom error message"])
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertTrue(error.message!.contains("CustomErrorDomain"))
|
||||
XCTAssertTrue(error.message!.contains("123"))
|
||||
XCTAssertTrue(error.message!.contains("custom error message"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Result Errors
|
||||
|
||||
func testAggregateResultThrowingDatabaseErrorWithMessage() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ dbValues: [DatabaseValue]) { }
|
||||
func finalize() throws -> DatabaseValueConvertible? {
|
||||
throw DatabaseError(message: "custom error message")
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message, "custom error message")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateResultThrowingDatabaseErrorWithCode() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ dbValues: [DatabaseValue]) { }
|
||||
func finalize() throws -> DatabaseValueConvertible? {
|
||||
throw DatabaseError(resultCode: ResultCode(rawValue: 123))
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode.rawValue, 123)
|
||||
XCTAssertEqual(error.message, "unknown error")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateResultThrowingDatabaseErrorWithMessageAndCode() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ dbValues: [DatabaseValue]) { }
|
||||
func finalize() throws -> DatabaseValueConvertible? {
|
||||
throw DatabaseError(resultCode: ResultCode(rawValue: 123), message: "custom error message")
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode.rawValue, 123)
|
||||
XCTAssertEqual(error.message, "custom error message")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testAggregateResultThrowingCustomError() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ dbValues: [DatabaseValue]) { }
|
||||
func finalize() throws -> DatabaseValueConvertible? {
|
||||
throw NSError(domain: "CustomErrorDomain", code: 123, userInfo: [NSString(string: NSLocalizedDescriptionKey): "custom error message"])
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertTrue(error.message!.contains("CustomErrorDomain"))
|
||||
XCTAssertTrue(error.message!.contains("123"))
|
||||
XCTAssertTrue(error.message!.contains("custom error message"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Aggregation
|
||||
|
||||
func testAggregation() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
var sum: Int?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
sum = (sum ?? 0) + int
|
||||
}
|
||||
}
|
||||
func finalize() throws -> DatabaseValueConvertible? {
|
||||
return sum
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try Int.fetchOne(db, "SELECT f(a) FROM (SELECT 1 AS a UNION ALL SELECT 2 UNION ALL SELECT 3)")!, 6)
|
||||
}
|
||||
}
|
||||
|
||||
func testParallelAggregation() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
var sum: Int?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
sum = (sum ?? 0) + int
|
||||
}
|
||||
}
|
||||
func finalize() throws -> DatabaseValueConvertible? {
|
||||
return sum
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
let row = try Row.fetchOne(db, "SELECT f(a), f(b) FROM (SELECT 1 AS a, 2 AS b UNION ALL SELECT 2, 4 UNION ALL SELECT 3, 6)")!
|
||||
XCTAssertEqual(row.value(atIndex: 0), 6)
|
||||
XCTAssertEqual(row.value(atIndex: 1), 12)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Deallocation
|
||||
|
||||
func testDeallocationAfterSuccess() throws {
|
||||
final class Aggregate : DatabaseAggregate {
|
||||
static var onInit: (() -> ())?
|
||||
static var onDeinit: (() -> ())?
|
||||
init() { Aggregate.onInit?() }
|
||||
deinit { Aggregate.onDeinit?() }
|
||||
func step(_ dbValues: [DatabaseValue]) { }
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
var allocationCount = 0
|
||||
var aliveCount = 0
|
||||
Aggregate.onInit = {
|
||||
allocationCount += 1
|
||||
aliveCount += 1
|
||||
}
|
||||
Aggregate.onDeinit = {
|
||||
aliveCount -= 1
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(allocationCount, 0)
|
||||
XCTAssertEqual(aliveCount, 0)
|
||||
try db.execute("SELECT f()")
|
||||
XCTAssertEqual(allocationCount, 1)
|
||||
XCTAssertEqual(aliveCount, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func testDeallocationAfterStepError() throws {
|
||||
final class Aggregate : DatabaseAggregate {
|
||||
static var onInit: (() -> ())?
|
||||
static var onDeinit: (() -> ())?
|
||||
init() { Aggregate.onInit?() }
|
||||
deinit { Aggregate.onDeinit?() }
|
||||
func step(_ dbValues: [DatabaseValue]) throws {
|
||||
throw DatabaseError(message: "boo")
|
||||
}
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
fatalError()
|
||||
}
|
||||
}
|
||||
var allocationCount = 0
|
||||
var aliveCount = 0
|
||||
Aggregate.onInit = {
|
||||
allocationCount += 1
|
||||
aliveCount += 1
|
||||
}
|
||||
Aggregate.onDeinit = {
|
||||
aliveCount -= 1
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(allocationCount, 0)
|
||||
XCTAssertEqual(aliveCount, 0)
|
||||
_ = try? db.execute("SELECT f()")
|
||||
XCTAssertEqual(allocationCount, 1)
|
||||
XCTAssertEqual(aliveCount, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func testDeallocationAfterResultError() throws {
|
||||
final class Aggregate : DatabaseAggregate {
|
||||
static var onInit: (() -> ())?
|
||||
static var onDeinit: (() -> ())?
|
||||
init() { Aggregate.onInit?() }
|
||||
deinit { Aggregate.onDeinit?() }
|
||||
func step(_ dbValues: [DatabaseValue]) { }
|
||||
func finalize() throws -> DatabaseValueConvertible? {
|
||||
throw DatabaseError(message: "boo")
|
||||
}
|
||||
}
|
||||
|
||||
var allocationCount = 0
|
||||
var aliveCount = 0
|
||||
Aggregate.onInit = {
|
||||
allocationCount += 1
|
||||
aliveCount += 1
|
||||
}
|
||||
Aggregate.onDeinit = {
|
||||
aliveCount -= 1
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self)
|
||||
dbQueue.add(function: fn)
|
||||
dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(allocationCount, 0)
|
||||
XCTAssertEqual(aliveCount, 0)
|
||||
_ = try? db.execute("SELECT f()")
|
||||
XCTAssertEqual(allocationCount, 1)
|
||||
XCTAssertEqual(aliveCount, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import XCTest
|
||||
import GRDB
|
||||
#endif
|
||||
|
||||
struct CustomValueType : DatabaseValueConvertible {
|
||||
private struct CustomValueType : DatabaseValueConvertible {
|
||||
var databaseValue: DatabaseValue {
|
||||
return "CustomValueType".databaseValue
|
||||
}
|
||||
@@ -126,78 +126,78 @@ class DatabaseFunctionTests: GRDBTestCase {
|
||||
|
||||
func testFunctionArgumentNil() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("isNil", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
let fn = DatabaseFunction("f", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
return dbValues[0].isNull
|
||||
}
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try Bool.fetchOne(db, "SELECT isNil(NULL)")!)
|
||||
XCTAssertFalse(try Bool.fetchOne(db, "SELECT isNil(1)")!)
|
||||
XCTAssertFalse(try Bool.fetchOne(db, "SELECT isNil(1.1)")!)
|
||||
XCTAssertFalse(try Bool.fetchOne(db, "SELECT isNil('foo')")!)
|
||||
XCTAssertFalse(try Bool.fetchOne(db, "SELECT isNil(?)", arguments: ["foo".data(using: .utf8)])!)
|
||||
XCTAssertTrue(try Bool.fetchOne(db, "SELECT f(NULL)")!)
|
||||
XCTAssertFalse(try Bool.fetchOne(db, "SELECT f(1)")!)
|
||||
XCTAssertFalse(try Bool.fetchOne(db, "SELECT f(1.1)")!)
|
||||
XCTAssertFalse(try Bool.fetchOne(db, "SELECT f('foo')")!)
|
||||
XCTAssertFalse(try Bool.fetchOne(db, "SELECT f(?)", arguments: ["foo".data(using: .utf8)])!)
|
||||
}
|
||||
}
|
||||
|
||||
func testFunctionArgumentInt64() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("asInt64", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
let fn = DatabaseFunction("f", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
return Int64.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try Int64.fetchOne(db, "SELECT asInt64(NULL)") == nil)
|
||||
XCTAssertEqual(try Int64.fetchOne(db, "SELECT asInt64(1)")!, 1)
|
||||
XCTAssertEqual(try Int64.fetchOne(db, "SELECT asInt64(1.1)")!, 1)
|
||||
XCTAssertTrue(try Int64.fetchOne(db, "SELECT f(NULL)") == nil)
|
||||
XCTAssertEqual(try Int64.fetchOne(db, "SELECT f(1)")!, 1)
|
||||
XCTAssertEqual(try Int64.fetchOne(db, "SELECT f(1.1)")!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testFunctionArgumentDouble() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("asDouble", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
let fn = DatabaseFunction("f", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
return Double.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try Double.fetchOne(db, "SELECT asDouble(NULL)") == nil)
|
||||
XCTAssertEqual(try Double.fetchOne(db, "SELECT asDouble(1)")!, 1.0)
|
||||
XCTAssertEqual(try Double.fetchOne(db, "SELECT asDouble(1.1)")!, 1.1)
|
||||
XCTAssertTrue(try Double.fetchOne(db, "SELECT f(NULL)") == nil)
|
||||
XCTAssertEqual(try Double.fetchOne(db, "SELECT f(1)")!, 1.0)
|
||||
XCTAssertEqual(try Double.fetchOne(db, "SELECT f(1.1)")!, 1.1)
|
||||
}
|
||||
}
|
||||
|
||||
func testFunctionArgumentString() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("asString", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
let fn = DatabaseFunction("f", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
return String.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try String.fetchOne(db, "SELECT asString(NULL)") == nil)
|
||||
XCTAssertEqual(try String.fetchOne(db, "SELECT asString('foo')")!, "foo")
|
||||
XCTAssertTrue(try String.fetchOne(db, "SELECT f(NULL)") == nil)
|
||||
XCTAssertEqual(try String.fetchOne(db, "SELECT f('foo')")!, "foo")
|
||||
}
|
||||
}
|
||||
|
||||
func testFunctionArgumentBlob() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("asData", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
let fn = DatabaseFunction("f", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
return Data.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try Data.fetchOne(db, "SELECT asData(NULL)") == nil)
|
||||
XCTAssertEqual(try Data.fetchOne(db, "SELECT asData(?)", arguments: ["foo".data(using: .utf8)])!, "foo".data(using: .utf8))
|
||||
XCTAssertTrue(try Data.fetchOne(db, "SELECT f(NULL)") == nil)
|
||||
XCTAssertEqual(try Data.fetchOne(db, "SELECT f(?)", arguments: ["foo".data(using: .utf8)])!, "foo".data(using: .utf8))
|
||||
}
|
||||
}
|
||||
|
||||
func testFunctionArgumentCustomValueType() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("asCustomValueType", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
let fn = DatabaseFunction("f", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
return CustomValueType.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertTrue(try CustomValueType.fetchOne(db, "SELECT asCustomValueType(NULL)") == nil)
|
||||
XCTAssertTrue(try CustomValueType.fetchOne(db, "SELECT asCustomValueType('CustomValueType')") != nil)
|
||||
XCTAssertTrue(try CustomValueType.fetchOne(db, "SELECT f(NULL)") == nil)
|
||||
XCTAssertTrue(try CustomValueType.fetchOne(db, "SELECT f('CustomValueType')") != nil)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,23 +211,37 @@ class DatabaseFunctionTests: GRDBTestCase {
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try String.fetchOne(db, "SELECT f()")!, "foo")
|
||||
do {
|
||||
try db.execute("SELECT f(1)")
|
||||
XCTFail("Expected error")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message!, "wrong number of arguments to function f()")
|
||||
XCTAssertEqual(error.sql!, "SELECT f(1)")
|
||||
XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT f(1)`: wrong number of arguments to function f()")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testFunctionOfOneArgument() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("unicodeUpper", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
let dbValue = dbValues[0]
|
||||
guard let string = String.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
return string.uppercased()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1) { (dbValues: [DatabaseValue]) in
|
||||
String.fromDatabaseValue(dbValues[0]).map { $0.uppercased() }
|
||||
}
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try String.fetchOne(db, "SELECT upper(?)", arguments: ["Roué"])!, "ROUé")
|
||||
XCTAssertEqual(try String.fetchOne(db, "SELECT unicodeUpper(?)", arguments: ["Roué"])!, "ROUÉ")
|
||||
XCTAssertTrue(try String.fetchOne(db, "SELECT unicodeUpper(NULL)") == nil)
|
||||
XCTAssertEqual(try String.fetchOne(db, "SELECT f(?)", arguments: ["Roué"])!, "ROUÉ")
|
||||
XCTAssertTrue(try String.fetchOne(db, "SELECT f(NULL)") == nil)
|
||||
do {
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected error")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message!, "wrong number of arguments to function f()")
|
||||
XCTAssertEqual(error.sql!, "SELECT f()")
|
||||
XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT f()`: wrong number of arguments to function f()")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,6 +254,15 @@ class DatabaseFunctionTests: GRDBTestCase {
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
XCTAssertEqual(try Int.fetchOne(db, "SELECT f(1, 2)")!, 3)
|
||||
do {
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected error")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message!, "wrong number of arguments to function f()")
|
||||
XCTAssertEqual(error.sql!, "SELECT f()")
|
||||
XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT f()`: wrong number of arguments to function f()")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -260,14 +283,13 @@ class DatabaseFunctionTests: GRDBTestCase {
|
||||
|
||||
func testFunctionThrowingDatabaseErrorWithMessage() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1) { dbValues in
|
||||
let fn = DatabaseFunction("f") { dbValues in
|
||||
throw DatabaseError(message: "custom error message")
|
||||
}
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute("CREATE TABLE items (value INT)")
|
||||
try db.execute("INSERT INTO items VALUES (f(1))")
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
@@ -278,14 +300,13 @@ class DatabaseFunctionTests: GRDBTestCase {
|
||||
|
||||
func testFunctionThrowingDatabaseErrorWithCode() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1) { dbValues in
|
||||
let fn = DatabaseFunction("f") { dbValues in
|
||||
throw DatabaseError(resultCode: ResultCode(rawValue: 123))
|
||||
}
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute("CREATE TABLE items (value INT)")
|
||||
try db.execute("INSERT INTO items VALUES (f(1))")
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode.rawValue, 123)
|
||||
@@ -296,14 +317,13 @@ class DatabaseFunctionTests: GRDBTestCase {
|
||||
|
||||
func testFunctionThrowingDatabaseErrorWithMessageAndCode() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1) { dbValues in
|
||||
let fn = DatabaseFunction("f") { dbValues in
|
||||
throw DatabaseError(resultCode: ResultCode(rawValue: 123), message: "custom error message")
|
||||
}
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute("CREATE TABLE items (value INT)")
|
||||
try db.execute("INSERT INTO items VALUES (f(1))")
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode.rawValue, 123)
|
||||
@@ -314,14 +334,13 @@ class DatabaseFunctionTests: GRDBTestCase {
|
||||
|
||||
func testFunctionThrowingCustomError() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let fn = DatabaseFunction("f", argumentCount: 1) { dbValues in
|
||||
let fn = DatabaseFunction("f") { dbValues in
|
||||
throw NSError(domain: "CustomErrorDomain", code: 123, userInfo: [NSString(string: NSLocalizedDescriptionKey): "custom error message"])
|
||||
}
|
||||
dbQueue.add(function: fn)
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
try db.execute("CREATE TABLE items (value INT)")
|
||||
try db.execute("INSERT INTO items VALUES (f(1))")
|
||||
try db.execute("SELECT f()")
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
|
||||
@@ -44,4 +44,28 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
} catch let error as DatabaseError where error.resultCode == .SQLITE_READONLY {
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabaseQueueUnsafeReentrantRead() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.unsafeReentrantRead { db1 in
|
||||
try dbQueue.unsafeReentrantRead { db2 in
|
||||
try dbQueue.unsafeReentrantRead { db3 in
|
||||
XCTAssertTrue(db1 === db2)
|
||||
XCTAssertTrue(db2 === db3)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testDatabasePoolUnsafeReentrantRead() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.unsafeReentrantRead { db1 in
|
||||
try dbPool.unsafeReentrantRead { db2 in
|
||||
try dbPool.unsafeReentrantRead { db3 in
|
||||
XCTAssertTrue(db1 === db2)
|
||||
XCTAssertTrue(db2 === db3)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,14 +11,17 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
|
||||
func testDatabaseQueueUnsafeReentrantWrite() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.unsafeReentrantWrite { db in
|
||||
try db.create(table: "table1") { t in
|
||||
try dbQueue.unsafeReentrantWrite { db1 in
|
||||
try db1.create(table: "table1") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
}
|
||||
try dbQueue.unsafeReentrantWrite { db in
|
||||
try db.execute("INSERT INTO table1 (id) VALUES (NULL)")
|
||||
try dbQueue.unsafeReentrantWrite { db in
|
||||
try XCTAssertEqual(Int.fetchOne(db, "SELECT * FROM table1"), 1)
|
||||
try dbQueue.unsafeReentrantWrite { db2 in
|
||||
try db2.execute("INSERT INTO table1 (id) VALUES (NULL)")
|
||||
|
||||
try dbQueue.unsafeReentrantWrite { db3 in
|
||||
try XCTAssertEqual(Int.fetchOne(db3, "SELECT * FROM table1"), 1)
|
||||
XCTAssertTrue(db1 === db2)
|
||||
XCTAssertTrue(db2 === db3)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,14 +29,17 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
|
||||
func testDatabasePoolUnsafeReentrantWrite() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
try dbPool.unsafeReentrantWrite { db in
|
||||
try db.create(table: "table1") { t in
|
||||
try dbPool.unsafeReentrantWrite { db1 in
|
||||
try db1.create(table: "table1") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
}
|
||||
try dbPool.unsafeReentrantWrite { db in
|
||||
try db.execute("INSERT INTO table1 (id) VALUES (NULL)")
|
||||
try dbPool.unsafeReentrantWrite { db in
|
||||
try XCTAssertEqual(Int.fetchOne(db, "SELECT * FROM table1"), 1)
|
||||
try dbPool.unsafeReentrantWrite { db2 in
|
||||
try db2.execute("INSERT INTO table1 (id) VALUES (NULL)")
|
||||
|
||||
try dbPool.unsafeReentrantWrite { db3 in
|
||||
try XCTAssertEqual(Int.fetchOne(db3, "SELECT * FROM table1"), 1)
|
||||
XCTAssertTrue(db1 === db2)
|
||||
XCTAssertTrue(db2 === db3)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,6 +128,26 @@ class GRDBTestCase: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
|
||||
func assertEqualSQL(_ lhs: String, _ rhs: String, file: StaticString = #file, line: UInt = #line) {
|
||||
// Trim white space and ";"
|
||||
let cs = CharacterSet.whitespacesAndNewlines.union(CharacterSet(charactersIn: ";"))
|
||||
XCTAssertEqual(lhs.trimmingCharacters(in: cs), rhs.trimmingCharacters(in: cs), file: file, line: line)
|
||||
}
|
||||
|
||||
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
|
||||
func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
|
||||
_ = try Row.fetchOne(db, request)
|
||||
assertEqualSQL(lastSQLQuery, sql, file: file, line: line)
|
||||
}
|
||||
|
||||
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
|
||||
func assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
|
||||
try databaseReader.unsafeRead { db in
|
||||
try assertEqualSQL(db, request, sql, file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
func sql(_ databaseReader: DatabaseReader, _ request: Request) -> String {
|
||||
return try! databaseReader.unsafeRead { db in
|
||||
_ = try Row.fetchOne(db, request)
|
||||
|
||||
@@ -620,4 +620,77 @@ class MutablePersistableTests: GRDBTestCase {
|
||||
XCTAssertEqual(existsCount, 2)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Misc
|
||||
|
||||
func testPartiallyEncodedRecord() throws {
|
||||
struct PartialRecord : MutablePersistable {
|
||||
var id: Int64?
|
||||
var a: String
|
||||
|
||||
static let databaseTableName = "records"
|
||||
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container["id"] = id
|
||||
container["a"] = a
|
||||
}
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
}
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "records") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("a", .text)
|
||||
t.column("b", .text)
|
||||
t.column("c", .integer).notNull().defaults(to: 123)
|
||||
}
|
||||
|
||||
// Insertion only inserts defined columns
|
||||
var record = PartialRecord(id: nil, a: "foo")
|
||||
try record.insert(db)
|
||||
XCTAssertTrue(
|
||||
["INSERT INTO \"records\" (\"id\", \"a\") VALUES (NULL,'foo')",
|
||||
"INSERT INTO \"records\" (\"a\", \"id\") VALUES ('foo',NULL)"]
|
||||
.contains(lastSQLQuery))
|
||||
XCTAssertEqual(try Row.fetchOne(db, "SELECT * FROM records")!, ["id": 1, "a": "foo", "b": nil, "c": 123])
|
||||
|
||||
// Update only updates defined columns
|
||||
record.a = "bar"
|
||||
try record.update(db)
|
||||
XCTAssertEqual(lastSQLQuery, "UPDATE \"records\" SET \"a\"='bar' WHERE \"id\"=1")
|
||||
XCTAssertEqual(try Row.fetchOne(db, "SELECT * FROM records")!, ["id": 1, "a": "bar", "b": nil, "c": 123])
|
||||
|
||||
// Update always update something
|
||||
record.a = "baz"
|
||||
try record.update(db, columns: ["b"])
|
||||
XCTAssertEqual(lastSQLQuery, "UPDATE \"records\" SET \"id\"=1 WHERE \"id\"=1")
|
||||
XCTAssertEqual(try Row.fetchOne(db, "SELECT * FROM records")!, ["id": 1, "a": "bar", "b": nil, "c": 123])
|
||||
|
||||
// Deletion
|
||||
try record.delete(db)
|
||||
XCTAssertEqual(lastSQLQuery, "DELETE FROM \"records\" WHERE \"id\"=1")
|
||||
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM records")!, 0)
|
||||
|
||||
// Expect database errors when missing columns must have a value
|
||||
try db.drop(table: "records")
|
||||
try db.create(table: "records") { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("a", .text)
|
||||
t.column("b", .text).notNull()
|
||||
}
|
||||
do {
|
||||
try record.insert(db)
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_CONSTRAINT)
|
||||
// actual error message depends on the SQLite version
|
||||
XCTAssertTrue(
|
||||
["NOT NULL constraint failed: records.b",
|
||||
"records.b may not be NULL"].contains(error.message!))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,9 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("name", .text)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"id\" INTEGER PRIMARY KEY, " +
|
||||
"\"name\" TEXT" +
|
||||
@@ -33,8 +34,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(table: "test", temporary: true, ifNotExists: true, withoutRowID: true) { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (" +
|
||||
"\"id\" INTEGER PRIMARY KEY" +
|
||||
") WITHOUT ROWID") as String)
|
||||
@@ -42,8 +43,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(table: "test", temporary: true, ifNotExists: true) { t in
|
||||
t.column("id", .integer).primaryKey()
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TEMPORARY TABLE IF NOT EXISTS \"test\" (" +
|
||||
"\"id\" INTEGER PRIMARY KEY" +
|
||||
")") as String)
|
||||
@@ -51,14 +52,27 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testUntypedColumn() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
// Simple table creation
|
||||
try db.create(table: "test") { t in
|
||||
t.column("a")
|
||||
t.column("b")
|
||||
}
|
||||
|
||||
assertEqualSQL(lastSQLQuery, "CREATE TABLE \"test\" (\"a\", \"b\")")
|
||||
}
|
||||
}
|
||||
|
||||
func testColumnPrimaryKeyOptions() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.create(table: "test") { t in
|
||||
t.column("id", .integer).primaryKey(onConflict: .fail)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"id\" INTEGER PRIMARY KEY ON CONFLICT FAIL" +
|
||||
")") as String)
|
||||
@@ -68,8 +82,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(table: "test") { t in
|
||||
t.column("id", .integer).primaryKey(autoincrement: true)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"id\" INTEGER PRIMARY KEY AUTOINCREMENT" +
|
||||
")") as String)
|
||||
@@ -88,8 +102,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("e", .integer).notNull(onConflict: .ignore)
|
||||
t.column("f", .integer).notNull(onConflict: .replace)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" INTEGER NOT NULL, " +
|
||||
"\"b\" INTEGER NOT NULL, " +
|
||||
@@ -101,6 +115,20 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testColumnIndexed() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
sqlQueries.removeAll()
|
||||
try db.create(table: "test") { t in
|
||||
t.column("a", .integer).indexed()
|
||||
t.column("b", .integer).indexed()
|
||||
}
|
||||
assertEqualSQL(sqlQueries[0], "CREATE TABLE \"test\" (\"a\" INTEGER, \"b\" INTEGER)")
|
||||
assertEqualSQL(sqlQueries[1], "CREATE INDEX \"test_on_a\" ON \"test\"(\"a\")")
|
||||
assertEqualSQL(sqlQueries[2], "CREATE INDEX \"test_on_b\" ON \"test\"(\"b\")")
|
||||
}
|
||||
}
|
||||
|
||||
func testColumnUnique() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
@@ -112,8 +140,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("e", .integer).unique(onConflict: .ignore)
|
||||
t.column("f", .integer).unique(onConflict: .replace)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" INTEGER UNIQUE, " +
|
||||
"\"b\" INTEGER UNIQUE, " +
|
||||
@@ -133,8 +161,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("b", .integer).check(sql: "b <> 2")
|
||||
t.column("c", .integer).check { $0 > 0 }.check { $0 < 10 }
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" INTEGER CHECK ((\"a\" > 0)), " +
|
||||
"\"b\" INTEGER CHECK (b <> 2), " +
|
||||
@@ -161,8 +189,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("d", .integer).defaults(to: "foo".data(using: .utf8)!)
|
||||
t.column("e", .integer).defaults(sql: "NULL")
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" INTEGER DEFAULT 1, " +
|
||||
"\"b\" INTEGER DEFAULT 1.0, " +
|
||||
@@ -184,8 +212,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(table: "test") { t in
|
||||
t.column("name", .text).collate(.nocase)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"name\" TEXT COLLATE NOCASE" +
|
||||
")") as String)
|
||||
@@ -198,8 +226,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(table: "test") { t in
|
||||
t.column("name", .text).collate(collation)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"name\" TEXT COLLATE foo" +
|
||||
")") as String)
|
||||
@@ -214,17 +242,22 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("name", .text).primaryKey()
|
||||
t.column("email", .text).unique()
|
||||
}
|
||||
try db.create(table: "pkless") { t in
|
||||
t.column("email", .text)
|
||||
}
|
||||
try db.create(table: "child") { t in
|
||||
t.column("parentName", .text).references("parent", onDelete: .cascade, onUpdate: .cascade)
|
||||
t.column("parentEmail", .text).references("parent", column: "email", onDelete: .restrict, deferred: true)
|
||||
t.column("weird", .text).references("parent", column: "name").references("parent", column: "email")
|
||||
t.column("pklessRowId", .text).references("pkless")
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"child\" (" +
|
||||
"\"parentName\" TEXT REFERENCES \"parent\"(\"name\") ON DELETE CASCADE ON UPDATE CASCADE, " +
|
||||
"\"parentEmail\" TEXT REFERENCES \"parent\"(\"email\") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED, " +
|
||||
"\"weird\" TEXT REFERENCES \"parent\"(\"name\") REFERENCES \"parent\"(\"email\")" +
|
||||
"\"weird\" TEXT REFERENCES \"parent\"(\"name\") REFERENCES \"parent\"(\"email\"), " +
|
||||
"\"pklessRowId\" TEXT REFERENCES \"pkless\"(\"rowid\")" +
|
||||
")") as String)
|
||||
}
|
||||
}
|
||||
@@ -237,8 +270,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("a", .text)
|
||||
t.column("b", .text)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" TEXT, " +
|
||||
"\"b\" TEXT, " +
|
||||
@@ -252,8 +285,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("a", .text)
|
||||
t.column("b", .text)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" TEXT, " +
|
||||
"\"b\" TEXT, " +
|
||||
@@ -273,8 +306,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("b", .text)
|
||||
t.column("c", .text)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" TEXT, " +
|
||||
"\"b\" TEXT, " +
|
||||
@@ -300,8 +333,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("d", .text)
|
||||
t.column("e", .text)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"child\" (" +
|
||||
"\"c\" TEXT, " +
|
||||
"\"d\" TEXT, " +
|
||||
@@ -321,8 +354,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("a", .integer)
|
||||
t.column("b", .integer)
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test\" (" +
|
||||
"\"a\" INTEGER, " +
|
||||
"\"b\" INTEGER, " +
|
||||
@@ -347,8 +380,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("id", .integer).primaryKey()
|
||||
t.column("id2", .integer).references("test1")
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test1\" (" +
|
||||
"\"id\" INTEGER PRIMARY KEY, " +
|
||||
"\"id2\" INTEGER REFERENCES \"test1\"(\"id\")" +
|
||||
@@ -359,8 +392,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.column("id2", .integer).references("test2")
|
||||
t.primaryKey(["id"])
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test2\" (" +
|
||||
"\"id\" INTEGER, " +
|
||||
"\"id2\" INTEGER REFERENCES \"test2\"(\"id\"), " +
|
||||
@@ -375,8 +408,8 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
t.foreignKey(["c", "d"], references: "test3")
|
||||
t.primaryKey(["a", "b"])
|
||||
}
|
||||
XCTAssertEqual(
|
||||
self.lastSQLQuery,
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test3\" (" +
|
||||
"\"a\" INTEGER, " +
|
||||
"\"b\" INTEGER, " +
|
||||
@@ -385,6 +418,15 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
"PRIMARY KEY (\"a\", \"b\"), " +
|
||||
"FOREIGN KEY (\"c\", \"d\") REFERENCES \"test3\"(\"a\", \"b\")" +
|
||||
")") as String)
|
||||
|
||||
try db.create(table: "test4") { t in
|
||||
t.column("parent", .integer).references("test4")
|
||||
}
|
||||
assertEqualSQL(
|
||||
lastSQLQuery,
|
||||
("CREATE TABLE \"test4\" (" +
|
||||
"\"parent\" INTEGER REFERENCES \"test4\"(\"rowid\")" +
|
||||
")") as String)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -398,7 +440,7 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
XCTAssertEqual(try db.columnCount(in: "test"), 1)
|
||||
|
||||
try db.rename(table: "test", to: "foo")
|
||||
XCTAssertEqual(self.lastSQLQuery, "ALTER TABLE \"test\" RENAME TO \"foo\"")
|
||||
assertEqualSQL(lastSQLQuery, "ALTER TABLE \"test\" RENAME TO \"foo\"")
|
||||
XCTAssertFalse(try db.tableExists("test"))
|
||||
XCTAssertTrue(try db.tableExists("foo"))
|
||||
XCTAssertEqual(try db.columnCount(in: "foo"), 1)
|
||||
@@ -411,15 +453,20 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(table: "test") { t in
|
||||
t.column("a", .text)
|
||||
}
|
||||
try db.create(table: "alt") { t in
|
||||
t.column("a", .text)
|
||||
}
|
||||
|
||||
self.sqlQueries.removeAll()
|
||||
sqlQueries.removeAll()
|
||||
try db.alter(table: "test") { t in
|
||||
t.add(column: "b", .text)
|
||||
t.add(column: "c", .integer).notNull().defaults(to: 1)
|
||||
t.add(column: "d", .text).references("alt")
|
||||
}
|
||||
|
||||
XCTAssertEqual(self.sqlQueries[0], "ALTER TABLE \"test\" ADD COLUMN \"b\" TEXT;")
|
||||
XCTAssertEqual(self.sqlQueries[1], " ALTER TABLE \"test\" ADD COLUMN \"c\" INTEGER NOT NULL DEFAULT 1")
|
||||
assertEqualSQL(sqlQueries[sqlQueries.count - 3], "ALTER TABLE \"test\" ADD COLUMN \"b\" TEXT")
|
||||
assertEqualSQL(sqlQueries[sqlQueries.count - 2], "ALTER TABLE \"test\" ADD COLUMN \"c\" INTEGER NOT NULL DEFAULT 1")
|
||||
assertEqualSQL(sqlQueries[sqlQueries.count - 1], "ALTER TABLE \"test\" ADD COLUMN \"d\" TEXT REFERENCES \"alt\"(\"rowid\")")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,7 +481,7 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
XCTAssertEqual(try db.columnCount(in: "test"), 2)
|
||||
|
||||
try db.drop(table: "test")
|
||||
XCTAssertEqual(self.lastSQLQuery, "DROP TABLE \"test\"")
|
||||
assertEqualSQL(lastSQLQuery, "DROP TABLE \"test\"")
|
||||
XCTAssertFalse(try db.tableExists("test"))
|
||||
}
|
||||
}
|
||||
@@ -449,10 +496,10 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
try db.create(index: "test_on_a", on: "test", columns: ["a"])
|
||||
XCTAssertEqual(self.lastSQLQuery, "CREATE INDEX \"test_on_a\" ON \"test\"(\"a\")")
|
||||
assertEqualSQL(lastSQLQuery, "CREATE INDEX \"test_on_a\" ON \"test\"(\"a\")")
|
||||
|
||||
try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], unique: true, ifNotExists: true)
|
||||
XCTAssertEqual(self.lastSQLQuery, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\")")
|
||||
assertEqualSQL(lastSQLQuery, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\")")
|
||||
|
||||
// Sanity check
|
||||
XCTAssertEqual(try Set(db.indexes(on: "test").map { $0.name }), ["test_on_a", "test_on_a_b"])
|
||||
@@ -475,7 +522,7 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], unique: true, ifNotExists: true, condition: Column("a") == 1)
|
||||
XCTAssertEqual(self.lastSQLQuery, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\") WHERE (\"a\" = 1)")
|
||||
assertEqualSQL(lastSQLQuery, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\") WHERE (\"a\" = 1)")
|
||||
|
||||
// Sanity check
|
||||
XCTAssertEqual(try Set(db.indexes(on: "test").map { $0.name }), ["test_on_a_b"])
|
||||
@@ -492,7 +539,7 @@ class TableDefinitionTests: GRDBTestCase {
|
||||
try db.create(index: "test_on_name", on: "test", columns: ["name"])
|
||||
|
||||
try db.drop(index: "test_on_name")
|
||||
XCTAssertEqual(self.lastSQLQuery, "DROP INDEX \"test_on_name\"")
|
||||
assertEqualSQL(lastSQLQuery, "DROP INDEX \"test_on_name\"")
|
||||
|
||||
// Sanity check
|
||||
XCTAssertTrue(try db.indexes(on: "test").isEmpty)
|
||||
|
||||
@@ -9,6 +9,7 @@ import XCTest
|
||||
|
||||
class TableMappingTests: GRDBTestCase {
|
||||
|
||||
// Test deprecated method primaryKeyRowComparator
|
||||
func testPrimaryKeyRowComparatorWithIntegerPrimaryKey() throws {
|
||||
struct Person : TableMapping {
|
||||
static let databaseTableName = "persons"
|
||||
@@ -32,6 +33,7 @@ class TableMappingTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// Test deprecated method primaryKeyRowComparator
|
||||
func testPrimaryKeyRowComparatorWithHiddenRowIDPrimaryKey() throws {
|
||||
struct Person : TableMapping {
|
||||
static let databaseTableName = "persons"
|
||||
|
||||
@@ -37,6 +37,14 @@ class UpdateStatementTests : GRDBTestCase {
|
||||
XCTAssertEqual(names, ["Arthur", "Barbara", "Craig", "Daniel"])
|
||||
}
|
||||
}
|
||||
|
||||
func testStatementSQL() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try XCTAssertEqual(db.makeUpdateStatement("INSERT INTO persons (name, age) VALUES ('Arthur', ?)").sql, "INSERT INTO persons (name, age) VALUES ('Arthur', ?)")
|
||||
try XCTAssertEqual(db.makeUpdateStatement(" INSERT INTO persons (name, age) VALUES ('Arthur', ?) ; ").sql, "INSERT INTO persons (name, age) VALUES ('Arthur', ?)")
|
||||
}
|
||||
}
|
||||
|
||||
func testArrayStatementArguments() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
@@ -269,7 +277,7 @@ class UpdateStatementTests : GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testMultipleValidStatementsError() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
|
||||
Reference in new issue
Block a user