Refactor ValueObservation tests around a common pattern

This commit is contained in:
Gwendal Roué committed 2020-03-22 13:31:05 +01:00
1 parent 98d381ed67
commit 7a583e02e8
9 files changed
+436 -850

No files matched your search

@@ -12,55 +12,30 @@ import XCTest
class ValueObservationCountTests: GRDBTestCase {
func testCount() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.RemoveDuplicates<ValueReducers.Fetch<Int>>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1
try db.execute(sql: "UPDATE t SET id = id") // =
try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1
try db.inTransaction { // +1
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "DELETE FROM t WHERE id = 1")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 2") // -1
}
let expectedValues = [0, 1, 2, 3, 2]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
struct T: TableRecord { }
let observations = [
T.all().observationForCount(),
T.observationForCount()]
for var observation in observations {
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
for observation in observations {
try assertValueObservation(
observation,
records: [0, 1, 2, 3, 2],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "UPDATE t SET id = id")
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
try db.inTransaction {
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "DELETE FROM t WHERE id = 1")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 2")
})
}
}
}
@@ -27,62 +27,44 @@ private struct Name: DatabaseValueConvertible, Equatable {
class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase {
func testAll() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.AllValues<SQLRequest<Name>.RowDecoder>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
try assertValueObservation(
SQLRequest<Name>(sql: "SELECT name FROM t ORDER BY id").observationForAll(),
records: [
[],
[Name(rawValue: "foo")],
[Name(rawValue: "foo"), Name(rawValue: "bar")],
[Name(rawValue: "bar")]],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1")
try db.inTransaction {
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1
}
let expectedValues = [
[],
["foo"],
["foo", "bar"],
["bar"]]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values.map { $0.map(\.rawValue) },
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = SQLRequest<Name>(sql: "SELECT name FROM t ORDER BY id").observationForAll()
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
try db.execute(sql: "DELETE FROM t WHERE id = 1")
})
}
func testOne() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.OneValue<SQLRequest<Name>.RowDecoder>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try assertValueObservation(
SQLRequest<Name>(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst(),
records: [
nil,
Name(rawValue: "foo"),
Name(rawValue: "bar"),
nil,
Name(rawValue: "baz"),
nil,
Name(rawValue: "qux")],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1")
try db.inTransaction {
@@ -97,100 +79,48 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase {
try db.execute(sql: "DELETE FROM t")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, NULL)")
try db.execute(sql: "UPDATE t SET name = 'qux'")
}
let expectedValues = [
nil,
"foo",
"bar",
nil,
"baz",
nil,
"qux"]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values.map { $0.map(\.rawValue) },
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = SQLRequest<Name>(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst()
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
})
}
func testAllOptional() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.AllOptionalValues<Name>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
try assertValueObservation(
SQLRequest<Name?>(sql: "SELECT name FROM t ORDER BY id").observationForAll(),
records: [
[],
[Name(rawValue: "foo")],
[Name(rawValue: "foo"), nil],
[nil]],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1")
try db.inTransaction {
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, NULL)")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1
}
let expectedValues = [
[],
["foo"],
["foo", nil],
[nil]]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values.map { $0.map { $0?.rawValue }},
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = SQLRequest<Name?>(sql: "SELECT name FROM t ORDER BY id").observationForAll()
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
try db.execute(sql: "DELETE FROM t WHERE id = 1")
})
}
func testOneOptional() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.OneValue<Name>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try assertValueObservation(
SQLRequest<Name?>(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst(),
records: [
nil,
Name(rawValue: "foo"),
Name(rawValue: "bar"),
nil,
Name(rawValue: "baz"),
nil,
Name(rawValue: "qux")],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1")
try db.inTransaction {
@@ -205,41 +135,7 @@ class ValueObservationDatabaseValueConvertibleTests: GRDBTestCase {
try db.execute(sql: "DELETE FROM t")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, NULL)")
try db.execute(sql: "UPDATE t SET name = 'qux'")
}
let expectedValues = [
nil,
"foo",
"bar",
nil,
"baz",
nil,
"qux"]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values.map { $0.map(\.rawValue)},
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = SQLRequest<Name?>(sql: "SELECT name FROM t ORDER BY id DESC").observationForFirst()
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
})
}
func testViewOptimization() throws {
@@ -21,86 +21,34 @@ class ValueObservationFetchTests: GRDBTestCase {
}
func testFetch() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.Fetch<Int>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try assertValueObservation(
ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: {
try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")!
}),
records: [0, 1, 1, 2],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "UPDATE t SET id = id")
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
let expectedValues = [0, 1, 1, 2]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: {
try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")!
})
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
})
}
func testRemoveDuplicated() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.RemoveDuplicates<ValueReducers.Fetch<Int>>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try assertValueObservation(
ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: {
try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")!
}).removeDuplicates(),
records: [0, 1, 2],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "UPDATE t SET id = id")
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
let expectedValues = [0, 1, 2]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: {
try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")!
}).removeDuplicates()
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
})
}
}
+14 -39
View File
@@ -12,47 +12,22 @@ import XCTest
class ValueObservationMapTests: GRDBTestCase {
func testMap() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.Map<ValueReducers.Fetch<Int>, String>>) throws {
// We need something to change
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
let valueObservation = ValueObservation
.tracking(DatabaseRegion.fullDatabase, fetch: {
try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")!
})
.map { "\($0)" }
try assertValueObservation(
valueObservation,
records: ["0", "1", "2"],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
let expectedValues = ["0", "1", "2"]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = ValueObservation
.tracking(DatabaseRegion.fullDatabase, fetch: {
try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")!
})
.map { "\($0)" }
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
})
}
func testMapPreservesConfiguration() {
@@ -28,29 +28,28 @@ private struct ParentInfo: FetchableRecord, Decodable, Equatable {
}
class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent", onDelete: .cascade)
t.column("name", .text)
}
try db.execute(sql: """
private func setup(_ db: Database) throws {
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent", onDelete: .cascade)
t.column("name", .text)
}
try db.execute(sql: """
INSERT INTO parent (id, name) VALUES (1, 'foo');
INSERT INTO parent (id, name) VALUES (2, 'bar');
INSERT INTO child (id, parentId, name) VALUES (1, 1, 'fooA');
INSERT INTO child (id, parentId, name) VALUES (2, 1, 'fooB');
INSERT INTO child (id, parentId, name) VALUES (3, 2, 'barA');
""")
}
}
func testOneRowWithPrefetchedRows() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write(setup)
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
@@ -74,6 +73,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
func testAllRowsWithPrefetchedRows() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write(setup)
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
@@ -103,13 +103,14 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
}
func testOneRecordWithPrefetchedRows() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.OneRecord<QueryInterfaceRequest<ParentInfo>.RowDecoder>>) throws {
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try db.execute(sql: "DELETE FROM child")
}
let expectedValues = [
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: ParentInfo.self)
try assertValueObservation(
request.observationForFirst(),
records: [
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: [
@@ -119,45 +120,22 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
ParentInfo(
parent: Parent(id: 1, name: "foo"),
children: []),
]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: ParentInfo.self)
var observation = request.observationForFirst()
observation.scheduling = scheduling
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
],
setup: setup,
recordedUpdates: { db in
try db.execute(sql: "DELETE FROM child")
})
}
func testAllRecordsWithPrefetchedRows() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.AllRecords<QueryInterfaceRequest<ParentInfo>.RowDecoder>>) throws {
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try db.execute(sql: "DELETE FROM child")
}
let expectedValues = [
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: ParentInfo.self)
try assertValueObservation(
request.observationForAll(),
records: [
[
ParentInfo(
parent: Parent(id: 1, name: "foo"),
@@ -179,34 +157,10 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
parent: Parent(id: 2, name: "bar"),
children: []),
],
]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
let request = Parent
.including(all: Parent.children.orderByPrimaryKey())
.orderByPrimaryKey()
.asRequest(of: ParentInfo.self)
var observation = request.observationForAll()
observation.scheduling = scheduling
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
],
setup: setup,
recordedUpdates: { db in
try db.execute(sql: "DELETE FROM child")
})
}
}
@@ -13,151 +13,73 @@ import GRDB
class ValueObservationReadonlyTests: GRDBTestCase {
func testReadOnlyObservation() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.Fetch<Int>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction {
try $0.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
let expectedValues = [0, 1]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: {
try assertValueObservation(
ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: {
try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")!
})
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
}),
records: [0, 1],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
})
}
func testWriteObservationFailsByDefaultWithErrorHandling() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.Fetch<Int>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
let recorder = observation.record(in: writer)
let (values, error) = try wait(for: recorder.failure(), timeout: 0.5)
XCTAssert(values.isEmpty)
do {
throw error
} catch let error as DatabaseError {
try assertValueObservation(
ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
return 0
}),
fails: { (error: DatabaseError, _: DatabaseWriter) in
XCTAssertEqual(error.resultCode, .SQLITE_READONLY)
XCTAssertEqual(error.message, "attempt to write a readonly database")
XCTAssertEqual(error.sql!, "INSERT INTO t DEFAULT VALUES")
XCTAssertEqual(error.description, "SQLite error 8 with statement `INSERT INTO t DEFAULT VALUES`: attempt to write a readonly database")
}
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
return 0
})
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
},
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
})
}
func testWriteObservation() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.Fetch<Int>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction {
try $0.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
let expectedValues = [0, 1]
let values = try wait(for: recorder.next(2), timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in
XCTAssert(db.isInsideTransaction, "expected a wrapping transaction")
try db.execute(sql: "CREATE TEMPORARY TABLE temp AS SELECT * FROM t")
let result = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM temp")!
try db.execute(sql: "DROP TABLE temp")
return result
})
observation.requiresWriteAccess = true
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db -> Int in
XCTAssert(db.isInsideTransaction, "expected a wrapping transaction")
try db.execute(sql: "CREATE TEMPORARY TABLE temp AS SELECT * FROM t")
let result = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM temp")!
try db.execute(sql: "DROP TABLE temp")
return result
})
observation.requiresWriteAccess = true
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
try assertValueObservation(
observation,
records: [0, 1],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
})
}
func testWriteObservationIsWrappedInSavepointWithErrorHandling() throws {
struct TestError: Error { }
var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
throw TestError()
})
observation.requiresWriteAccess = true
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.Fetch<Void>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
let recorder = observation.record(in: writer)
let (_, error) = try wait(for: recorder.failure(), timeout: 0.5)
do {
throw error
} catch is TestError {
try assertValueObservation(
observation,
fails: { (_: TestError, writer: DatabaseWriter) in
let count = try writer.read { try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t")! }
XCTAssertEqual(count, 0)
}
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: { db in
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
throw TestError()
})
observation.requiresWriteAccess = true
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
},
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)")
})
}
}
+50 -122
View File
@@ -24,146 +24,74 @@ extension Player: TableRecord, FetchableRecord {
class ValueObservationRecordTests: GRDBTestCase {
func testAll() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.AllRecords<SQLRequest<Player>.RowDecoder>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
try assertValueObservation(
SQLRequest<Player>(sql: "SELECT * FROM t ORDER BY id").observationForAll(),
records: [
[],
[Player(id: 1, name: "foo")],
[Player(id: 1, name: "foo"), Player(id: 2, name: "bar")],
[Player(id: 2, name: "bar")]],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1")
try db.inTransaction {
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1
}
let expectedValues = [
[],
[Player(id: 1, name: "foo")],
[Player(id: 1, name: "foo"), Player(id: 2, name: "bar")],
[Player(id: 2, name: "bar")]]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = SQLRequest<Player>(sql: "SELECT * FROM t ORDER BY id").observationForAll()
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
try db.execute(sql: "DELETE FROM t WHERE id = 1")
})
}
func testTableRecordStaticAll() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.AllRecords<Player>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1
}
let expectedValues = [
try assertValueObservation(
Player.observationForAll(),
records: [
[],
[Player(id: 1, name: "foo")],
[Player(id: 1, name: "foo"), Player(id: 2, name: "bar")],
[Player(id: 2, name: "bar")]]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = Player.observationForAll()
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
}
func testOne() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.OneRecord<SQLRequest<Player>.RowDecoder>>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
[Player(id: 2, name: "bar")]],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1")
try db.inTransaction {
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t") // -1
}
let expectedValues = [
try db.execute(sql: "DELETE FROM t WHERE id = 1")
})
}
func testOne() throws {
try assertValueObservation(
SQLRequest<Player>(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst(),
records: [
nil,
Player(id: 1, name: "foo"),
Player(id: 2, name: "bar"),
nil]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = SQLRequest<Player>(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst()
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
nil],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1")
try db.inTransaction {
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t")
})
}
}
@@ -330,6 +330,117 @@ extension XCTestCase {
}
}
// MARK: - GRDBTestCase + ValueObservationExpectation
extension GRDBTestCase {
func assertValueObservation<Reducer: _ValueReducer>(
_ valueObservation: ValueObservation<Reducer>,
records expectedValues: [Reducer.Value],
setup: (Database) throws -> Void,
recordedUpdates: (Database) throws -> Void,
file: StaticString = #file,
line: UInt = #line)
throws
where Reducer.Value: Equatable
{
func testRecordingEqual(writer: DatabaseWriter, observation: ValueObservation<Reducer>) throws {
try writer.write(setup)
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction(recordedUpdates)
let expectation = recorder.next(expectedValues.count)
let values = try wait(for: expectation, timeout: 0.3)
XCTAssertEqual(values, expectedValues, file: file, line: line)
}
func testRecordingMatch(writer: DatabaseWriter, observation: ValueObservation<Reducer>) throws {
try writer.write(setup)
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction(recordedUpdates)
let expectation = recorder
.prefix(expectedValues.count + 2 /* pool may perform double initial fetch */)
.inverted
let values = try wait(for: expectation, timeout: 0.3)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
file: file, line: line)
}
do {
var observation = valueObservation
observation.scheduling = .mainQueue
try testRecordingEqual(writer: DatabaseQueue(), observation: observation)
try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation)
try testRecordingEqual(writer: makeDatabasePool(), observation: observation)
}
do {
var observation = valueObservation
observation.scheduling = .async(onQueue: .main)
try testRecordingEqual(writer: DatabaseQueue(), observation: observation)
try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation)
if valueObservation.requiresWriteAccess {
try testRecordingEqual(writer: makeDatabasePool(), observation: observation)
} else {
// DatabasePool performs an immediate async fetch and may miss initial changes
try testRecordingMatch(writer: makeDatabasePool(), observation: observation)
}
}
do {
var observation = valueObservation
observation.scheduling = .unsafe
try testRecordingEqual(writer: DatabaseQueue(), observation: observation)
try testRecordingEqual(writer: makeDatabaseQueue(), observation: observation)
try testRecordingEqual(writer: makeDatabasePool(), observation: observation)
}
}
func assertValueObservation<Reducer: _ValueReducer, Failure: Error>(
_ valueObservation: ValueObservation<Reducer>,
fails testFailure: (Failure, DatabaseWriter) throws -> Void,
setup: (Database) throws -> Void,
file: StaticString = #file,
line: UInt = #line)
throws
{
func test(writer: DatabaseWriter, observation: ValueObservation<Reducer>) throws {
try writer.write(setup)
let recorder = observation.record(in: writer)
let (_, error) = try wait(for: recorder.failure(), timeout: 0.3)
if let error = error as? Failure {
try testFailure(error, writer)
} else {
throw error
}
}
do {
var observation = valueObservation
observation.scheduling = .mainQueue
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
do {
var observation = valueObservation
observation.scheduling = .async(onQueue: .main)
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
do {
var observation = valueObservation
observation.scheduling = .unsafe
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
}
}
// MARK: - ValueObservationExpectations
public enum ValueObservationExpectations { }
+72 -195
View File
@@ -12,143 +12,74 @@ import XCTest
class ValueObservationRowTests: GRDBTestCase {
func testAll() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.AllRows>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t WHERE id = 1") // -1
}
let expectedValues: [[Row]] = [
try assertValueObservation(
SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id").observationForAll(),
records: [
[],
[["id":1, "name":"foo"]],
[["id":1, "name":"foo"], ["id":2, "name":"bar"]],
[["id":2, "name":"bar"]]]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id").observationForAll()
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
}
func testOne() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.OneRow>) throws {
try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')") // +1
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1") // =
try db.inTransaction { // +1
[["id":2, "name":"bar"]]],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1")
try db.inTransaction {
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t") // -1
}
let expectedValues: [Row?] = [
try db.execute(sql: "DELETE FROM t WHERE id = 1")
})
}
func testOne() throws {
try assertValueObservation(
SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst(),
records: [
nil,
["id":1, "name":"foo"],
["id":2, "name":"bar"],
nil]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 1 /* deduplication: don't expect more than expectedValues */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
var observation = SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id DESC").observationForFirst()
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
nil],
setup: { db in
try db.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
try db.execute(sql: "UPDATE t SET name = 'foo' WHERE id = 1")
try db.inTransaction {
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "DELETE FROM t WHERE id = 3")
return .commit
}
try db.execute(sql: "DELETE FROM t")
})
}
func testFTS4Observation() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.Fetch<[Row]>>) throws {
try writer.write { try $0.create(virtualTable: "ft_documents", using: FTS4()) }
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
try db.execute(sql: "INSERT INTO ft_documents VALUES (?)", arguments: ["foo"])
}
let expectedValues: [[Row]] = [
try assertValueObservation(
SQLRequest<Row>(sql: "SELECT * FROM ft_documents").observationForAll(),
records: [
[],
[["content":"foo"]]]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
let request = SQLRequest<Row>(sql: "SELECT * FROM ft_documents")
var observation = ValueObservation.tracking(value: request.fetchAll)
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
[["content":"foo"]]],
setup: { db in
try db.create(virtualTable: "ft_documents", using: FTS4())
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO ft_documents VALUES (?)", arguments: ["foo"])
})
}
func testSynchronizedFTS4Observation() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.Fetch<[Row]>>) throws {
try writer.write { db in
try assertValueObservation(
SQLRequest<Row>(sql: "SELECT * FROM ft_documents").observationForAll(),
records: [
[],
[["content":"foo"]]],
setup: { db in
try db.create(table: "documents") { t in
t.column("id", .integer).primaryKey()
t.column("content", .text)
@@ -157,91 +88,37 @@ class ValueObservationRowTests: GRDBTestCase {
t.synchronize(withTable: "documents")
t.column("content")
}
}
let recorder = observation.record(in: writer)
try writer.writeWithoutTransaction { db in
},
recordedUpdates: { db in
try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["foo"])
}
let expectedValues: [[Row]] = [
[],
[["content":"foo"]]]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
let request = SQLRequest<Row>(sql: "SELECT * FROM ft_documents")
var observation = ValueObservation.tracking(value: request.fetchAll)
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
})
}
func testJoinedFTS4Observation() throws {
func test(writer: DatabaseWriter, observation: ValueObservation<ValueReducers.Fetch<[Row]>>) throws {
try writer.write { db in
try assertValueObservation(
SQLRequest<Row>(sql: """
SELECT document.* FROM document
JOIN ft_document ON ft_document.rowid = document.id
WHERE ft_document MATCH 'foo'
""")
.observationForAll(),
records: [
[],
[["id":1]]],
setup: { db in
try db.create(table: "document") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(virtualTable: "ft_document", using: FTS4()) { t in
t.column("content")
}
}
let recorder = observation.record(in: writer)
try writer.write { db in
try db.execute(sql: "INSERT INTO document (id) VALUES (?)", arguments: [1])
try db.execute(sql: "INSERT INTO ft_document (rowid, content) VALUES (?, ?)", arguments: [1, "foo"])
}
let expectedValues: [[Row]] = [
[],
[["id":1]]]
let values = try wait(
for: recorder
.prefix(expectedValues.count + 2 /* async pool may perform double initial fetch */)
.inverted,
timeout: 0.5)
assertValueObservationRecordingMatch(
recorded: values,
expected: expectedValues,
"\(type(of: writer)), \(observation.scheduling)")
}
let schedulings: [ValueObservationScheduling] = [
.mainQueue,
.async(onQueue: .main),
.unsafe
]
for scheduling in schedulings {
let request = SQLRequest<Row>(sql: """
SELECT document.* FROM document
JOIN ft_document ON ft_document.rowid = document.id
WHERE ft_document MATCH 'foo'
""")
var observation = ValueObservation.tracking(value: request.fetchAll)
observation.scheduling = scheduling
try test(writer: DatabaseQueue(), observation: observation)
try test(writer: makeDatabaseQueue(), observation: observation)
try test(writer: makeDatabasePool(), observation: observation)
}
},
recordedUpdates: { db in
try db.inTransaction {
try db.execute(sql: "INSERT INTO document (id) VALUES (?)", arguments: [1])
try db.execute(sql: "INSERT INTO ft_document (rowid, content) VALUES (?, ?)", arguments: [1, "foo"])
return .commit
}
})
}
}