Merge pull request #478 from groue/feature/SQLInterpolation2

Swift 5: SQL interpolation
This commit is contained in:
Gwendal Roué authored and GitHub committed 2019-02-22 13:43:11 +01:00
commit 03b8df2fe1
209 files changed
+5878 -3697

No files matched your search

+8
View File
@@ -44,6 +44,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection:
## GRDB-4.0 branch
### New
- [#478](https://github.com/groue/GRDB.swift/pull/478): Swift 5: SQL interpolation
### Breaking Changes
- Swift 4.0 and Swift 4.1 are no longer supported
@@ -51,6 +55,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection:
- Deprecated APIs are no longer available.
- `SQLRequest.arguments` is no longer optional
### Documentation Diff
- [SQL Interpolation](Documentation/SQLInterpolation.md): this new document describes the new SQL interpolation feature.
## 3.6.2
+1 -1
View File
@@ -81,7 +81,7 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
The full-text table can be fed and queried in [a regular way](../../../#full-text-search):
```swift
try db.execute("INSERT INTO documents VALUES (?)", arguments: ["..."])
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["..."])
try Document(content: "...").insert(db)
let pattern = FTS5Pattern(matchingAnyTokenIn:"...")
+414
View File
@@ -0,0 +1,414 @@
SQL Interpolation
=================
Your SQL skills are [welcomed] throughout GRDB. Yet writing raw SQL presents commonplace challenges. For example, you want to make sure your queries don't break whenever the database schema changes as you ship new versions of your application. When you inject user values in the database, you have to use statement arguments, and it is easy to make a mistake in the process.
The query below exemplifies this situation. It even contains a bug that is not quite easy to spot:
```swift
try db.execute(
sql: """
UPDATE student
SET firstName = ?, lastName = ?, department = ?, birthDate = ?,
registrationDate = ?, mainTeacherId = ?
WHERE id = ?
""",
arguments: [firstName, lastName, department, birthDate,
registrationDate, mainTeacherId])
```
SQL Interpolation is an answer to these troubles. It is available in Swift 5.
- [Introduction]
- [SQLLiteral]
- [SQL Interpolation and Record Protocols]
- [SQL Interpolation Reference]
## Introduction
**SQL Interpolation** lets you embed values in your SQL queries by wrapping them inside `\(` and `)`:
```swift
let name: String = ...
let id: Int64 = ...
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
```
SQL interpolation looks and feel just like regular [String interpolation]:
```swift
let name = "World"
print("Hello \(name)!") // prints "Hello World!"
```
The difference is that it generates valid SQL which does not suffer from syntax errors or [SQL injection]. For example, you do not need to validate input or process single quotes:
```swift
// Executes `UPDATE player SET name = 'O''Brien' WHERE id = 42`
let name = "O'Brien"
let id = 42
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
```
Under the hood, SQL interpolation generates a plain SQL string. It runs exactly as below:
```swift
try db.execute(sql: "UPDATE player SET name = ? WHERE id = ?", arguments: [name, id])
```
Plain SQL strings are indeed still available, and SQL interpolation only kicks in when you ask for it. There is a simple rule to remember:
- For plain SQL strings, use the `sql` argument label:
```swift
try db.execute(sql: "UPDATE player SET name = ? WHERE id = ?", arguments: [name, id])
```
- For SQL interpolation, use the `literal` argument label:
```swift
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
```
## SQLLiteral
**SQLLiteral** is the type that looks like a plain String, but profits from SQL interpolation:
```swift
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
try db.execute(literal: query)
```
**SQLLiteral is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
```swift
// Compiler error:
// Cannot convert value of type 'String' to expected argument type 'SQLLiteral'
let query = "UPDATE player SET name = \(name) WHERE id = \(id)" // a String
try db.execute(literal: query)
```
SQLLiteral can build your queries step by step, with regular operators and methods:
```swift
// +, +=, append
var query: SQLLiteral = "UPDATE player "
query += "SET name = \(name) "
query.append(literal: "WHERE id = \(id)")
// joined(), joined(separator:)
let components: [SQLLiteral] = [
"UPDATE player",
"SET name = \(name)",
"WHERE id = \(id)"
]
let query = components.joined(separator: " ")
```
Extract the plain SQL string from a literal:
```swift
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(query.arguments) // prints ["O'Brien", 42]
```
Build a literal from a plain SQL string:
```swift
let query = SQLLiteral(
sql: "UPDATE player SET name = ? WHERE id = ?",
arguments: [name, id])
```
SQLLiteral can embed any [value], as we have seen above, but not only. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
## SQL Interpolation and Record Protocols
The [record protocols] extend your application types with database abilities.
**A record type knows everything about the schema of its underlying database table**. With the [TableRecord] protocol, the `databaseTableName` property contains the table name. With the [Decodable] protocol, the [CodingKeys] enum contain the column names. And with [FetchableRecord], you can decode raw database rows:
SQL Interpolation puts this knowledge to good use, so that you can build robust queries that consistently use correct table and column names:
```swift
struct Player {
var id: Int64
var name: String
var score: Int?
}
extension Player: Decodable, FetchableRecord, TableRecord {
/// Deletes all player with no score
static func deleteAllWithoutScore(_ db: Database) throws {
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
}
/// The player with a given id
static func filter(id: Int64) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
}
/// All players with the given ids
static func filter(ids: [Int64]) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
}
/// The maximum score
static func maximumScore() -> SQLRequest<Int> {
return "SELECT MAX(\(CodingKeys.score)) FROM \(self)"
}
/// All players whose score is the maximum score
static func leaders() -> SQLRequest<Player> {
return """
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
"""
}
/// A complex request
static func complexRequest() -> SQLRequest<Player> {
let query: SQLLiteral = "SELECT * FROM \(self) "
query += "JOIN \(Team.self) ON ..."
query += "GROUP BY ..."
return SQLRequest(literal: query)
}
}
```
Let's breakdown each one of those methods.
- `deleteAllWithoutScore(_:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// Deletes all player with no score
static func deleteAllWithoutScore(_ db: Database) throws {
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
}
}
```
Usage:
```swift
try dbQueue.write { db in
// DELETE FROM player WHERE score IS NULL
try Player.deleteAllWithoutScore(db)
}
```
`DELETE FROM \(self) ...` embeds the Player type itself. Since Player adopts the [TableRecord] protocol, this embeds `Player.databaseTableName` in the SQL query.
`... \(CodingKeys.score) IS NULL` embeds CodingKeys.score. This one has been synthesized by the Swift compiler because Player adopts the Decodable protocol. It embeds the column name in the SQL query.
- `filter(id:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// The player with a given id
static func filter(id: Int64) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
}
}
```
Usage:
```swift
let player = try dbQueue.read { db in
// SELECT * player WHERE id = 42
try Player.filter(id: 42).fetchOne(db) // Player?
}
```
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. And it profits from SQL interpolation: this is why this method can simply return an "SQL literal"".
It embeds `\(self)` (the Player type which adopts the TableRecord protocol) and `\(CodingKeys.id)` (the coding key synthesized by the Decodable protocol), and `\(id)` (a [value]).
- `filter(ids:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// All players with the given ids
static func filter(ids: [Int64]) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
}
}
```
Usage:
```swift
let players = try dbQueue.read { db in
// SELECT * player WHERE id IN (1, 2, 3)
try Player.filter(ids: [1, 2, 3]).fetchAll(db) // [Player]
}
```
It embeds `\(ids)`, an array of ids. All [value] sequences are supported (arrays, sets, etc.) Empty sequences are supported as well, with both `IN` and `NOT IN` SQL operators.
- `maximumScore()`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// The maximum score
static func maximumScore() -> SQLRequest<Int> {
return "SELECT MAX(\(CodingKeys.score)) FROM \(self)"
}
}
```
Usage:
```swift
let maximumScore = try dbQueue.read { db in
// SELECT MAX(score) FROM player
try Player.maximumScore().fetchOne(db) // Int?
}
```
The result is `SQLRequest<Int>`, unlike previous requests of type `SQLRequest<Player>`. SQLRequest accepts any fetchable type (database [row], simple [value], or custom [record]).
- `leaders()`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// All players whose score is the maximum score
static func leaders() -> SQLRequest<Player> {
return """
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
"""
}
}
```
Usage:
```swift
let leaders = try dbQueue.read { db in
// SELECT * FROM player
// WHERE score = (SELECT MAX(score) FROM player)
try Player.leaders().fetchAll(db) // [Player]
}
```
This request embeds `\(maximumScore())`, the `SQLRequest<Int>` returned by the `maximumScore` method. After values, coding keys, and types that adopt the TableRecord protocol, this ends our quick tour of things you can embed between `\(` and `)`. Check out the [SQL Interpolation Reference] for the full list of supported interpolations.
- `complexRequest()`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// A complex request
static func complexRequest() -> SQLRequest<Player> {
let query: SQLLiteral = "SELECT * FROM \(self) "
query += "JOIN \(Team.self) ON ..."
query += "GROUP BY ..."
return SQLRequest(literal: query)
}
}
```
This last request shows how to build an SQLRequest from an [SQLLiteral]. You will need SQLLiteral when the request can not be expressed in a single "SQL literal".
## SQL Interpolation Reference
This chapter lists all kinds of supported interpolations.
- Types adopting the [TableRecord] protocol:
```swift
// SELECT * FROM player
extension Player: TableRecord { }
"SELECT * FROM \(Player.self)"
```
- [Expressions] and [values]:
```swift
// SELECT name FROM player
"SELECT \(Column("name")) FROM player"
// SELECT (score + 100) AS points FROM player
let bonus = 100
"SELECT \(Column("score") + bonus) AS points FROM player"
// SELECT (score + 100) AS points FROM player
"SELECT (score + \(bonus)) AS points FROM player"
```
- Coding keys:
```swift
// SELECT name FROM player
"SELECT \(CodingKeys.name) FROM player"
```
- Sequences:
```swift
// SELECT * FROM player WHERE id IN (1, 2, 3)
let ids = [1, 2, 3]
"SELECT * FROM player WHERE id IN \(ids)"
```
- Orderings:
```swift
// SELECT * FROM player ORDER BY name DESC
"SELECT * FROM player WHERE id IN \(Column("name").desc)"
```
- SQLRequest:
```swift
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
"SELECT * FROM player WHERE score = \(subQuery)"
```
- SQLLiteral:
```swift
// SELECT * FROM player WHERE name = 'O''Brien'
let condition: SQLLiteral = "name = \("O'Brien")"
"SELECT * FROM player WHERE \(literal: condition)"
```
- Plain SQL strings and eventual arguments:
```swift
// SELECT * FROM player
"SELECT * FROM \(sql: "player")"
// SELECT * FROM player WHERE name = 'O''Brien'
"SELECT * FROM player WHERE \(sql: "name = ?", arguments: ["O'Brien"])"
```
[Introduction]: #introduction
[SQLLiteral]: #sqlliteral
[SQL Interpolation and Record Protocols]: #sql-interpolation-and-record-protocols
[SQL Interpolation Reference]: #sql-interpolation-reference
[String interpolation]: https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID292
[SQL injection]: ../README.md#avoiding-sql-injection
[record protocols]: ../README.md#record-protocols-overview
[FetchableRecord]: ../README.md#fetchablerecord-protocol
[TableRecord]: ../README.md#tablerecord-protocol
[Decodable]: ../README.md#codable-records
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[value]: ../README.md#values
[values]: ../README.md#values
[request types]: ../README.md#custom-requests
[row]: ../README.md#row-queries
[record]: ../README.md#records
[Expressions]: ../README.md#expressions
[welcomed]: ../README.md#sqlite-api
[SE-0228 Fix ExpressibleByStringInterpolation]: https://github.com/apple/swift-evolution/blob/master/proposals/0228-fix-expressiblebystringinterpolation.md
+40 -28
View File
@@ -69,7 +69,7 @@ By adopting the [FetchableRecord] protocol, places can be loaded from SQL reques
```swift
extension Place: FetchableRecord { ... }
let places = try Place.fetchAll(db, "SELECT * FROM place") // [Place]
let places = try Place.fetchAll(db, sql: "SELECT * FROM place") // [Place]
```
Add the [TableRecord] protocol, and SQL requests are generated for you:
@@ -177,9 +177,14 @@ For further information about GRDB concurrency, check its detailed [Concurrency
SQL is a weird language. Born in the 70s, easy to [misuse](https://xkcd.com/327/), feared by some developers, despised by others, and yet wonderfully concise and powerful.
GRDB [query interface] and [associations] can generate SQL for you:
GRDB [records], [query interface] and [associations] can generate SQL for you:
```swift
// UPDATE player SET score = 950 WHERE id = 42
try player.updateChanges {
$0.score += 10
}
// SELECT * FROM player ORDER BY score DESC LIMIT 10
let bestPlayers: [Player] = try Player
.order(scoreColumn.desc)
@@ -202,19 +207,47 @@ let bookInfos: [BookInfo] = BookInfo.fetchAll(db, request)
But you can always switch to SQL when you want to:
```swift
let bestPlayers: [Player] = try Player.fetchAll(db, """
try db.execute(
sql: "UPDATE player SET score = ? WHERE id = ?",
arguments: [950, 42])
let bestPlayers: [Player] = try Player.fetchAll(db, sql: """
SELECT * FROM player ORDER BY score DESC LIMIT 10
""")
let maximumScore: Int? = try Int.fetchOne(db, """
let maximumScore: Int? = try Int.fetchOne(db, sql: """
SELECT MAX(score) FROM player
""")
```
With Swift 5, you can profit from **SQL interpolation**. It lets you build SQL queries from natural looking strings, but without any risk of syntax error or [SQL injection](https://xkcd.com/327/):
```swift
try db.execute(literal: "UPDATE player SET score = \(score) WHERE id = \(id)")
extension Player {
static func filter(name: String) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.name) = \(name)"
}
}
let player = try Player.filter(name: "Arthur O'Brien").fetchOne(db)
```
Custom SQL requests as the one above are welcome in database observation tools like [ValueObservation] and [RxGRDB]:
```swift
Player.filter(name: "Arthur O'Brien").rx
.fetchOne(in: dbQueue)
.subscribe(onNext: { (player: Player?) in
print("Player has changed")
})
```
Power users can also consume complex joined SQL queries into handy record values, by *adapting* raw database rows to the decoded records (see [Joined Queries Support](#../README.md#joined-queries-support)):
```swift
let bookInfos: [BookInfo] = SQLRequest<BookInfo>("""
let bookInfos: [BookInfo] = SQLRequest<BookInfo>(sql: """
SELECT book.*, author.*
FROM book
LEFT JOIN author ON author.id = book.authorId
@@ -232,7 +265,7 @@ let bookInfos: [BookInfo] = SQLRequest<BookInfo>("""
In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](../README.md#cursors) instead of arrays:
```swift
let rows = try Row.fetchCursor(db, "SELECT id, name, score FROM player")
let rows = try Row.fetchCursor(db, sql: "SELECT id, name, score FROM player")
while let row = try rows.next() {
let id: Int64 = row[0]
let name: String = row[1]
@@ -240,28 +273,6 @@ while let row = try rows.next() {
}
```
When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](../README.md#custom-requests):
```swift
extension Player {
static func customRequest(...) -> SQLRequest<Player> {
return SQLRequest<Player>("SELECT ...", arguments: ...)
}
}
let players = try Player.customRequest(...).fetchAll(db)
```
Those custom requests are welcome in database observation tools like [ValueObservation] and [RxGRDB]:
```swift
Player.customRequest(...).rx
.fetchAll(in: dbQueue)
.subscribe(onNext: { players: [Player] in
print("Players have changed")
})
```
---
If this little tour of GRDB has convinced you, the real trip starts here: [GRDB].
@@ -294,3 +305,4 @@ Happy GRDB! :gift:
[query interface]: ../README.md#the-query-interface
[associations]: AssociationsBasics.md
[Codable records]: ../README.md#codable-records
[records]: ../README.md#records
+45
View File
@@ -438,6 +438,8 @@
567DAF221EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567DAF391EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567F0B2D220F0E2E00D111FB /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */; };
567F0B2E220F0E2E00D111FB /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */; };
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
@@ -504,6 +506,9 @@
5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; };
5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; };
569C1EB51CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; };
569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */; };
569D6DDF220EF9E100A058A9 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */; };
569D6DE0220EF9E100A058A9 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */; };
569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; };
569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; };
569EF0E4200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; };
@@ -567,6 +572,8 @@
56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
56B86E79220FF4E000524C16 /* SQLLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */; };
56B86E7A220FF4E000524C16 /* SQLLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */; };
56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; };
56B964A01DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; };
56B964A31DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; };
@@ -735,6 +742,12 @@
56E5D82D1B4D438800430942 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; };
56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; };
56E8CE111BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */; };
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
56E9FACD221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
56E9FAD8221053DD00C703A8 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */; };
56E9FAD9221053DD00C703A8 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */; };
56E9FADA221053DD00C703A8 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */; };
56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; };
56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; };
56EA86951C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; };
@@ -748,6 +761,9 @@
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
56F5ABDC1D814330001F60CB /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; };
56F5ABDD1D814330001F60CB /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
@@ -1053,6 +1069,7 @@
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
@@ -1093,6 +1110,7 @@
5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = "<group>"; };
5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = "<group>"; };
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = "<group>"; };
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLInterpolation.swift; sourceTree = "<group>"; };
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = "<group>"; };
56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = "<group>"; };
56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryTests.swift; sourceTree = "<group>"; };
@@ -1140,6 +1158,7 @@
56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = "<group>"; };
56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-4.2.1/Realm.framework"; sourceTree = "<group>"; };
56B8C2411CA1758F00510325 /* RealmSwift.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = RealmSwift.framework; path = "Realm/build/osx/swift-4.2.1/RealmSwift.framework"; sourceTree = "<group>"; };
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = "<group>"; };
@@ -1207,6 +1226,8 @@
56E5D7F91B4D422D00430942 /* GRDBOSXTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = "<group>"; };
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = "<group>"; };
56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "SQLInterpolation+QueryInterface.swift"; sourceTree = "<group>"; };
56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteral.swift; sourceTree = "<group>"; };
56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = "<group>"; };
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = "<group>"; };
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = "<group>"; };
@@ -1214,6 +1235,7 @@
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = "<group>"; };
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = "<group>"; };
@@ -1509,6 +1531,7 @@
56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */,
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */,
5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */,
56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */,
56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */,
56D91AA12205E03700770D8D /* SQLRelation.swift */,
56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */,
@@ -1721,6 +1744,8 @@
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */,
56A2381D1B9C74A90082EB20 /* Row */,
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */,
567F0B2C220F0E2E00D111FB /* SQLInterpolationTests.swift */,
56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */,
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */,
56A238201B9C74A90082EB20 /* Statement */,
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */,
@@ -1814,6 +1839,9 @@
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
56FBFED82210731A00945324 /* SQLRequest.swift */,
56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */,
56A238781B9C75030082EB20 /* Statement.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
@@ -2497,12 +2525,15 @@
5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
563EF45D2163309F007DAACD /* Inflections.swift in Sources */,
56D7E453221596180052464B /* GRDB-4.0.swift in Sources */,
569D6DE0220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
56D7E453221596180052464B /* GRDB-4.0.swift in Sources */,
565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */,
566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
5613ED4E21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift in Sources */,
5613ED5621A95DD000DC7A68 /* ValueObservation+Count.swift in Sources */,
56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
56E9FAD9221053DD00C703A8 /* SQLLiteral.swift in Sources */,
56B964A31DA51B4C0002DA19 /* FTS5.swift in Sources */,
56D91AAB2205F2F100770D8D /* DatabasePromise.swift in Sources */,
566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
@@ -2519,6 +2550,7 @@
565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */,
565490B71D5AE236005622CB /* Database.swift in Sources */,
5674A6E81F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
56E9FACD221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
5653EB2320944C7C00F46237 /* HasOneAssociation.swift in Sources */,
565490C01D5AE236005622CB /* DatabaseWriter.swift in Sources */,
565490C41D5AE236005622CB /* SchedulingWatchdog.swift in Sources */,
@@ -2535,6 +2567,7 @@
565490C61D5AE236005622CB /* Statement.swift in Sources */,
56CEB5071EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
56CEB4F71EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */,
56F5ABD91D814330001F60CB /* Data.swift in Sources */,
565490D41D5AE252005622CB /* (null) in Sources */,
566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
@@ -2669,11 +2702,13 @@
563B06AC217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */,
5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
569D6DDF220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */,
5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
56D7E452221596180052464B /* GRDB-4.0.swift in Sources */,
566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */,
5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */,
C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */,
5605F1681C672E4000235C62 /* NSNumber.swift in Sources */,
@@ -2681,12 +2716,14 @@
564CE5AD21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */,
56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */,
5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
5613ED5121A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */,
560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
5613ED3621A95A5C00DC7A68 /* ValueObservation+Map.swift in Sources */,
566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */,
56E9FAD8221053DD00C703A8 /* SQLLiteral.swift in Sources */,
5653EB0720944C7C00F46237 /* ForeignKeyRequest.swift in Sources */,
5657AABC1D107001006283EF /* NSData.swift in Sources */,
31A778841C6A4E0600F507F6 /* FetchedRecordsController.swift in Sources */,
@@ -2741,6 +2778,7 @@
56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */,
5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
5698AC071D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */,
567F0B2E220F0E2E00D111FB /* SQLInterpolationTests.swift in Sources */,
56C3F7561CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */,
56B021CD1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
563B0706218627F800B38F35 /* ValueObservationRowTests.swift in Sources */,
@@ -2782,6 +2820,7 @@
56741EAC1E66A8B3003E422D /* FetchRequestTests.swift in Sources */,
5672DE5C1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */,
56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */,
56B86E7A220FF4E000524C16 /* SQLLiteralTests.swift in Sources */,
56176C6C1EACCCC9000F3F2B /* FTS5PatternTests.swift in Sources */,
563363B21C933FF8000BE133 /* PersistableRecordTests.swift in Sources */,
56A238421B9C74A90082EB20 /* DatabaseValueConversionTests.swift in Sources */,
@@ -2921,6 +2960,7 @@
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */,
56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */,
56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */,
567F0B2D220F0E2E00D111FB /* SQLInterpolationTests.swift in Sources */,
5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */,
563B0705218627F800B38F35 /* ValueObservationRowTests.swift in Sources */,
@@ -2962,6 +3002,7 @@
5698ACD71DA925420056AF8C /* RowTestCase.swift in Sources */,
56176C7D1EACCD2D000F3F2B /* EncryptionTests.swift in Sources */,
56741EA81E66A8B3003E422D /* FetchRequestTests.swift in Sources */,
56B86E79220FF4E000524C16 /* SQLLiteralTests.swift in Sources */,
56D496831D813147008276D7 /* DatabaseSavepointTests.swift in Sources */,
56D496871D81316E008276D7 /* DatabaseTimestampTests.swift in Sources */,
56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */,
@@ -3150,11 +3191,13 @@
56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
568D131F2207213E00674B58 /* SQLSelectQueryGenerator.swift in Sources */,
5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
56D7E451221596180052464B /* GRDB-4.0.swift in Sources */,
56193E8E1CD8A3E200F95862 /* FetchedRecordsController.swift in Sources */,
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */,
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */,
5605F1651C672E4000235C62 /* NSNull.swift in Sources */,
@@ -3162,12 +3205,14 @@
5653EB1820944C7C00F46237 /* ForeignKey.swift in Sources */,
5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
5653EB0620944C7C00F46237 /* ForeignKeyRequest.swift in Sources */,
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
5605F1671C672E4000235C62 /* NSNumber.swift in Sources */,
56E9FADA221053DD00C703A8 /* SQLLiteral.swift in Sources */,
C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */,
56A238871B9C75030082EB20 /* Row.swift in Sources */,
5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */,
-3
View File
@@ -10,9 +10,6 @@
<FileRef
location = "group:JSONSynchronization.playground">
</FileRef>
<FileRef
location = "group:Record.playground">
</FileRef>
<FileRef
location = "group:TransactionObserver.playground">
</FileRef>
+4 -4
View File
@@ -14,7 +14,7 @@
extension Array {
/// Creates an array containing the elements of a cursor.
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let strings = try Array(cursor) // ["foo", "bar"]
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
@@ -36,7 +36,7 @@ extension Sequence {
extension Set {
/// Creates a set containing the elements of a cursor.
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'foo'")
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'foo'")
/// let strings = try Set(cursor) // ["foo"]
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
@@ -111,7 +111,7 @@ extension Cursor {
/// Returns a cursor of pairs (n, x), where n represents a consecutive
/// integer starting at zero, and x represents an element of the cursor.
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let c = cursor.enumerated()
/// while let (n, x) = c.next() {
/// print("\(n): \(x)")
@@ -595,7 +595,7 @@ public final class DropWhileCursor<Base: Cursor> : Cursor {
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
/// on a cursor:
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let c = cursor.enumerated()
/// while let (n, x) = c.next() {
/// print("\(n): \(x)")
+7 -7
View File
@@ -171,13 +171,13 @@ extension Database {
}
let indexes = try Row
.fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
.fetchAll(self, sql: "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
.map { row -> IndexInfo in
// [seq:0 name:"index" unique:0 origin:"c" partial:0]
let indexName: String = row[1]
let unique: Bool = row[2]
let columns = try Row
.fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.fetchAll(self, sql: "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.map { row -> (Int, String) in
// [seqno:0 cid:2 name:"column"]
(row[0] as Int, row[2] as String)
@@ -213,7 +213,7 @@ extension Database {
var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = []
var previousId: Int? = nil
for row in try Row.fetchAll(self, "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
for row in try Row.fetchAll(self, sql: "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
// row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."]
let id: Int = row[0]
let seq: Int = row[1]
@@ -320,7 +320,7 @@ extension Database {
}
}
let columns = try ColumnInfo
.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
.fetchAll(self, sql: "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
.sorted(by: { $0.cid < $1.cid })
guard columns.count > 0 else {
throw DatabaseError(message: "no such table: \(tableName)")
@@ -386,7 +386,7 @@ public struct ColumnInfo : FetchableRecord {
///
/// For example:
///
/// try db.execute("""
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY,
/// name TEXT DEFAULT 'Anonymous',
@@ -579,7 +579,7 @@ struct SchemaInfo: Equatable {
private var objects: Set<SchemaObject>
init(_ db: Database) throws {
objects = try Set(SchemaObject.fetchCursor(db, """
objects = try Set(SchemaObject.fetchCursor(db, sql: """
SELECT type, name, tbl_name, sql, 0 AS isTemporary FROM sqlite_master \
UNION \
SELECT type, name, tbl_name, sql, 1 FROM sqlite_temp_master
@@ -597,7 +597,7 @@ struct SchemaInfo: Equatable {
/// Returns the canonical name of the object:
///
/// try db.execute("CREATE TABLE FooBar (...)")
/// try db.execute(sql: "CREATE TABLE FooBar (...)")
/// try db.schema().canonicalName("foobar", ofType: .table) // "FooBar"
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
let name = name.lowercased()
+59 -28
View File
@@ -11,20 +11,20 @@ extension Database {
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
/// - parameter sql: An SQL query.
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeSelectStatement(_ sql: String) throws -> SelectStatement {
return try makeSelectStatement(sql, prepFlags: 0)
public func makeSelectStatement(sql: String) throws -> SelectStatement {
return try makeSelectStatement(sql: sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
@@ -33,13 +33,13 @@ extension Database {
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement {
return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
/// let statement = try db.cachedSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
@@ -49,31 +49,31 @@ extension Database {
/// - parameter sql: An SQL query.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func cachedSelectStatement(_ sql: String) throws -> SelectStatement {
public func cachedSelectStatement(sql: String) throws -> SelectStatement {
return try publicStatementCache.selectStatement(sql)
}
/// Returns a cached statement that does not conflict with user's cached statements.
func internalCachedSelectStatement(_ sql: String) throws -> SelectStatement {
func internalCachedSelectStatement(sql: String) throws -> SelectStatement {
return try internalStatementCache.selectStatement(sql)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// - parameter sql: An SQL query.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement {
return try makeUpdateStatement(sql, prepFlags: 0)
public func makeUpdateStatement(sql: String) throws -> UpdateStatement {
return try makeUpdateStatement(sql: sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)", prepFlags: 0)
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)", prepFlags: 0)
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
@@ -82,13 +82,13 @@ extension Database {
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement {
return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedUpdateStatement("INSERT INTO player (name) VALUES (?)")
/// let statement = try db.cachedUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
@@ -98,34 +98,63 @@ extension Database {
/// - parameter sql: An SQL query.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
public func cachedUpdateStatement(sql: String) throws -> UpdateStatement {
return try publicStatementCache.updateStatement(sql)
}
/// Returns a cached statement that does not conflict with user's cached statements.
func internalCachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
func internalCachedUpdateStatement(sql: String) throws -> UpdateStatement {
return try internalStatementCache.updateStatement(sql)
}
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try db.execute(
/// "INSERT INTO player (name) VALUES (:name)",
/// sql: "INSERT INTO player (name) VALUES (:name)",
/// arguments: ["name": "Arthur"])
///
/// try db.execute("""
/// try db.execute(sql: """
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// """, arguments; ['Arthur', 'Barbara', 'Craig'])
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
///
/// This method may throw a DatabaseError.
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws {
public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws {
try execute(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try db.execute(literal: SQLLiteral(
/// sql: "INSERT INTO player (name) VALUES (:name)",
/// arguments: ["name": "Arthur"]))
///
/// try db.execute(literal: SQLLiteral(sql: """
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// """, arguments: ["Arthur", "Barbara", "O'Brien"]))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// try db.execute(literal: """
/// INSERT INTO player (name) VALUES (\("Arthur"));
/// INSERT INTO player (name) VALUES (\("Barbara"));
/// INSERT INTO player (name) VALUES (\("O'Brien"));
/// """)
///
/// This method may throw a DatabaseError.
///
/// - parameter sqlLiteral: An SQLLiteral.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(literal sqlLiteral: SQLLiteral) throws {
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
// It adds support for arguments, and the tricky part is to consume
// arguments as statements are executed.
@@ -136,7 +165,9 @@ extension Database {
// all statements have been executed, in the same way
// as Statement.validate(arguments:)
var arguments = arguments ?? StatementArguments()
let sql = sqlLiteral.sql
var arguments = sqlLiteral.arguments
let initialValuesCount = arguments.values.count
let consumeArguments = { (statement: UpdateStatement) throws -> StatementArguments in
let bindings = try arguments.consume(statement, allowingRemainingValues: true)
@@ -254,15 +285,15 @@ struct StatementCache {
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let statement = try db.makeSelectStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
let statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement: SelectStatement
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
// SQLite 3.24.0 or more
statement = try db.makeSelectStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
} else {
// SQLite 3.19.3 or less
statement = try db.makeSelectStatement(sql)
statement = try db.makeSelectStatement(sql: sql)
}
#endif
selectStatements[sql] = statement
@@ -284,15 +315,15 @@ struct StatementCache {
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let statement = try db.makeUpdateStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
let statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement: UpdateStatement
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
// SQLite 3.24.0 or more
statement = try db.makeUpdateStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
} else {
// SQLite 3.19.3 or less
statement = try db.makeUpdateStatement(sql)
statement = try db.makeUpdateStatement(sql: sql)
}
#endif
updateStatements[sql] = statement
+16 -16
View File
@@ -151,7 +151,7 @@ public final class Database {
/// The list of compile options used when building SQLite
static let sqliteCompileOptions: Set<String> = DatabaseQueue().inDatabase {
try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS"))
try! Set(String.fetchCursor($0, sql: "PRAGMA COMPILE_OPTIONS"))
}
// MARK: - Private properties
@@ -353,7 +353,7 @@ extension Database {
private func setupForeignKeys() throws {
// Foreign keys are disabled by default with SQLite3
if configuration.foreignKeysEnabled {
try execute("PRAGMA foreign_keys = ON")
try execute(sql: "PRAGMA foreign_keys = ON")
}
}
@@ -489,7 +489,7 @@ extension Database {
/// return int + 1
/// }
/// db.add(function: fn)
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
public func add(function: DatabaseFunction) {
functions.update(with: function)
function.install(in: self)
@@ -512,7 +512,7 @@ extension Database {
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// db.add(collation: collation)
/// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
/// try db.execute(sql: "CREATE TABLE files (name TEXT COLLATE localized_standard")
public func add(collation: DatabaseCollation) {
collations.update(with: collation)
let collationPointer = Unmanaged.passUnretained(collation).toOpaque()
@@ -555,8 +555,8 @@ extension Database {
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// Assume those pragmas never fail
try! internalCachedUpdateStatement("PRAGMA query_only = 1").execute()
defer { try! internalCachedUpdateStatement("PRAGMA query_only = 0").execute() }
try! internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute()
defer { try! internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute() }
return try block()
}
}
@@ -569,7 +569,7 @@ extension Database {
///
/// try dbQueue.inDatabase do {
/// try db.inTransaction {
/// try db.execute("INSERT ...")
/// try db.execute(sql: "INSERT ...")
/// return .commit
/// }
/// }
@@ -629,7 +629,7 @@ extension Database {
///
/// try dbQueue.inDatabase do {
/// try db.inSavepoint {
/// try db.execute("INSERT ...")
/// try db.execute(sql: "INSERT ...")
/// return .commit
/// }
/// }
@@ -665,7 +665,7 @@ extension Database {
// using unique savepoint names. User could still mess with them
// with raw SQL queries, but let's assume that it is unlikely that
// the user uses "grdb" as a savepoint name.
try execute("SAVEPOINT grdb")
try execute(sql: "SAVEPOINT grdb")
// Now that savepoint has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
@@ -676,7 +676,7 @@ extension Database {
let completion = try block()
switch completion {
case .commit:
try execute("RELEASE SAVEPOINT grdb")
try execute(sql: "RELEASE SAVEPOINT grdb")
assert(!topLevelSavepoint || !isInsideTransaction)
needsRollback = false
case .rollback:
@@ -695,8 +695,8 @@ extension Database {
// Rollback, and release the savepoint.
// Rollback alone is not enough to clear the savepoint from
// the SQLite savepoint stack.
try execute("ROLLBACK TRANSACTION TO SAVEPOINT grdb")
try execute("RELEASE SAVEPOINT grdb")
try execute(sql: "ROLLBACK TRANSACTION TO SAVEPOINT grdb")
try execute(sql: "RELEASE SAVEPOINT grdb")
}
} catch {
if firstError == nil {
@@ -719,7 +719,7 @@ extension Database {
/// - throws: The error thrown by the block.
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
let kind = kind ?? configuration.defaultTransactionKind
try execute("BEGIN \(kind.rawValue) TRANSACTION")
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
assert(isInsideTransaction)
}
@@ -769,7 +769,7 @@ extension Database {
// UPDATE ...
// Here the change is not visible by GRDB user
try beginTransaction(.deferred)
try internalCachedSelectStatement("SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
try internalCachedSelectStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
}
/// Rollbacks a database transaction.
@@ -815,14 +815,14 @@ extension Database {
// should be exposed to the library user.
SchedulingWatchdog.preconditionValidQueue(self) // guard sqlite3_get_autocommit
if sqlite3_get_autocommit(sqliteConnection) == 0 {
try execute("ROLLBACK TRANSACTION")
try execute(sql: "ROLLBACK TRANSACTION")
}
assert(!isInsideTransaction)
}
/// Commits a database transaction.
public func commit() throws {
try execute("COMMIT TRANSACTION")
try execute(sql: "COMMIT TRANSACTION")
assert(!isInsideTransaction)
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ public final class DatabaseCollation {
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// db.add(collation: collation)
/// try db.execute("CREATE TABLE file (name TEXT COLLATE localized_standard")
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard")
///
/// - parameters:
/// - name: The function name.
+9 -9
View File
@@ -27,7 +27,7 @@ public final class DatabaseFunction: Hashable {
/// return int + 1
/// }
/// db.add(function: fn)
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
///
/// - parameters:
/// - name: The function name.
@@ -73,10 +73,10 @@ public final class DatabaseFunction: Hashable {
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
/// dbQueue.add(function: fn)
/// try dbQueue.write { db in
/// try db.execute("CREATE TABLE test(i)")
/// try db.execute("INSERT INTO test(i) VALUES (1)")
/// try db.execute("INSERT INTO test(i) VALUES (2)")
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
/// try db.execute(sql: "CREATE TABLE test(i)")
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
/// }
///
/// - parameters:
@@ -353,10 +353,10 @@ extension DatabaseFunction {
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
/// dbQueue.add(function: fn)
/// try dbQueue.write { db in
/// try db.execute("CREATE TABLE test(i)")
/// try db.execute("INSERT INTO test(i) VALUES (1)")
/// try db.execute("INSERT INTO test(i) VALUES (2)")
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
/// try db.execute(sql: "CREATE TABLE test(i)")
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
/// }
public protocol DatabaseAggregate {
/// Creates an aggregate.
+14 -14
View File
@@ -58,14 +58,14 @@ public final class DatabasePool: DatabaseWriter {
// Activate WAL Mode unless readonly
if !configuration.readonly {
try writer.sync { db in
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = WAL")
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode = WAL")
guard journalMode == "wal" else {
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
}
// https://www.sqlite.org/pragma.html#pragma_synchronous
// > Many applications choose NORMAL when in WAL mode
try db.execute("PRAGMA synchronous = NORMAL")
try db.execute(sql: "PRAGMA synchronous = NORMAL")
if !FileManager.default.fileExists(atPath: path + "-wal") {
// Create the -wal file if it does not exist yet. This
@@ -73,7 +73,7 @@ public final class DatabasePool: DatabaseWriter {
// opens a pool to an existing non-WAL database, and
// attempts to read from it.
// See https://github.com/groue/GRDB.swift/issues/102
try db.execute("CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); DROP TABLE grdb_issue_102;")
try db.execute(sql: "CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); DROP TABLE grdb_issue_102;")
}
}
}
@@ -247,13 +247,13 @@ extension DatabasePool : DatabaseReader {
/// try dbPool.read { db in
/// // Those two values are guaranteed to be equal, even if the
/// // `wine` table is modified between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// try dbPool.read { db in
/// // Now this value may be different:
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// This method is *not* reentrant.
@@ -288,15 +288,15 @@ extension DatabasePool : DatabaseReader {
/// try dbPool.unsafeRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// Cursor iteration is safe, though:
///
/// try dbPool.unsafeRead { db in
/// // No concurrent update can mess with this iteration:
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
/// while let row = try rows.next() { ... }
/// }
///
@@ -325,15 +325,15 @@ extension DatabasePool : DatabaseReader {
/// try dbPool.unsafeReentrantRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// 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 ...")
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
/// while let row = try rows.next() { ... }
/// }
///
@@ -557,7 +557,7 @@ extension DatabasePool : DatabaseReader {
/// }
/// dbPool.add(function: fn)
/// try dbPool.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
/// try Int.fetchOne(db, sql: "SELECT succ(1)") // 2
/// }
public func add(function: DatabaseFunction) {
functions.update(with: function)
@@ -579,7 +579,7 @@ extension DatabasePool : DatabaseReader {
/// }
/// dbPool.add(collation: collation)
/// try dbPool.write { db in
/// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func add(collation: DatabaseCollation) {
collations.update(with: collation)
+2 -2
View File
@@ -332,7 +332,7 @@ extension DatabaseQueue {
/// }
/// dbQueue.add(function: fn)
/// try dbQueue.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
/// try Int.fetchOne(db, sql: "SELECT succ(1)") // 2
/// }
public func add(function: DatabaseFunction) {
writer.sync { $0.add(function: function) }
@@ -352,7 +352,7 @@ extension DatabaseQueue {
/// }
/// dbQueue.add(collation: collation)
/// try dbQueue.write { db in
/// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func add(collation: DatabaseCollation) {
writer.sync { $0.add(collation: collation) }
+11 -11
View File
@@ -32,13 +32,13 @@ public protocol DatabaseReader : class {
/// try reader.read { db in
/// // Those two values are guaranteed to be equal, even if the
/// // `wine` table is modified between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// try reader.read { db in
/// // Now this value may be different:
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
@@ -61,15 +61,15 @@ public protocol DatabaseReader : class {
/// try reader.unsafeRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// Cursor iterations are isolated, though:
///
/// try reader.unsafeRead { db in
/// // No concurrent update can mess with this iteration:
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
/// while let row = try rows.next() { ... }
/// }
///
@@ -92,15 +92,15 @@ public protocol DatabaseReader : class {
/// try reader.unsafeReentrantRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// 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 ...")
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
/// while let row = try rows.next() { ... }
/// }
///
@@ -128,7 +128,7 @@ public protocol DatabaseReader : class {
/// }
/// reader.add(function: fn)
/// try reader.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
/// }
func add(function: DatabaseFunction)
@@ -144,7 +144,7 @@ public protocol DatabaseReader : class {
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// reader.add(collation: collation)
/// try reader.execute("SELECT * FROM file ORDER BY name COLLATE localized_standard")
/// try reader.execute(sql: "SELECT * FROM file ORDER BY name COLLATE localized_standard")
func add(collation: DatabaseCollation)
/// Remove a collation.
+2 -2
View File
@@ -18,7 +18,7 @@
///
/// - `SelectStatement.databaseRegion`:
///
/// let statement = db.makeSelectStatement("SELECT name, score FROM player")
/// let statement = db.makeSelectStatement(sql: "SELECT name, score FROM player")
/// print(statement.databaseRegion)
/// // prints "player(name,score)"
///
@@ -33,7 +33,7 @@
/// don't know about rowids:
///
/// // A plain statement
/// let statement = db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
/// let statement = db.makeSelectStatement(sql: "SELECT * FROM player WHERE id = 1")
/// statement.databaseRegion // "player(*)"
///
/// // A query interface request that executes the same statement:
+1 -1
View File
@@ -28,7 +28,7 @@ public class DatabaseSnapshot : DatabaseReader {
try serializedDatabase.sync { db in
// Assert WAL mode
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode")
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode")
guard journalMode == "wal" else {
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
}
+2 -2
View File
@@ -286,12 +286,12 @@ extension DatabaseValue {
return "NULL"
}
if context.appendArguments([self]) {
if context.append(arguments: [self]) {
return "?"
} else {
// Correctness above all: use SQLite to quote the value.
// Assume that the Quote function always succeeds
return DatabaseQueue().inDatabase { try! String.fetchOne($0, "SELECT QUOTE(?)", arguments: [self])! }
return DatabaseQueue().inDatabase { try! String.fetchOne($0, sql: "SELECT QUOTE(?)", arguments: [self])! }
}
}
+38 -38
View File
@@ -12,11 +12,11 @@
/// The protocol comes with built-in methods that allow to fetch cursors,
/// arrays, or single values:
///
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
/// try String.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
/// try String.fetchAll(statement, arguments:...) // [String]
/// try String.fetchOne(statement, arguments:...) // String?
@@ -42,7 +42,7 @@ extension DatabaseValueConvertible {
/// For example:
///
/// try dbQueue.read { db in
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM link")
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, sql: "SELECT url FROM link")
/// while let url = urls.next() { // URL
/// print(url)
/// }
@@ -102,7 +102,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor
/// For example:
///
/// try dbQueue.read { db in
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM link")
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, sql: "SELECT url FROM link")
/// while let url = urls.next() { // URL?
/// print(url)
/// }
@@ -161,11 +161,11 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
/// cursors, arrays, or single values:
///
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
/// try String.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
/// try String.fetchAll(statement, arguments:...) // [String]
/// try String.fetchOne(statement, arguments:...) // String
@@ -177,7 +177,7 @@ extension DatabaseValueConvertible {
/// Returns a cursor over values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try String.fetchCursor(statement) // Cursor of String
/// while let name = try names.next() { // String
/// ...
@@ -200,7 +200,7 @@ extension DatabaseValueConvertible {
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try String.fetchAll(statement) // [String]
///
/// - parameters:
@@ -218,7 +218,7 @@ extension DatabaseValueConvertible {
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let name = try String.fetchOne(statement) // String?
///
/// - parameters:
@@ -240,7 +240,7 @@ extension DatabaseValueConvertible {
/// Returns a cursor over values fetched from an SQL query.
///
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
/// let names = try String.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String
/// while let name = try name.next() { // String
/// ...
/// }
@@ -253,27 +253,27 @@ extension DatabaseValueConvertible {
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from an SQL query.
@@ -281,17 +281,17 @@ extension DatabaseValueConvertible {
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
/// let name = try String.fetchOne(db, sql: "SELECT name FROM ...") // String?
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -411,10 +411,10 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// Swift's Optional comes with built-in methods that allow to fetch cursors
/// and arrays of optional DatabaseValueConvertible:
///
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
/// try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?]
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
///
@@ -425,7 +425,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns a cursor over optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
@@ -448,7 +448,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns an array of optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try Optional<String>.fetchAll(statement) // [String?]
///
/// - parameters:
@@ -468,7 +468,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns a cursor over optional values fetched from an SQL query.
///
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
/// let names = try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
@@ -481,27 +481,27 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of optional values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String?]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - parameter arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
+7 -7
View File
@@ -132,30 +132,30 @@ extension DatabaseWriter {
// So we'll drop all database objects one after the other.
try writeWithoutTransaction { db in
// Prevent foreign keys from messing with drop table statements
let foreignKeysEnabled = try Bool.fetchOne(db, "PRAGMA foreign_keys")!
let foreignKeysEnabled = try Bool.fetchOne(db, sql: "PRAGMA foreign_keys")!
if foreignKeysEnabled {
try db.execute("PRAGMA foreign_keys = OFF")
try db.execute(sql: "PRAGMA foreign_keys = OFF")
}
// Remove all database objects, one after the other
do {
try db.inTransaction {
while let row = try Row.fetchOne(db, "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") {
while let row = try Row.fetchOne(db, sql: "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") {
let type: String = row["type"]
let name: String = row["name"]
try db.execute("DROP \(type) \(name.quotedDatabaseIdentifier)")
try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
}
return .commit
}
// Restore foreign keys if needed
if foreignKeysEnabled {
try db.execute("PRAGMA foreign_keys = ON")
try db.execute(sql: "PRAGMA foreign_keys = ON")
}
} catch {
// Restore foreign keys if needed
if foreignKeysEnabled {
try? db.execute("PRAGMA foreign_keys = ON")
try? db.execute(sql: "PRAGMA foreign_keys = ON")
}
throw error
}
@@ -172,7 +172,7 @@ extension DatabaseWriter {
///
/// See https://www.sqlite.org/lang_vacuum.html for more information.
public func vacuum() throws {
try writeWithoutTransaction { try $0.execute("VACUUM") }
try writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
// MARK: - Value Observation
+2 -95
View File
@@ -47,7 +47,7 @@ extension FetchRequest {
public func fetchCount(_ db: Database) throws -> Int {
let (statement, _) = try prepare(db)
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
return try Int.fetchOne(db, sql: sql, arguments: statement.arguments)!
}
/// Returns the database region that the request looks into.
@@ -129,7 +129,7 @@ public struct AnyFetchRequest<T> : FetchRequest {
_fetchCount = { db in
let (statement, _) = try prepare(db)
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
return try Int.fetchOne(db, sql: sql, arguments: statement.arguments)!
}
_databaseRegion = { db in
@@ -153,96 +153,3 @@ public struct AnyFetchRequest<T> : FetchRequest {
return try _databaseRegion(db)
}
}
// MARK: - SQLRequest
/// A FetchRequest built from raw SQL.
public struct SQLRequest<T> : FetchRequest {
public typealias RowDecoder = T
public var sql: String
public var arguments: StatementArguments
public var adapter: RowAdapter?
private let cache: Cache?
/// Creates a request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest("SELECT * FROM player")
/// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: A SQLRequest
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates an SQL request from any other fetch request.
///
/// - parameters:
/// - db: A database connection.
/// - request: A request.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: An SQLRequest
public init<Request: FetchRequest>(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder {
let (statement, adapter) = try request.prepare(db)
self.init(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
}
/// Creates an SQL request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest("SELECT * FROM player")
/// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter.
/// - statementCacheName: Optional statement cache name.
/// - returns: A SQLRequest
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
self.sql = sql
self.arguments = arguments ?? StatementArguments()
self.adapter = adapter
self.cache = cache
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
///
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement: SelectStatement
switch cache {
case .none:
statement = try db.makeSelectStatement(sql)
case .public?:
statement = try db.cachedSelectStatement(sql)
case .internal?:
statement = try db.internalCachedSelectStatement(sql)
}
try statement.setArgumentsWithValidation(arguments)
return (statement, adapter)
}
/// There are two statement caches: one for statements generated by the
/// user, and one for the statements generated by GRDB. Those are separated
/// so that GRDB has no opportunity to inadvertently modify the arguments of
/// user's cached statements.
enum Cache {
/// The public cache, for library user
case `public`
/// The internal cache, for grdb
case `internal`
}
}
+32 -24
View File
@@ -14,8 +14,8 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl
/// Unless we are producing a row array, we use a single row when iterating
/// a statement:
///
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let players = try Player.fetchAll(db, "SELECT ...")
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
/// let players = try Player.fetchAll(db, sql: "SELECT ...")
///
/// This row keeps an unmanaged reference to the statement, and a handle to
/// the sqlite statement, so that we avoid many retain/release invocations.
@@ -162,10 +162,10 @@ extension Row {
///
/// For example:
///
/// let row = try Row.fetchOne(db, "SELECT 'foo', 1")!
/// let row = try Row.fetchOne(db, sql: "SELECT 'foo', 1")!
/// row.containsNonNullValue // true
///
/// let row = try Row.fetchOne(db, "SELECT NULL, NULL")!
/// let row = try Row.fetchOne(db, sql: "SELECT NULL, NULL")!
/// row.containsNonNullValue // false
public var containsNonNullValue: Bool {
for i in (0..<count) where !impl.hasNull(atUncheckedIndex: i) {
@@ -541,7 +541,7 @@ extension Row {
///
/// // Fetch
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
///
/// row.scopes.count // 2
/// row.scopes.names // ["foo", "bar"]
@@ -565,7 +565,7 @@ extension Row {
///
/// // Fetch
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
///
/// row.scopesTree.names // ["foo", "bar", "baz"]
///
@@ -602,7 +602,7 @@ extension Row {
/// A cursor of database rows. For example:
///
/// try dbQueue.read { db in
/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM player")
/// let rows: RowCursor = try Row.fetchCursor(db, sql: "SELECT * FROM player")
/// }
public final class RowCursor : Cursor {
public let statement: SelectStatement
@@ -649,7 +649,7 @@ extension Row {
/// Returns a cursor over rows fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT ...")
/// let rows = try Row.fetchCursor(statement) // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row[0]
@@ -682,7 +682,7 @@ extension Row {
/// Returns an array of rows fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT ...")
/// let rows = try Row.fetchAll(statement)
///
/// - parameters:
@@ -698,7 +698,7 @@ extension Row {
/// Returns a single row fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT ...")
/// let row = try Row.fetchOne(statement)
///
/// - parameters:
@@ -722,7 +722,7 @@ extension Row {
/// Returns a cursor over rows fetched from an SQL query.
///
/// let rows = try Row.fetchCursor(db, "SELECT id, name FROM player") // RowCursor
/// let rows = try Row.fetchCursor(db, sql: "SELECT id, name FROM player") // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row[0]
/// let name: String = row[1]
@@ -744,42 +744,50 @@ extension Row {
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of rows fetched from an SQL query.
///
/// let rows = try Row.fetchAll(db, "SELECT ...")
/// let rows = try Row.fetchAll(db, sql: "SELECT id, name FROM player") // [Row]
/// for row in rows {
/// let id: Int64 = row[0]
/// let name: String = row[1]
/// }
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] {
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single row fetched from an SQL query.
///
/// let row = try Row.fetchOne(db, "SELECT ...")
/// let row = try Row.fetchOne(db, sql: "SELECT id, name FROM player") // Row?
/// if let row = row {
/// let id: Int64 = row[0]
/// let name: String = row[1]
/// }
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? {
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row? {
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -1093,7 +1101,7 @@ extension Row {
///
/// // Fetch
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
///
/// row.scopes.count // 2
/// row.scopes.names // ["foo", "bar"]
@@ -1168,7 +1176,7 @@ extension Row {
///
/// // Fetch
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
///
/// row.scopesTree.names // ["foo", "bar", "baz"]
///
+10 -10
View File
@@ -13,7 +13,7 @@ import Foundation
/// "b": adapters[1],
/// "c": adapters[2],
/// "d": adapters[3]])
/// let row = try Row.fetchOne(db, sql, adapter: adapter)
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)
/// row.scopes["a"] // [1]
/// row.scopes["b"] // [2, 3, 4]
/// row.scopes["c"] // [5, 6]
@@ -78,7 +78,7 @@ public struct LayoutedColumnMapping {
/// }
///
/// // [foo:"foo" bar: "bar"]
/// try Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
/// try Row.fetchOne(db, sql: "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
public init<S: Sequence>(layoutColumns: S) where S.Iterator.Element == (Int, String) {
self.layoutColumns = Array(layoutColumns)
self.lowercaseColumnIndexes = Dictionary(
@@ -201,7 +201,7 @@ extension SelectStatement : RowLayout {
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
///
/// // [baz:3]
/// try Row.fetchOne(db, sql, adapter: adapter)
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public protocol RowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -224,7 +224,7 @@ public protocol RowAdapter {
/// }
///
/// // [foo:1]
/// try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
/// try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter
}
@@ -269,7 +269,7 @@ public struct EmptyRowAdapter: RowAdapter {
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
///
/// // [foo:"bar"]
/// try Row.fetchOne(db, sql, adapter: adapter)
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public struct ColumnMapping : RowAdapter {
/// A dictionary from mapped column names to column names in a base row.
let mapping: [String: String]
@@ -303,7 +303,7 @@ public struct ColumnMapping : RowAdapter {
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
///
/// // [baz:3]
/// try Row.fetchOne(db, sql, adapter: adapter)
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public struct SuffixRowAdapter : RowAdapter {
/// The suffix index
let index: Int
@@ -330,7 +330,7 @@ public struct SuffixRowAdapter : RowAdapter {
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
///
/// // [bar:2 baz:3]
/// try Row.fetchOne(db, sql, adapter: adapter)
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public struct RangeRowAdapter : RowAdapter {
/// The range
let range: CountableRange<Int>
@@ -367,7 +367,7 @@ public struct RangeRowAdapter : RowAdapter {
///
/// // Fetch
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
///
/// // Scoped rows:
/// if let fooRow = row.scopes["foo"] {
@@ -389,7 +389,7 @@ public struct ScopeAdapter : RowAdapter {
/// For example:
///
/// let adapter = ScopeAdapter(["suffix": SuffixRowAdapter(fromIndex: 1)])
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: adapter)!
/// row // [1, 2, 3]
/// row.scopes["suffix"] // [2, 3]
///
@@ -406,7 +406,7 @@ public struct ScopeAdapter : RowAdapter {
///
/// let baseAdapter = RangeRowAdapter(0..<1)
/// let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)])
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: adapter)!
/// row // [1]
/// row.scopes["initial"] // [2, 3]
///
+33
View File
@@ -0,0 +1,33 @@
#if swift(>=5.0)
/// :nodoc:
public struct SQLInterpolation: StringInterpolationProtocol {
var context = SQLGenerationContext.literalGenerationContext(withArguments: true)
var sql: String
var arguments: StatementArguments {
get { return context.arguments! }
set { context.arguments = newValue }
}
public init(literalCapacity: Int, interpolationCount: Int) {
sql = ""
sql.reserveCapacity(literalCapacity + interpolationCount)
}
/// "SELECT * FROM player"
public mutating func appendLiteral(_ sql: String) {
self.sql += sql
}
/// "SELECT * FROM \(sql: "player")"
public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) {
self.sql += sql
self.arguments += arguments
}
/// "SELECT * FROM player WHERE \(literal: condition)"
public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) {
sql += sqlLiteral.sql
arguments += sqlLiteral.arguments
}
}
#endif
+145
View File
@@ -0,0 +1,145 @@
/// SQLLiteral is a type which support [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
///
/// For example:
///
/// try dbQueue.write { db in
/// let name: String = ...
/// let id: Int64 = ...
/// let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
/// try db.execute(literal: query)
/// }
public struct SQLLiteral {
private(set) public var sql: String
private(set) public var arguments: StatementArguments
/// Creates an SQLLiteral from a plain SQL string, and eventual arguments.
///
/// For example:
///
/// let query = SQLLiteral(
/// sql: "UPDATE player SET name = ? WHERE id = ?",
/// arguments: [name, id])
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
self.sql = sql
self.arguments = arguments
}
/// Returns a literal whose SQL is transformed by the given closure.
public func mapSQL(_ transform: (String) throws -> String) rethrows -> SQLLiteral {
var result = self
result.sql = try transform(sql)
return result
}
}
extension SQLLiteral {
/// Returns the SQLLiteral produced by the concatenation of two literals.
///
/// let name = "O'Brien"
/// let selection: SQLLiteral = "SELECT * FROM player "
/// let condition: SQLLiteral = "WHERE name = \(name)"
/// let query = selection + condition
public static func + (lhs: SQLLiteral, rhs: SQLLiteral) -> SQLLiteral {
var result = lhs
result += rhs
return result
}
/// Appends an SQLLiteral to the receiver.
///
/// let name = "O'Brien"
/// var query: SQLLiteral = "SELECT * FROM player "
/// query += "WHERE name = \(name)"
public static func += (lhs: inout SQLLiteral, rhs: SQLLiteral) {
lhs.sql += rhs.sql
lhs.arguments += rhs.arguments
}
/// Appends an SQLLiteral to the receiver.
///
/// let name = "O'Brien"
/// var query: SQLLiteral = "SELECT * FROM player "
/// query.append(literal: "WHERE name = \(name)")
public mutating func append(literal sqlLiteral: SQLLiteral) {
self += sqlLiteral
}
/// Appends a plain SQL string to the receiver, and eventual arguments.
///
/// let name = "O'Brien"
/// var query: SQLLiteral = "SELECT * FROM player "
/// query.append(sql: "WHERE name = ?", arguments: [name])
public mutating func append(sql: String, arguments: StatementArguments = StatementArguments()) {
self += SQLLiteral(sql: sql, arguments: arguments)
}
}
extension Sequence where Element == SQLLiteral {
/// Returns the concatenated SQLLiteral of this sequence of literals,
/// inserting the given separator between each element.
///
/// let components: [SQLLiteral] = [
/// "UPDATE player",
/// "SET name = \(name)",
/// "WHERE id = \(id)"
/// ]
/// let query = components.joined(separator: " ")
public func joined(separator: String = "") -> SQLLiteral {
var sql = ""
var arguments = StatementArguments()
var first = true
for literal in self {
if first {
first = false
} else {
sql += separator
}
sql += literal.sql
arguments += literal.arguments
}
return SQLLiteral(sql: sql, arguments: arguments)
}
}
extension Collection where Element == SQLLiteral {
/// Returns the concatenated SQLLiteral of this collection of literals,
/// inserting the given separator between each element.
///
/// let components: [SQLLiteral] = [
/// "UPDATE player",
/// "SET name = \(name)",
/// "WHERE id = \(id)"
/// ]
/// let query = components.joined(separator: " ")
public func joined(separator: String = "") -> SQLLiteral {
let sql = map { $0.sql }.joined(separator: separator)
let arguments = reduce(into: StatementArguments()) { $0 += $1.arguments }
return SQLLiteral(sql: sql, arguments: arguments)
}
}
// MARK: - ExpressibleByStringInterpolation
#if swift(>=5.0)
extension SQLLiteral: ExpressibleByStringInterpolation {
/// :nodoc
public init(unicodeScalarLiteral: String) {
self.init(sql: unicodeScalarLiteral, arguments: [])
}
/// :nodoc:
public init(extendedGraphemeClusterLiteral: String) {
self.init(sql: extendedGraphemeClusterLiteral, arguments: [])
}
/// :nodoc:
public init(stringLiteral: String) {
self.init(sql: stringLiteral, arguments: [])
}
/// :nodoc:
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
self.init(sql: sqlInterpolation.sql, arguments: sqlInterpolation.arguments)
}
}
#endif
+167
View File
@@ -0,0 +1,167 @@
/// A FetchRequest built from raw SQL.
public struct SQLRequest<T> : FetchRequest {
/// There are two statement caches: one "public" for statements generated by
/// the user, and one "internal" for the statements generated by GRDB. Those
/// are separated so that GRDB has no opportunity to inadvertently modify
/// the arguments of user's cached statements.
enum Cache {
/// The public cache, for library user
case `public`
/// The internal cache, for GRDB
case `internal`
}
public typealias RowDecoder = T
/// The raw SQL query
///
/// let id = 42
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
/// request.sql // "SELECT * FROM player WHERE id = ?"
public var sql: String { return sqlLiteral.sql }
/// The request argument
///
/// let id = 42
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
/// request.arguments // [42]
public var arguments: StatementArguments { return sqlLiteral.arguments }
/// The request adapter
public var adapter: RowAdapter?
private var sqlLiteral: SQLLiteral
private let cache: Cache?
/// Creates a request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest<String>(sql: """
/// SELECT name FROM player
/// """)
/// let request = SQLRequest<Player>(sql: """
/// SELECT * FROM player WHERE id = ?
/// """, arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: A SQLRequest
public init(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(literal: SQLLiteral(sql: sql, arguments: arguments), adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates a request from an SQLLiteral, and optional row adapter.
///
/// let request = SQLRequest<String>(literal: SQLLiteral(sql: """
/// SELECT name FROM player
/// """))
/// let request = SQLRequest<Player>(literal: SQLLiteral(sql: """
/// SELECT * FROM player WHERE name = ?
/// """, arguments: ["O'Brien"]))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// let request = SQLRequest<Player>(literal: """
/// SELECT * FROM player WHERE name = \("O'brien")
/// """)
///
/// - parameters:
/// - sqlLiteral: An SQLLiteral.
/// - adapter: Optional RowAdapter.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: A SQLRequest
public init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates an SQL request from any other fetch request.
///
/// - parameters:
/// - db: A database connection.
/// - request: A request.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: An SQLRequest
public init<Request: FetchRequest>(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder {
let (statement, adapter) = try request.prepare(db)
self.init(literal: SQLLiteral(sql: statement.sql, arguments: statement.arguments), adapter: adapter, cached: cached)
}
/// Creates a request from an SQLLiteral, and optional row adapter.
///
/// let request = SQLRequest<String>(literal: SQLLiteral(sql: """
/// SELECT name FROM player
/// """))
/// let request = SQLRequest<Player>(literal: SQLLiteral(sql: """
/// SELECT * FROM player WHERE name = ?
/// """, arguments: ["O'Brien"]))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// let request = SQLRequest<Player>(literal: """
/// SELECT * FROM player WHERE name = \("O'brien")
/// """)
///
/// - parameters:
/// - sqlLiteral: An SQLLiteral.
/// - adapter: Optional RowAdapter.
/// - cache: The eventual cache
/// - returns: A SQLRequest
init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
self.sqlLiteral = sqlLiteral
self.adapter = adapter
self.cache = cache
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
///
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement: SelectStatement
switch cache {
case .none:
statement = try db.makeSelectStatement(sql: sqlLiteral.sql)
case .public?:
statement = try db.cachedSelectStatement(sql: sqlLiteral.sql)
case .internal?:
statement = try db.internalCachedSelectStatement(sql: sqlLiteral.sql)
}
try statement.setArgumentsWithValidation(sqlLiteral.arguments)
return (statement, adapter)
}
}
#if swift(>=5.0)
extension SQLRequest: ExpressibleByStringInterpolation {
/// :nodoc
public init(unicodeScalarLiteral: String) {
self.init(sql: unicodeScalarLiteral)
}
/// :nodoc:
public init(extendedGraphemeClusterLiteral: String) {
self.init(sql: extendedGraphemeClusterLiteral)
}
/// :nodoc:
public init(stringLiteral: String) {
self.init(sql: stringLiteral)
}
/// :nodoc:
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
self.init(literal: SQLLiteral(stringInterpolation: sqlInterpolation))
}
}
#endif
+19 -19
View File
@@ -101,7 +101,7 @@ public class Statement {
// MARK: Arguments
var argumentsNeedValidation = true
var _arguments: StatementArguments = []
var _arguments = StatementArguments()
lazy var sqliteArgumentCount: Int = {
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
@@ -284,7 +284,7 @@ extension StatementProtocol where Self: Statement {
/// You create SelectStatement with the Database.makeSelectStatement() method:
///
/// try dbQueue.read { db in
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
/// }
@@ -367,7 +367,7 @@ public final class SelectStatement : Statement {
/// For example:
///
/// try dbQueue.read { db in
/// let statement = db.makeSelectStatement("SELECT * FROM player")
/// let statement = db.makeSelectStatement(sql: "SELECT * FROM player")
/// let cursor: StatementCursor = statement.makeCursor()
/// }
public final class StatementCursor: Cursor {
@@ -416,7 +416,7 @@ public final class StatementCursor: Cursor {
/// You create UpdateStatement with the Database.makeUpdateStatement() method:
///
/// try dbQueue.inTransaction { db in
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
/// return .commit
@@ -470,7 +470,7 @@ public final class UpdateStatement : Statement {
/// Executes the SQL query.
///
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(arguments: StatementArguments? = nil) throws {
SchedulingWatchdog.preconditionValidQueue(database)
@@ -484,17 +484,17 @@ public final class UpdateStatement : Statement {
// The statement did return a row, and the user ignores the
// content of this row:
//
// try db.execute("SELECT ...")
// try db.execute(sql: "SELECT ...")
//
// That's OK: maybe the selected rows perform side effects.
// For example:
//
// try db.execute("SELECT sqlcipher_export(...)")
// try db.execute(sql: "SELECT sqlcipher_export(...)")
//
// Or maybe the user doesn't know that the executed statement
// return rows (https://github.com/groue/GRDB.swift/issues/15);
//
// try db.execute("PRAGMA journal_mode=WAL")
// try db.execute(sql: "PRAGMA journal_mode=WAL")
//
// It is thus important that we consume *all* rows.
continue
@@ -531,12 +531,12 @@ public final class UpdateStatement : Statement {
/// To fill question marks placeholders, feed StatementArguments with an array:
///
/// db.execute(
/// "INSERT ... (?, ?)",
/// sql: "INSERT ... (?, ?)",
/// arguments: StatementArguments(["Arthur", 41]))
///
/// // Array literals are automatically converted:
/// db.execute(
/// "INSERT ... (?, ?)",
/// sql: "INSERT ... (?, ?)",
/// arguments: ["Arthur", 41])
///
/// ## Named Arguments
@@ -544,12 +544,12 @@ public final class UpdateStatement : Statement {
/// To fill named arguments, feed StatementArguments with a dictionary:
///
/// db.execute(
/// "INSERT ... (:name, :score)",
/// sql: "INSERT ... (:name, :score)",
/// arguments: StatementArguments(["name": "Arthur", "score": 41]))
///
/// // Dictionary literals are automatically converted:
/// db.execute(
/// "INSERT ... (:name, :score)",
/// sql: "INSERT ... (:name, :score)",
/// arguments: ["name": "Arthur", "score": 41])
///
/// ## Concatenating Arguments
@@ -559,7 +559,7 @@ public final class UpdateStatement : Statement {
///
/// var arguments: StatementArguments = ["Arthur"]
/// arguments += [41]
/// db.execute("INSERT ... (?, ?)", arguments: arguments)
/// db.execute(sql: "INSERT ... (?, ?)", arguments: arguments)
///
/// `+` and `+=` operators consider that overriding named arguments is a
/// programmer error:
@@ -582,7 +582,7 @@ public final class UpdateStatement : Statement {
///
/// let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
/// var arguments: StatementArguments = [1, 2, "bar"] + ["foo": "foo"]
/// let row = try Row.fetchOne(db, sql, arguments: arguments)!
/// let row = try Row.fetchOne(db, sql: sql, arguments: arguments)!
/// print(row)
/// // Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
///
@@ -604,7 +604,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
// MARK: Empty Arguments
/// Creates empty StatementArguments.
init() {
public init() {
}
// MARK: Positional Arguments
@@ -612,7 +612,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
/// Creates statement arguments from a sequence of optional values.
///
/// let values: [DatabaseValueConvertible?] = ["foo", 1, nil]
/// db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values))
/// db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
/// - returns: A StatementArguments.
@@ -623,7 +623,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
/// Creates statement arguments from a sequence of optional values.
///
/// let values: [String] = ["foo", "bar"]
/// db.execute("INSERT ... (?,?)", arguments: StatementArguments(values))
/// db.execute(sql: "INSERT ... (?,?)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
/// - returns: A StatementArguments.
@@ -654,7 +654,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
/// such as a dictionary.
///
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
/// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of (key, value) pairs
/// - returns: A StatementArguments.
@@ -666,7 +666,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
/// as a dictionary.
///
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
/// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of (key, value) pairs
/// - returns: A StatementArguments.
+32 -32
View File
@@ -13,11 +13,11 @@
/// DatabaseValueConvertible. GRDB will then automatically apply the
/// optimization whenever direct access to SQLite is possible:
///
/// let rows = Row.fetchCursor(db, "SELECT ...")
/// let rows = Row.fetchCursor(db, sql: "SELECT ...")
/// while let row = try rows.next() {
/// let int: Int = row[0] // there
/// }
/// let ints = Int.fetchAll(db, "SELECT ...") // there
/// let ints = Int.fetchAll(db, sql: "SELECT ...") // there
/// struct Player {
/// init(row: Row) {
/// name = row["name"] // there
@@ -54,7 +54,7 @@ public protocol StatementColumnConvertible {
/// For example:
///
/// try dbQueue.read { db in
/// let names: ColumnCursor<String> = try String.fetchCursor(db, "SELECT name FROM player")
/// let names: ColumnCursor<String> = try String.fetchCursor(db, sql: "SELECT name FROM player")
/// while let name = names.next() { // String
/// print(name)
/// }
@@ -107,7 +107,7 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
/// For example:
///
/// try dbQueue.read { db in
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, "SELECT email FROM player")
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, sql: "SELECT email FROM player")
/// while let email = emails.next() { // String?
/// print(email ?? "<NULL>")
/// }
@@ -168,7 +168,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns a cursor over values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try String.fetchCursor(statement) // Cursor of String
/// while let name = try names.next() { // String
/// ...
@@ -191,7 +191,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try String.fetchAll(statement) // [String]
///
/// - parameters:
@@ -206,7 +206,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns a single value fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let name = try String.fetchOne(statement) // String?
///
/// - parameters:
@@ -228,7 +228,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns a cursor over values fetched from an SQL query.
///
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
/// let names = try String.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String
/// while let name = try names.next() { // String
/// ...
/// }
@@ -241,42 +241,42 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from an SQL query.
///
/// let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
/// let name = try String.fetchOne(db, sql: "SELECT name FROM ...") // String?
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -393,10 +393,10 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// Swift's Optional comes with built-in methods that allow to fetch cursors
/// and arrays of optional DatabaseValueConvertible:
///
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
/// try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?]
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
///
@@ -407,7 +407,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// Returns a cursor over optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
@@ -430,7 +430,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// Returns an array of optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try Optional<String>.fetchAll(statement) // [String?]
///
/// - parameters:
@@ -450,7 +450,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// Returns a cursor over optional values fetched from an SQL query.
///
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
/// let names = try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
@@ -463,27 +463,27 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of optional values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String?]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - parameter arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -616,11 +616,11 @@ extension DatabaseCollation {
/// You can use it when creating database tables:
///
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
/// dbQueue.execute(
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
/// dbQueue.execute(sql: """
/// CREATE TABLE players (
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let unicodeCompare = DatabaseCollation("swiftCompare") { (lhs, rhs) in
return (lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending)
}
@@ -634,11 +634,11 @@ extension DatabaseCollation {
/// You can use it when creating database tables:
///
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
/// dbQueue.execute(
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
/// dbQueue.execute(sql: """
/// CREATE TABLE players (
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let caseInsensitiveCompare = DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in
return lhs.caseInsensitiveCompare(rhs)
}
@@ -652,11 +652,11 @@ extension DatabaseCollation {
/// You can use it when creating database tables:
///
/// let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name
/// dbQueue.execute(
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
/// dbQueue.execute(sql: """
/// CREATE TABLE players (
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let localizedCaseInsensitiveCompare = DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in
return lhs.localizedCaseInsensitiveCompare(rhs)
}
@@ -670,11 +670,11 @@ extension DatabaseCollation {
/// You can use it when creating database tables:
///
/// let collationName = DatabaseCollation.localizedCompare.name
/// dbQueue.execute(
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
/// dbQueue.execute(sql: """
/// CREATE TABLE players (
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let localizedCompare = DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in
return lhs.localizedCompare(rhs)
}
@@ -688,11 +688,11 @@ extension DatabaseCollation {
/// You can use it when creating database tables:
///
/// let collationName = DatabaseCollation.localizedStandardCompare.name
/// dbQueue.execute(
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
/// dbQueue.execute(sql: """
/// CREATE TABLE players (
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let localizedStandardCompare = DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in
return lhs.localizedStandardCompare(rhs)
}
+9 -9
View File
@@ -95,11 +95,11 @@ extension Database {
/// let observer = MyObserver()
/// dbQueue.add(transactionObserver: observer)
/// dbQueue.inDatabase { db in
/// try db.execute("BEGIN TRANSACTION")
/// try db.execute(sql: "BEGIN TRANSACTION")
///
/// Then a statement is executed:
///
/// try db.execute("INSERT INTO document ...")
/// try db.execute(sql: "INSERT INTO document ...")
///
/// The observation process starts when the statement is *compiled*:
/// sqlite3_set_authorizer tells that the statement performs insertion into the
@@ -117,7 +117,7 @@ extension Database {
///
/// Now a savepoint is started:
///
/// try db.execute("SAVEPOINT foo")
/// try db.execute(sql: "SAVEPOINT foo")
///
/// Statement compilation has sqlite3_set_authorizer tell that this statement
/// begins a "foo" savepoint.
@@ -128,7 +128,7 @@ extension Database {
///
/// Then another statement is executed:
///
/// try db.execute("INSERT INTO document ...")
/// try db.execute(sql: "INSERT INTO document ...")
///
/// This time, when the statement is *executed* and SQLite tells that a row has
/// been inserted, the broker buffers the change event instead of immediately
@@ -138,7 +138,7 @@ extension Database {
///
/// The savepoint is released:
///
/// try db.execute("RELEASE SAVEPOINT foo")
/// try db.execute(sql: "RELEASE SAVEPOINT foo")
///
/// Statement compilation has sqlite3_set_authorizer tell that this statement
/// releases the "foo" savepoint.
@@ -149,7 +149,7 @@ extension Database {
///
/// Finally the transaction is committed:
///
/// try db.execute("COMMIT")
/// try db.execute(sql: "COMMIT")
///
/// During the statement *execution*, SQlite tells the broker that the
/// transaction is about to be committed through sqlite3_commit_hook. The broker
@@ -440,8 +440,8 @@ class DatabaseObservationBroker {
// SQLite, no transaction at all has started, and sqlite3_commit_hook
// was not triggered:
//
// try db.execute("BEGIN DEFERRED TRANSACTION")
// try db.execute("COMMIT") // <- no sqlite3_commit_hook callback invocation
// try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
// try db.execute(sql: "COMMIT") // <- no sqlite3_commit_hook callback invocation
//
// Should we tell transaction observers of this transaction, or not?
// The code says that a transaction was open, but SQLite says the
@@ -517,7 +517,7 @@ class DatabaseObservationBroker {
//
// But we have to deal with a particular case:
//
// let journalMode = String.fetchOne(db, "PRAGMA journal_mode = wal")
// let journalMode = String.fetchOne(db, sql: "PRAGMA journal_mode = wal")
//
// It runs a SelectStatement, not an UpdateStatement. But this not why
// this case is particular. What is unexpected is that it triggers
+2 -2
View File
@@ -19,8 +19,8 @@ public struct FTS3Pattern {
// that pattern.
do {
try DatabaseQueue().inDatabase { db in
try db.execute("CREATE VIRTUAL TABLE documents USING fts3()")
try db.execute("SELECT * FROM documents WHERE content MATCH ?", arguments: [rawPattern])
try db.execute(sql: "CREATE VIRTUAL TABLE documents USING fts3()")
try db.execute(sql: "SELECT * FROM documents WHERE content MATCH ?", arguments: [rawPattern])
}
} catch let error as DatabaseError {
// Remove private SQL & arguments from the thrown error
+2 -2
View File
@@ -116,8 +116,8 @@ public struct FTS3TokenizerDescriptor {
}
let tokenizerSQL = tokenizerChunks.joined(separator: ", ")
// Assume fts3tokenize virtual table in an in-memory database always succeeds
try! db.execute("CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))")
return try! String.fetchAll(db, "SELECT token FROM tokens WHERE input = ? ORDER BY position", arguments: [string])
try! db.execute(sql: "CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))")
return try! String.fetchAll(db, sql: "SELECT token FROM tokens WHERE input = ? ORDER BY position", arguments: [string])
}
}
}
+3 -3
View File
@@ -110,7 +110,7 @@ public struct FTS4 : VirtualTableModule {
let oldRowID = "old.\(rowIDColumn.quotedDatabaseIdentifier)"
try db.execute("""
try db.execute(sql: """
CREATE TRIGGER \("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
END;
@@ -127,7 +127,7 @@ public struct FTS4 : VirtualTableModule {
// https://www.sqlite.org/fts3.html#*fts4rebuidcmd
try db.execute("INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')")
try db.execute(sql: "INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')")
}
}
}
@@ -318,7 +318,7 @@ public final class FTS4ColumnDefinition {
extension Database {
/// Deletes the synchronization triggers for a synchronized FTS4 table
public func dropFTS4SynchronizationTriggers(forTable tableName: String) throws {
try execute("""
try execute(sql: """
DROP TRIGGER IF EXISTS \("__\(tableName)_bu".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_bd".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier);
+10 -10
View File
@@ -49,27 +49,27 @@
}
if let tokenizer = definition.tokenizer {
arguments.append("tokenize=\(tokenizer.components.joined(separator: " ").sqlExpression.sql)")
arguments.append("tokenize=\(tokenizer.components.joined(separator: " ").sqlExpression.quotedSQL())")
}
switch definition.contentMode {
case .raw(let content, let contentRowID):
if let content = content {
arguments.append("content=\(content.sqlExpression.sql)")
arguments.append("content=\(content.sqlExpression.quotedSQL())")
}
if let contentRowID = contentRowID {
arguments.append("content_rowid=\(contentRowID.sqlExpression.sql)")
arguments.append("content_rowid=\(contentRowID.sqlExpression.quotedSQL())")
}
case .synchronized(let contentTable):
arguments.append("content=\(contentTable.sqlExpression.sql)")
arguments.append("content=\(contentTable.sqlExpression.quotedSQL())")
if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn {
arguments.append("content_rowid=\(rowIDColumn.sqlExpression.sql)")
arguments.append("content_rowid=\(rowIDColumn.sqlExpression.quotedSQL())")
}
}
if let prefixes = definition.prefixes {
arguments.append("prefix=\(prefixes.sorted().map { "\($0)" }.joined(separator: " ").sqlExpression.sql)")
arguments.append("prefix=\(prefixes.sorted().map { "\($0)" }.joined(separator: " ").sqlExpression.quotedSQL())")
}
if let columnSize = definition.columnSize {
@@ -110,7 +110,7 @@
.map { "old.\($0.quotedDatabaseIdentifier)" }
.joined(separator: ", ")
try db.execute("""
try db.execute(sql: """
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
@@ -125,7 +125,7 @@
// https://sqlite.org/fts5.html#the_rebuild_command
try db.execute("INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')")
try db.execute(sql: "INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')")
}
}
@@ -156,7 +156,7 @@
}
private static func api_v1(_ db: Database) -> UnsafePointer<fts5_api> {
guard let data = try! Data.fetchOne(db, "SELECT fts5()") else {
guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else {
fatalError("FTS5 is not available")
}
#if swift(>=5.0)
@@ -371,7 +371,7 @@
extension Database {
/// Deletes the synchronization triggers for a synchronized FTS5 table
public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws {
try execute("""
try execute(sql: """
DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_ad".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier);
+1 -1
View File
@@ -74,7 +74,7 @@
}
}
}
try db.makeSelectStatement("SELECT * FROM document WHERE document MATCH ?")
try db.makeSelectStatement(sql: "SELECT * FROM document WHERE document MATCH ?")
.makeCursor(arguments: [rawPattern])
.next() // error on next() for invalid patterns
}
+17 -3
View File
@@ -60,7 +60,7 @@
if separators.isEmpty {
return FTS5TokenizerDescriptor(components: ["ascii"])
} else {
return FTS5TokenizerDescriptor(components: ["ascii", "separators", separators.map { String($0) }.joined(separator: "").sqlExpression.sql])
return FTS5TokenizerDescriptor(components: ["ascii", "separators", separators.map { String($0) }.joined(separator: "").sqlExpression.quotedSQL()])
}
}
@@ -106,11 +106,25 @@
}
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
components.append(contentsOf: ["separators", separators.sorted().map { String($0) }.joined(separator: "").sqlExpression.sql])
components.append(contentsOf: [
"separators",
separators
.sorted()
.map { String($0) }
.joined(separator: "")
.sqlExpression
.quotedSQL()])
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
components.append(contentsOf: ["tokenchars", tokenCharacters.sorted().map { String($0) }.joined(separator: "").sqlExpression.sql])
components.append(contentsOf: [
"tokenchars",
tokenCharacters
.sorted()
.map { String($0) }
.joined(separator: "")
.sqlExpression
.quotedSQL()])
}
return FTS5TokenizerDescriptor(components: components)
}
+85
View File
@@ -1,3 +1,5 @@
import Dispatch
// Fixits for changes introduced by GRDB 4.0.0
extension Cursor {
@@ -23,3 +25,86 @@ public typealias ColumnCursor<Value: DatabaseValueConvertible & StatementColumnC
@available(*, unavailable, renamed: "FastNullableDatabaseValueCursor")
public typealias NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastNullableDatabaseValueCursor<Value>
extension Database {
@available(*, unavailable, renamed: "execute(sql:arguments:)")
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws { preconditionFailure() }
@available(*, unavailable, renamed: "makeSelectStatement(sql:)")
public func makeSelectStatement(_ sql: String) throws -> SelectStatement { preconditionFailure() }
@available(*, unavailable, renamed: "cachedSelectStatement(sql:)")
public func cachedSelectStatement(_ sql: String) throws -> SelectStatement { preconditionFailure() }
@available(*, unavailable, renamed: "makeUpdateStatement(sql:)")
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement { preconditionFailure() }
@available(*, unavailable, renamed: "cachedUpdateStatement(sql:)")
public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement { preconditionFailure() }
}
extension DatabaseValueConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> { preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> { preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { preconditionFailure() }
}
extension Row {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor { preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { preconditionFailure() }
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> { preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> { preconditionFailure() }
}
extension FetchableRecord {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> { preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { preconditionFailure() }
}
extension SQLRequest {
@available(*, unavailable, renamed: "init(sql:arguments:adapter:cached:)")
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) { preconditionFailure() }
}
extension SQLExpressionLiteral {
@available(*, unavailable, renamed: "init(sql:arguments:)")
public init(_ sql: String, arguments: StatementArguments? = nil) { preconditionFailure() }
}
extension SQLExpression {
@available(*, unavailable, message: "Use sqlLiteral property instead")
public var literal: SQLExpressionLiteral { preconditionFailure() }
}
+4 -4
View File
@@ -100,7 +100,7 @@ public struct DatabaseMigrator {
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// }
/// try db.execute("INSERT INTO new_player SELECT * FROM player")
/// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
/// try db.drop(table: "player")
/// try db.rename(table: "new_player", to: "player")
/// }
@@ -128,7 +128,7 @@ public struct DatabaseMigrator {
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// }
/// try db.execute("INSERT INTO new_player SELECT * FROM player")
/// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
/// try db.drop(table: "player")
/// try db.rename(table: "new_player", to: "player")
/// }
@@ -237,11 +237,11 @@ public struct DatabaseMigrator {
}
private func setupMigrations(_ db: Database) throws {
try db.execute("CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
}
private func appliedIdentifiers(_ db: Database) throws -> Set<String> {
return try Set(String.fetchAll(db, "SELECT identifier FROM grdb_migrations"))
return try Set(String.fetchAll(db, sql: "SELECT identifier FROM grdb_migrations"))
}
private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws {
+5 -5
View File
@@ -28,7 +28,7 @@ struct Migration {
#endif
func run(_ db: Database) throws {
if try disabledForeignKeyChecks && (Bool.fetchOne(db, "PRAGMA foreign_keys") ?? false) {
if try disabledForeignKeyChecks && (Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false) {
try runWithDisabledForeignKeys(db)
} else {
try runWithoutDisabledForeignKeys(db)
@@ -50,7 +50,7 @@ struct Migration {
//
// > 1. If foreign key constraints are enabled, disable them using
// > PRAGMA foreign_keys=OFF.
try db.execute("PRAGMA foreign_keys = OFF")
try db.execute(sql: "PRAGMA foreign_keys = OFF")
// > 2. Start a transaction.
try db.inTransaction(.immediate) {
@@ -60,7 +60,7 @@ struct Migration {
// > 10. If foreign key constraints were originally enabled then run PRAGMA
// > foreign_key_check to verify that the schema change did not break any foreign key
// > constraints.
if try Row.fetchOne(db, "PRAGMA foreign_key_check") != nil {
if try Row.fetchOne(db, sql: "PRAGMA foreign_key_check") != nil {
// https://www.sqlite.org/pragma.html#pragma_foreign_key_check
//
// PRAGMA foreign_key_check does not return an error,
@@ -76,10 +76,10 @@ struct Migration {
}
// > 12. If foreign keys constraints were originally enabled, reenable them now.
try db.execute("PRAGMA foreign_keys = ON")
try db.execute(sql: "PRAGMA foreign_keys = ON")
}
private func insertAppliedIdentifier(_ db: Database) throws {
try db.execute("INSERT INTO grdb_migrations (identifier) VALUES (?)", arguments: [identifier])
try db.execute(sql: "INSERT INTO grdb_migrations (identifier) VALUES (?)", arguments: [identifier])
}
}
+97 -10
View File
@@ -106,8 +106,39 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest {
/// let request = Player.all().select(sql: "max(score)", as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return select(SQLSelectionLiteral(sql, arguments: arguments), as: type)
public func select<RowDecoder>(sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type)
}
/// Creates a request which selects an SQL *literal*, and fetches values of
/// type *type*.
///
/// try dbQueue.read { db in
/// // SELECT IFNULL(name, 'Anonymous') FROM player WHERE id = 42
/// let request = Player.
/// .filter(primaryKey: 42)
/// .select(
/// SQLLiteral(
/// sql: "IFNULL(name, ?)",
/// arguments: ["Anonymous"]),
/// as: String.self)
/// let name: String? = try request.fetchOne(db)
/// }
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// try dbQueue.read { db in
/// // SELECT IFNULL(name, 'Anonymous') FROM player WHERE id = 42
/// let request = Player.
/// .filter(primaryKey: 42)
/// .select(
/// literal: "IFNULL(name, \("Anonymous"))",
/// as: String.self)
/// let name: String? = try request.fetchOne(db)
/// }
public func select<RowDecoder>(literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return select(SQLSelectionLiteral(literal: sqlLiteral), as: type)
}
/// Creates a request which appends *selection*.
@@ -340,8 +371,16 @@ extension TableRecord {
///
/// // SELECT id, email FROM player
/// let request = Player.select(sql: "id, email")
public static func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
return all().select(sql: sql, arguments: arguments)
public static func select(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest<Self> {
return select(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request which selects an SQL *literal*.
///
/// // SELECT id, email FROM player
/// let request = Player.select(literal: SQLLiteral(sql: "id, email"))
public static func select(literal sqlLiteral: SQLLiteral) -> QueryInterfaceRequest<Self> {
return all().select(literal: sqlLiteral)
}
/// Creates a request which selects *selection*, and fetches values of
@@ -376,10 +415,22 @@ extension TableRecord {
/// let request = Player.select(sql: "max(score)", as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public static func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return all().select(sql: sql, arguments: arguments, as: type)
public static func select<RowDecoder>(sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return all().select(literal: SQLLiteral(sql: sql, arguments: arguments), as: type)
}
/// Creates a request which selects an SQL *literal*, and fetches values of
/// type *type*.
///
/// try dbQueue.read { db in
/// // SELECT max(score) FROM player
/// let request = Player.select(literal: SQLLiteral(sql: "max(score)"), as: Int.self)
/// let maxScore: Int? = try request.fetchOne(db)
/// }
public static func select<RowDecoder>(literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
return all().select(literal: sqlLiteral, as: type)
}
/// Creates a request with the provided *predicate*.
///
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
@@ -454,10 +505,28 @@ extension TableRecord {
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
return all().filter(sql: sql, arguments: arguments)
public static func filter(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest<Self> {
return filter(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request with the provided *predicate*.
///
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
/// let request = Player.filter(literal: SQLLiteral(sql: "email = ?", arguments: ["arthur@example.com"]))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// let request = Player.filter(literal: "name = \("O'Brien"))
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func filter(literal sqlLiteral: SQLLiteral) -> QueryInterfaceRequest<Self> {
// NOT TESTED
return all().filter(literal: sqlLiteral)
}
/// Creates a request sorted according to the
/// provided *orderings*.
///
@@ -507,10 +576,28 @@ extension TableRecord {
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self> {
return all().order(sql: sql, arguments: arguments)
public static func order(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest<Self> {
return all().order(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request sorted according to an SQL *literal*.
///
/// // SELECT * FROM player ORDER BY name
/// let request = Player.order(literal: SQLLiteral(sql: "name"))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// // SELECT * FROM player ORDER BY name
/// let request = Player.order(literal: "name"))
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func order(literal sqlLiteral: SQLLiteral) -> QueryInterfaceRequest<Self> {
return all().order(literal: sqlLiteral)
}
/// Creates a request which fetches *limit* rows, starting at
/// *offset*.
///
+97 -22
View File
@@ -51,8 +51,38 @@ extension SelectionRequest {
/// request
/// .select(sql: "id")
/// .select(sql: "email")
public func select(sql: String, arguments: StatementArguments? = nil) -> Self {
return select(SQLSelectionLiteral(sql, arguments: arguments))
public func select(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
return select(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request which selects an SQL *literal*.
///
/// // SELECT id, email, score + 1000 FROM player
/// let bonus = 1000
/// var request = Player.all()
/// request = request.select(literal: SQLLiteral(sql: """
/// id, email, score + ?
/// """, arguments: [bonus]))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// // SELECT id, email, score + 1000 FROM player
/// let bonus = 1000
/// var request = Player.all()
/// request = request.select(literal: """
/// id, email, score + \(bonus)
/// """)
///
/// Any previous selection is replaced:
///
/// // SELECT email FROM player
/// request
/// .select(...)
/// .select(literal: SQLLiteral(sql: "email"))
public func select(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
return select(SQLSelectionLiteral(literal: sqlLiteral))
}
}
@@ -91,10 +121,29 @@ extension FilteredRequest {
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
/// var request = Player.all()
/// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"])
public func filter(sql: String, arguments: StatementArguments? = nil) -> Self {
return filter(SQLExpressionLiteral(sql, arguments: arguments))
public func filter(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
return filter(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request with the provided *predicate* added to the
/// eventual set of already applied predicates.
///
/// // SELECT * FROM player WHERE email = 'arthur@example.com'
/// var request = Player.all()
/// request = request.filter(literal: SQLLiteral(sql: """
/// email = ?
/// """, arguments: ["arthur@example.com"])
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// var request = Player.all()
/// request = request.filter(literal: "name = \("O'Brien")")
public func filter(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
return filter(SQLExpressionLiteral(literal: sqlLiteral))
}
/// Creates a request that matches nothing.
///
/// // SELECT * FROM player WHERE 0
@@ -268,24 +317,35 @@ extension AggregatingRequest {
}
/// Creates a request with a new grouping.
public func group(sql: String, arguments: StatementArguments? = nil) -> Self {
public func group(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
return group(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request with a new grouping.
public func group(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
// This "expression" is not a real expression. We support raw sql which
// actually contains several expressions:
//
// request = Player.group(sql: "teamId, level")
//
// This is why we use the "unsafe" flag, so that the SQLExpressionLiteral
// does not output its safe wrapping parenthesis, and generates
// invalid SQL.
var expression = SQLExpressionLiteral(sql, arguments: arguments)
expression.unsafeRaw = true
return group(expression)
// This is why we use the "unsafeLiteral" initializer, so that the
// SQLExpressionLiteral does not wrap input in parentheses, and
// generates invalid SQL `GROUP BY (teamId, level)`.
return group(SQLExpressionLiteral(unsafeLiteral: sqlLiteral))
}
/// Creates a request with the provided *sql* added to the
/// eventual set of already applied predicates.
public func having(sql: String, arguments: StatementArguments? = nil) -> Self {
return having(SQLExpressionLiteral(sql, arguments: arguments))
public func having(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
return having(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request with the provided *sql* added to the
/// eventual set of already applied predicates.
public func having(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
return having(SQLExpressionLiteral(literal: sqlLiteral))
}
}
@@ -362,7 +422,7 @@ extension OrderedRequest {
return order { _ in orderings }
}
/// Creates a request with the provided *sql* used for sorting.
/// Creates a request sorted according to *sql*.
///
/// // SELECT * FROM player ORDER BY name
/// var request = Player.all()
@@ -374,18 +434,33 @@ extension OrderedRequest {
/// request
/// .order(sql: "email")
/// .order(sql: "name")
public func order(sql: String, arguments: StatementArguments? = nil) -> Self {
public func order(sql: String, arguments: StatementArguments = StatementArguments()) -> Self {
return order(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Creates a request sorted according to an SQL *literal*.
///
/// // SELECT * FROM player ORDER BY name
/// var request = Player.all()
/// request = request.order(sql: "name")
///
/// Any previous ordering is replaced:
///
/// // SELECT * FROM player ORDER BY name
/// request
/// .order(sql: "email")
/// .order(sql: "name")
public func order(literal sqlLiteral: SQLLiteral) -> Self {
// NOT TESTED
// This "expression" is not a real expression. We support raw sql which
// actually contains several expressions:
//
// request = Player.order(sql: "teamId, level")
//
// This is why we use the "unsafe" flag, so that the SQLExpressionLiteral
// does not output its safe wrapping parenthesis, and generates
// invalid SQL.
var expression = SQLExpressionLiteral(sql, arguments: arguments)
expression.unsafeRaw = true
return order([expression])
// This is why we use the "unsafeLiteral" initializer, so that the
// SQLExpressionLiteral does not wrap input in parentheses, and
// generates invalid SQL `ORDER BY (teamId, level)`.
return order(SQLExpressionLiteral(unsafeLiteral: sqlLiteral))
}
}
@@ -1,22 +1,21 @@
// MARK: - SQLExpression
extension SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Converts an expression to an SQLExpressionLiteral
/// Converts an expression to an SQLLiteral
///
/// :nodoc:
public var literal: SQLExpressionLiteral {
public var sqlLiteral: SQLLiteral {
var context = SQLGenerationContext.literalGenerationContext(withArguments: true)
let sql = expressionSQL(&context)
return SQLExpressionLiteral(sql, arguments: context.arguments)
return SQLLiteral(sql: sql, arguments: context.arguments!)
}
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
///
/// "foo'bar".databaseValue.sql // "'foo''bar'""
var sql: String {
/// "foo'bar".databaseValue.quotedSQL() // "'foo''bar'""
func quotedSQL() -> String {
var context = SQLGenerationContext.literalGenerationContext(withArguments: false)
return expressionSQL(&context)
}
@@ -28,57 +27,61 @@ extension SQLExpression {
///
/// SQLExpressionLiteral is an expression built from a raw SQL snippet.
///
/// SQLExpressionLiteral("1 + 2")
/// SQLExpressionLiteral(sql: "1 + 2")
///
/// The SQL literal may contain `?` and colon-prefixed arguments:
///
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
/// SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2])
/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])
public struct SQLExpressionLiteral : SQLExpression {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The SQL literal
public let sql: String
private let sqlLiteral: SQLLiteral
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Eventual arguments that feed the `?` and colon-prefixed arguments in the
/// SQL literal
public let arguments: StatementArguments?
/// If safe, an SQLExpressionLiteral("foo") wraps itself in parenthesis,
/// and outputs "(foo)" in SQL queries. This avoids any bug due to operator
/// precedence. When unsafe, the expression literal does not wrap itself
/// in parenthesis and outputs its raw sql.
var unsafeRaw: Bool = false
public var sql: String { return sqlLiteral.sql }
public var arguments: StatementArguments { return sqlLiteral.arguments }
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates an SQL literal expression.
///
/// SQLExpressionLiteral("1 + 2")
/// SQLExpressionLiteral("? + ?", arguments: [1, 2])
/// SQLExpressionLiteral(":one + :two", arguments: ["one": 1, "two": 2])
public init(_ sql: String, arguments: StatementArguments? = nil) {
self.sql = sql
self.arguments = arguments
/// SQLExpressionLiteral(sql: "1 + 2")
/// SQLExpressionLiteral(sql: "? + ?", arguments: [1, 2])
/// SQLExpressionLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2])
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
self.init(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Creates an SQL literal expression.
///
/// SQLExpressionLiteral(literal: SQLLiteral(sql: "1 + 2")
/// SQLExpressionLiteral(literal: SQLLiteral(sql: "? + ?", arguments: [1, 2]))
/// SQLExpressionLiteral(literal: SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// SQLExpressionLiteral(literal: "\(1) + \(2)")
public init(literal sqlLiteral: SQLLiteral) {
self.init(unsafeLiteral: sqlLiteral.mapSQL { "(\($0))" })
}
/// Creates an SQL literal expression without wrapping the SQL literal
/// inside parentheses. It is unsafe because the result expression can not
/// be safely composed with other expressions.
init(unsafeLiteral sqlLiteral: SQLLiteral) {
self.sqlLiteral = sqlLiteral
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func expressionSQL(_ context: inout SQLGenerationContext) -> String {
if let arguments = arguments {
if context.appendArguments(arguments) == false {
// GRDB limitation: we don't know how to look for `?` in sql and
// replace them with with literals.
fatalError("Not implemented")
}
}
if unsafeRaw {
return sql
} else {
return "(" + sql + ")"
if context.append(arguments: sqlLiteral.arguments) == false {
// GRDB limitation: we don't know how to look for `?` in sql and
// replace them with with literals.
fatalError("Not implemented")
}
return sqlLiteral.sql
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -5,11 +5,12 @@
///
/// :nodoc:
public struct SQLGenerationContext {
private(set) var arguments: StatementArguments?
var arguments: StatementArguments?
private var resolvedNames: [TableAlias: String]
private var qualifierNeeded: Bool
/// Used for SQLExpression -> SQLExpressionLiteral conversion
/// and SQLInterpolation
static func literalGenerationContext(withArguments: Bool) -> SQLGenerationContext {
return SQLGenerationContext(
arguments: withArguments ? [] : nil,
@@ -26,7 +27,7 @@ public struct SQLGenerationContext {
}
/// Used for TableRecord.selectionSQL
static func recordSelectionGenerationContext(alias: TableAlias) -> SQLGenerationContext {
static func recordSelectionGenerationContext() -> SQLGenerationContext {
return SQLGenerationContext(
arguments: nil,
resolvedNames: [:],
@@ -34,7 +35,10 @@ public struct SQLGenerationContext {
}
/// Returns whether arguments could be appended
mutating func appendArguments(_ newArguments: StatementArguments) -> Bool {
mutating func append(arguments newArguments: StatementArguments) -> Bool {
if newArguments.isEmpty {
return true
}
guard let arguments = arguments else {
return false
}
@@ -0,0 +1,140 @@
#if swift(>=5.0)
/// :nodoc:
extension SQLInterpolation {
/// Appends the table name of the record type.
///
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = "SELECT * FROM \(Player.self)"
public mutating func appendInterpolation<T: TableRecord>(_ table: T.Type) {
sql += table.databaseTableName.quotedDatabaseIdentifier
}
/// Appends the selectable SQL.
///
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = """
/// SELECT \(AllColumns()) FROM player
/// """
public mutating func appendInterpolation(_ selection: SQLSelectable) {
sql += selection.resultColumnSQL(&context)
}
/// Appends the expression SQL.
///
/// // SELECT name FROM player
/// let request: SQLRequest<String> = """
/// SELECT \(Column("name")) FROM player
/// """
public mutating func appendInterpolation(_ expressible: SQLExpressible & SQLSelectable & SQLOrderingTerm) {
sql += expressible.sqlExpression.expressionSQL(&context)
}
/// Appends the name of the coding key.
///
/// // SELECT name FROM player
/// let request: SQLRequest<String> = "
/// SELECT \(CodingKey.name) FROM player
/// """
public mutating func appendInterpolation(_ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey) {
sql += codingKey.sqlExpression.expressionSQL(&context)
}
/// Appends the expression SQL, or NULL if it is nil.
///
/// // SELECT score + ? FROM player
/// let bonus = 1000
/// let request: SQLRequest<Int> = """
/// SELECT score + \(bonus) FROM player
/// """
public mutating func appendInterpolation<T: SQLExpressible>(_ expressible: T?) {
if let expressible = expressible {
sql += expressible.sqlExpression.expressionSQL(&context)
} else {
sql += "NULL"
}
}
/// Appends the name of the coding key.
///
/// // SELECT name FROM player
/// let request: SQLRequest<String> = """
/// SELECT \(CodingKey.name) FROM player
/// """
public mutating func appendInterpolation(_ codingKey: CodingKey) {
appendInterpolation(Column(codingKey.stringValue))
}
/// Appends a sequence of expressions, wrapped in parentheses.
///
/// // SELECT * FROM player WHERE id IN (?,?,?)
/// let ids = [1, 2, 3]
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE id IN \(ids)
/// """
///
/// If the sequence is empty, an empty subquery is appended:
///
/// // SELECT * FROM player WHERE id IN (SELECT NULL WHERE NULL)
/// let ids: [Int] = []
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE id IN \(ids)
/// """
public mutating func appendInterpolation<S>(_ sequence: S) where S: Sequence, S.Element: SQLExpressible {
appendInterpolation(sequence.lazy.map { $0.sqlExpression })
}
/// Appends a sequence of expressions, wrapped in parentheses.
///
/// // SELECT * FROM player WHERE a IN (b, c + 2)
/// let expressions = [Column("b"), Column("c") + 2]
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE a IN \(expressions)
/// """
///
/// If the sequence is empty, an empty subquery is appended:
///
/// // SELECT * FROM player WHERE a IN (SELECT NULL WHERE NULL)
/// let expressions: [SQLExpression] = []
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE a IN \(expressions)
/// """
public mutating func appendInterpolation<S>(_ sequence: S) where S: Sequence, S.Element == SQLExpression {
sql += "("
var first = true
for element in sequence {
if first {
first = false
} else {
sql += ","
}
appendInterpolation(element)
}
if first {
sql += "SELECT NULL WHERE NULL"
}
sql += ")"
}
/// Appends the ordering SQL.
///
/// // SELECT name FROM player ORDER BY name DESC
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player ORDER BY \(Column("name").desc)
/// """
public mutating func appendInterpolation(_ ordering: SQLOrderingTerm) {
sql += ordering.orderingTermSQL(&context)
}
/// Appends the request SQL, wrapped in parentheses
///
/// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player)
/// let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE score = \(subQuery)
/// """
public mutating func appendInterpolation<T>(_ request: SQLRequest<T>) {
sql += "(" + request.sql + ")"
arguments += request.arguments
}
}
#endif
@@ -163,7 +163,7 @@ struct SQLSelectQueryGenerator {
}
}
let statement = try db.makeUpdateStatement(sql)
let statement = try db.makeUpdateStatement(sql: sql)
statement.arguments = context.arguments!
return statement
}
@@ -179,7 +179,7 @@ struct SQLSelectQueryGenerator {
let sql = try self.sql(db, &context)
// Compile & set arguments
let statement = try db.makeSelectStatement(sql)
let statement = try db.makeSelectStatement(sql: sql)
statement.arguments = context.arguments! // not nil for this kind of context
return statement
}
+8 -12
View File
@@ -26,23 +26,19 @@ public protocol SQLSelectable {
// MARK: - SQLSelectionLiteral
struct SQLSelectionLiteral : SQLSelectable {
let sql: String
let arguments: StatementArguments?
private let sqlLiteral: SQLLiteral
init(_ sql: String, arguments: StatementArguments? = nil) {
self.sql = sql
self.arguments = arguments
init(literal sqlLiteral: SQLLiteral) {
self.sqlLiteral = sqlLiteral
}
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
if let arguments = arguments {
if context.appendArguments(arguments) == false {
// GRDB limitation: we don't know how to look for `?` in sql and
// replace them with with literals.
fatalError("Not implemented")
}
if context.append(arguments: sqlLiteral.arguments) == false {
// GRDB limitation: we don't know how to look for `?` in sql and
// replace them with with literals.
fatalError("Not implemented")
}
return sql
return sqlLiteral.sql
}
func countedSQL(_ context: inout SQLGenerationContext) -> String {
+26 -26
View File
@@ -29,7 +29,7 @@ extension Database {
let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID)
body(definition)
let sql = try definition.sql(self)
try execute(sql)
try execute(sql: sql)
}
#else
/// Creates a database table.
@@ -61,7 +61,7 @@ extension Database {
let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: withoutRowID)
body(definition)
let sql = try definition.sql(self)
try execute(sql)
try execute(sql: sql)
}
/// Creates a database table.
@@ -88,7 +88,7 @@ extension Database {
let definition = TableDefinition(name: name, temporary: temporary, ifNotExists: ifNotExists, withoutRowID: false)
body(definition)
let sql = try definition.sql(self)
try execute(sql)
try execute(sql: sql)
}
#endif
@@ -98,7 +98,7 @@ extension Database {
///
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func rename(table name: String, to newName: String) throws {
try execute("ALTER TABLE \(name.quotedDatabaseIdentifier) RENAME TO \(newName.quotedDatabaseIdentifier)")
try execute(sql: "ALTER TABLE \(name.quotedDatabaseIdentifier) RENAME TO \(newName.quotedDatabaseIdentifier)")
}
/// Modifies a database table.
@@ -117,7 +117,7 @@ extension Database {
let alteration = TableAlteration(name: name)
body(alteration)
let sql = try alteration.sql(self)
try execute(sql)
try execute(sql: sql)
}
/// Deletes a database table.
@@ -126,7 +126,7 @@ extension Database {
///
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func drop(table name: String) throws {
try execute("DROP TABLE \(name.quotedDatabaseIdentifier)")
try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)")
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
@@ -138,7 +138,7 @@ extension Database {
/// and use specific collations. To create such an index, use a raw SQL
/// query.
///
/// try db.execute("CREATE INDEX ...")
/// try db.execute(sql: "CREATE INDEX ...")
///
/// See https://www.sqlite.org/lang_createindex.html
///
@@ -155,7 +155,7 @@ extension Database {
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition?.sqlExpression)
let sql = definition.sql()
try execute(sql)
try execute(sql: sql)
}
#else
/// Creates an index.
@@ -166,7 +166,7 @@ extension Database {
/// and use specific collations. To create such an index, use a raw SQL
/// query.
///
/// try db.execute("CREATE INDEX ...")
/// try db.execute(sql: "CREATE INDEX ...")
///
/// See https://www.sqlite.org/lang_createindex.html
///
@@ -181,7 +181,7 @@ extension Database {
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: nil)
let sql = definition.sql()
try execute(sql)
try execute(sql: sql)
}
/// Creates a partial index.
@@ -204,7 +204,7 @@ extension Database {
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
let definition = IndexDefinition(name: name, table: table, columns: columns, unique: unique, ifNotExists: ifNotExists, condition: condition.sqlExpression)
let sql = definition.sql()
try execute(sql)
try execute(sql: sql)
}
#endif
@@ -214,7 +214,7 @@ extension Database {
///
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func drop(index name: String) throws {
try execute("DROP INDEX \(name.quotedDatabaseIdentifier)")
try execute(sql: "DROP INDEX \(name.quotedDatabaseIdentifier)")
}
/// Delete and recreate from scratch all indices that use this collation.
@@ -226,7 +226,7 @@ extension Database {
///
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func reindex(collation: Database.CollationName) throws {
try execute("REINDEX \(collation.rawValue)")
try execute(sql: "REINDEX \(collation.rawValue)")
}
/// Delete and recreate from scratch all indices that use this collation.
@@ -416,9 +416,9 @@ public final class TableDefinition {
///
/// - parameter sql: An SQL snippet
public func check(sql: String) {
var expression = SQLExpressionLiteral(sql)
expression.unsafeRaw = true // It's safe because this expression can't be composed with others
checkConstraints.append(expression)
// We do not want to wrap the SQL snippet inside parentheses around the
// checked SQL. This is why we use the "unsafeLiteral" initializer.
checkConstraints.append(SQLExpressionLiteral(unsafeLiteral: SQLLiteral(sql: sql)))
}
fileprivate func sql(_ db: Database) throws -> String {
@@ -507,7 +507,7 @@ public final class TableDefinition {
for checkExpression in checkConstraints {
var chunks: [String] = []
chunks.append("CHECK")
chunks.append("(" + checkExpression.sql + ")")
chunks.append("(" + checkExpression.quotedSQL() + ")")
items.append(chunks.joined(separator: " "))
}
@@ -721,9 +721,9 @@ public final class ColumnDefinition {
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func check(sql: String) -> Self {
var expression = SQLExpressionLiteral(sql)
expression.unsafeRaw = true // It's safe because this expression can't be composed with others
checkConstraints.append(expression)
// We do not want to wrap the SQL snippet inside parentheses around the
// checked SQL. This is why we use the "unsafeLiteral" initializer.
checkConstraints.append(SQLExpressionLiteral(unsafeLiteral: SQLLiteral(sql: sql)))
return self
}
@@ -755,9 +755,9 @@ public final class ColumnDefinition {
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func defaults(sql: String) -> Self {
var expression = SQLExpressionLiteral(sql)
expression.unsafeRaw = true // It's safe because this expression can't be composed with others
defaultExpression = expression
// We do not want to wrap the SQL snippet inside parentheses around the
// checked SQL. This is why we use the "unsafeLiteral" initializer.
defaultExpression = SQLExpressionLiteral(unsafeLiteral: SQLLiteral(sql: sql))
return self
}
@@ -861,12 +861,12 @@ public final class ColumnDefinition {
for checkConstraint in checkConstraints {
chunks.append("CHECK")
chunks.append("(" + checkConstraint.sql + ")")
chunks.append("(" + checkConstraint.quotedSQL() + ")")
}
if let defaultExpression = defaultExpression {
chunks.append("DEFAULT")
chunks.append(defaultExpression.sql)
chunks.append(defaultExpression.quotedSQL())
}
if let collationName = collationName {
@@ -943,7 +943,7 @@ private struct IndexDefinition {
chunks.append("\(table.quotedDatabaseIdentifier)(\((columns.map { $0.quotedDatabaseIdentifier } as [String]).joined(separator: ", ")))")
if let condition = condition {
chunks.append("WHERE")
chunks.append(condition.sql)
chunks.append(condition.quotedSQL())
}
return chunks.joined(separator: " ")
}
+2 -2
View File
@@ -64,7 +64,7 @@ extension Database {
chunks.append("USING")
chunks.append(module)
let sql = chunks.joined(separator: " ")
try execute(sql)
try execute(sql: sql)
}
/// Creates a virtual database table.
@@ -120,7 +120,7 @@ extension Database {
let sql = chunks.joined(separator: " ")
try inSavepoint {
try execute(sql)
try execute(sql: sql)
try module.database(self, didCreate: tableName, using: definition)
return .commit
}
+21 -21
View File
@@ -7,17 +7,17 @@ import Foundation
/// Types that adopt FetchableRecord can be initialized from a database Row.
///
/// let row = try Row.fetchOne(db, "SELECT ...")!
/// let row = try Row.fetchOne(db, sql: "SELECT ...")!
/// let player = Player(row)
///
/// The protocol comes with built-in methods that allow to fetch cursors,
/// arrays, or single records:
///
/// try Player.fetchCursor(db, "SELECT ...", arguments:...) // Cursor of Player
/// try Player.fetchAll(db, "SELECT ...", arguments:...) // [Player]
/// try Player.fetchOne(db, "SELECT ...", arguments:...) // Player?
/// try Player.fetchCursor(db, sql: "SELECT ...", arguments:...) // Cursor of Player
/// try Player.fetchAll(db, sql: "SELECT ...", arguments:...) // [Player]
/// try Player.fetchOne(db, sql: "SELECT ...", arguments:...) // Player?
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT ...")
/// try Player.fetchCursor(statement, arguments:...) // Cursor of Player
/// try Player.fetchAll(statement, arguments:...) // [Player]
/// try Player.fetchOne(statement, arguments:...) // Player?
@@ -141,7 +141,7 @@ extension FetchableRecord {
/// A cursor over records fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT * FROM player")
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player")
/// let players = try Player.fetchCursor(statement) // Cursor of Player
/// while let player = try players.next() { // Player
/// ...
@@ -164,7 +164,7 @@ extension FetchableRecord {
/// Returns an array of records fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT * FROM player")
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player")
/// let players = try Player.fetchAll(statement) // [Player]
///
/// - parameters:
@@ -179,7 +179,7 @@ extension FetchableRecord {
/// Returns a single record fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT * FROM player")
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player")
/// let player = try Player.fetchOne(statement) // Player?
///
/// - parameters:
@@ -199,7 +199,7 @@ extension FetchableRecord {
/// Returns a cursor over records fetched from an SQL query.
///
/// let players = try Player.fetchCursor(db, "SELECT * FROM player") // Cursor of Player
/// let players = try Player.fetchCursor(db, sql: "SELECT * FROM player") // Cursor of Player
/// while let player = try players.next() { // Player
/// ...
/// }
@@ -212,42 +212,42 @@ extension FetchableRecord {
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor<Self> {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of records fetched from an SQL query.
///
/// let players = try Player.fetchAll(db, "SELECT * FROM player") // [Player]
/// let players = try Player.fetchAll(db, sql: "SELECT * FROM player") // [Player]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single record fetched from an SQL query.
///
/// let player = try Player.fetchOne(db, "SELECT * FROM player") // Player?
/// let player = try Player.fetchOne(db, sql: "SELECT * FROM player") // Player?
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -366,7 +366,7 @@ extension FetchRequest where RowDecoder: FetchableRecord {
///
/// struct Player : FetchableRecord { ... }
/// try dbQueue.read { db in
/// let players: RecordCursor<Player> = try Player.fetchCursor(db, "SELECT * FROM player")
/// let players: RecordCursor<Player> = try Player.fetchCursor(db, sql: "SELECT * FROM player")
/// }
public final class RecordCursor<Record: FetchableRecord> : Cursor {
private let statement: SelectStatement
+6 -6
View File
@@ -40,14 +40,14 @@ public final class FetchedRecordsController<Record: FetchableRecord> {
public convenience init(
_ databaseWriter: DatabaseWriter,
sql: String,
arguments: StatementArguments? = nil,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil,
queue: DispatchQueue = .main,
isSameRecord: ((Record, Record) -> Bool)? = nil) throws
{
try self.init(
databaseWriter,
request: SQLRequest<Record>(sql, arguments: arguments, adapter: adapter),
request: SQLRequest<Record>(sql: sql, arguments: arguments, adapter: adapter),
queue: queue,
isSameRecord: isSameRecord)
}
@@ -196,8 +196,8 @@ public final class FetchedRecordsController<Record: FetchableRecord> {
///
/// 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(sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
try setRequest(SQLRequest(sql, arguments: arguments, adapter: adapter))
public func setRequest(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws {
try setRequest(SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
/// Registers changes notification callbacks.
@@ -429,13 +429,13 @@ extension FetchedRecordsController where Record: TableRecord {
public convenience init(
_ databaseWriter: DatabaseWriter,
sql: String,
arguments: StatementArguments? = nil,
arguments: StatementArguments = StatementArguments(),
adapter: RowAdapter? = nil,
queue: DispatchQueue = .main) throws
{
try self.init(
databaseWriter,
request: SQLRequest(sql, arguments: arguments, adapter: adapter),
request: SQLRequest(sql: sql, arguments: arguments, adapter: adapter),
queue: queue)
}
+4 -4
View File
@@ -1168,7 +1168,7 @@ final class DAO {
onConflict: onConflict,
tableName: databaseTableName,
insertedColumns: persistenceContainer.columns)
let statement = try db.internalCachedUpdateStatement(query.sql)
let statement = try db.internalCachedUpdateStatement(sql: query.sql)
statement.unsafeSetArguments(StatementArguments(persistenceContainer.values))
return statement
}
@@ -1217,7 +1217,7 @@ final class DAO {
tableName: databaseTableName,
updatedColumns: updatedColumns,
conditionColumns: primaryKeyColumns)
let statement = try db.internalCachedUpdateStatement(query.sql)
let statement = try db.internalCachedUpdateStatement(sql: query.sql)
statement.unsafeSetArguments(StatementArguments(updatedValues + primaryKeyValues))
return statement
}
@@ -1236,7 +1236,7 @@ final class DAO {
let query = DeleteQuery(
tableName: databaseTableName,
conditionColumns: primaryKeyColumns)
let statement = try db.internalCachedUpdateStatement(query.sql)
let statement = try db.internalCachedUpdateStatement(sql: query.sql)
statement.unsafeSetArguments(StatementArguments(primaryKeyValues))
return statement
}
@@ -1255,7 +1255,7 @@ final class DAO {
let query = ExistsQuery(
tableName: databaseTableName,
conditionColumns: primaryKeyColumns)
let statement = try db.internalCachedSelectStatement(query.sql)
let statement = try db.internalCachedSelectStatement(sql: query.sql)
statement.unsafeSetArguments(StatementArguments(primaryKeyValues))
return statement
}
+1 -1
View File
@@ -122,7 +122,7 @@ extension TableRecord {
public static func selectionSQL(alias: String? = nil) -> String {
let alias = TableAlias(tableName: databaseTableName, userName: alias)
let selection = databaseSelection.map { $0.qualifiedSelectable(with: alias) }
var context = SQLGenerationContext.recordSelectionGenerationContext(alias: alias)
var context = SQLGenerationContext.recordSelectionGenerationContext()
return selection
.map { $0.resultColumnSQL(&context) }
.joined(separator: ", ")
+1 -1
View File
@@ -6,7 +6,7 @@ extension String {
/// Returns the receiver, quoted for safe insertion as an identifier in an
/// SQL query.
///
/// db.execute("SELECT * FROM \(tableName.quotedDatabaseIdentifier)")
/// db.execute(sql: "SELECT * FROM \(tableName.quotedDatabaseIdentifier)")
public var quotedDatabaseIdentifier: String {
// See https://www.sqlite.org/lang_keywords.html
return "\"" + self + "\""
@@ -7,7 +7,7 @@ extension ValueObservation where Reducer == Void {
///
/// For example:
///
/// let request = SQLRequest<Row>("SELECT * FROM player")
/// let request = SQLRequest<Row>(sql: "SELECT * FROM player")
/// let observation = ValueObservation.trackingAll(request)
///
/// let observer = try observation.start(in: dbQueue) { rows: [Row] in
@@ -39,7 +39,7 @@ extension ValueObservation where Reducer == Void {
///
/// For example:
///
/// let request = SQLRequest<Row>("SELECT * FROM player WHERE id = ?", arguments: [1])
/// let request = SQLRequest<Row>(sql: "SELECT * FROM player WHERE id = ?", arguments: [1])
/// let observation = ValueObservation.trackingOne(request)
///
/// let observer = try observation.start(in: dbQueue) { row: Row? in
+44
View File
@@ -577,6 +577,10 @@
567E55EE1D2BDD3F00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
567E55F41D2BDDFF00CC6F79 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
567F0B33220F196F00D111FB /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B32220F196F00D111FB /* SQLInterpolationTests.swift */; };
567F0B34220F196F00D111FB /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B32220F196F00D111FB /* SQLInterpolationTests.swift */; };
567F0B35220F196F00D111FB /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B32220F196F00D111FB /* SQLInterpolationTests.swift */; };
567F0B36220F196F00D111FB /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B32220F196F00D111FB /* SQLInterpolationTests.swift */; };
567F45A91F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AA1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AD1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
@@ -854,6 +858,10 @@
56B6EF65208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */; };
56B6EF66208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */; };
56B6EF67208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */; };
56B86E7D220FF4F500524C16 /* SQLLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B86E7B220FF4F500524C16 /* SQLLiteralTests.swift */; };
56B86E7E220FF4F500524C16 /* SQLLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B86E7B220FF4F500524C16 /* SQLLiteralTests.swift */; };
56B86E7F220FF4F500524C16 /* SQLLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B86E7B220FF4F500524C16 /* SQLLiteralTests.swift */; };
56B86E80220FF4F500524C16 /* SQLLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B86E7B220FF4F500524C16 /* SQLLiteralTests.swift */; };
56B9649E1DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; };
56B964A11DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; };
56B964B21DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; };
@@ -920,6 +928,12 @@
56DAA2D81DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
56DAA2DC1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; };
56DAA2DF1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; };
56E9FAC8221046A100C703A8 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAC7221046A100C703A8 /* SQLInterpolation.swift */; };
56E9FAC9221046A100C703A8 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAC7221046A100C703A8 /* SQLInterpolation.swift */; };
56E9FACF2210477800C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACE2210477800C703A8 /* SQLInterpolation+QueryInterface.swift */; };
56E9FAD02210477800C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACE2210477800C703A8 /* SQLInterpolation+QueryInterface.swift */; };
56E9FADC221053ED00C703A8 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FADB221053EC00C703A8 /* SQLLiteral.swift */; };
56E9FADD221053ED00C703A8 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FADB221053EC00C703A8 /* SQLLiteral.swift */; };
56EA63CC209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; };
56EA63CD209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; };
56EA63CE209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; };
@@ -929,6 +943,8 @@
56F3E74B1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F3E74E1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F3E74F1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56FBFED3221072E500945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED2221072E500945324 /* SQLRequest.swift */; };
56FBFED4221072E500945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED2221072E500945324 /* SQLRequest.swift */; };
56FEE7FC1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
56FEE7FD1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
56FEE8001F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
@@ -1171,6 +1187,7 @@
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567F0B32220F196F00D111FB /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
@@ -1257,6 +1274,7 @@
56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
56B86E7B220FF4F500524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = "<group>"; };
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = "<group>"; };
56B9649C1DA51B4C0002DA19 /* FTS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5.swift; sourceTree = "<group>"; };
56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerDescriptor.swift; sourceTree = "<group>"; };
@@ -1293,6 +1311,9 @@
56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = "<group>"; };
56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = "<group>"; };
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = "<group>"; };
56E9FAC7221046A100C703A8 /* SQLInterpolation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLInterpolation.swift; sourceTree = "<group>"; };
56E9FACE2210477800C703A8 /* SQLInterpolation+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLInterpolation+QueryInterface.swift"; sourceTree = "<group>"; };
56E9FADB221053EC00C703A8 /* SQLLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteral.swift; sourceTree = "<group>"; };
56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = "<group>"; };
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = "<group>"; };
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = "<group>"; };
@@ -1300,6 +1321,7 @@
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
56FBFED2221072E500945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = "<group>"; };
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = "<group>"; };
@@ -1605,6 +1627,7 @@
56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */,
5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */,
5653EC19209873E600F46237 /* SQLGenerationContext.swift */,
56E9FACE2210477800C703A8 /* SQLInterpolation+QueryInterface.swift */,
56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */,
56D91A9B2205DD5200770D8D /* SQLRelation.swift */,
56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */,
@@ -1802,6 +1825,8 @@
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */,
56A2381D1B9C74A90082EB20 /* Row */,
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */,
567F0B32220F196F00D111FB /* SQLInterpolationTests.swift */,
56B86E7B220FF4F500524C16 /* SQLLiteralTests.swift */,
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */,
56A238201B9C74A90082EB20 /* Statement */,
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */,
@@ -1895,6 +1920,9 @@
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56E9FAC7221046A100C703A8 /* SQLInterpolation.swift */,
56E9FADB221053EC00C703A8 /* SQLLiteral.swift */,
56FBFED2221072E500945324 /* SQLRequest.swift */,
56A238781B9C75030082EB20 /* Statement.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
@@ -2322,6 +2350,7 @@
5653EC17209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */,
564CE52621B312B500652B19 /* ValueObservation+MapReducer.swift in Sources */,
5659F4A11EA8D997004A4992 /* Result.swift in Sources */,
56E9FAC8221046A100C703A8 /* SQLInterpolation.swift in Sources */,
560FC5201CB003810014AA8E /* Date.swift in Sources */,
560FC5221CB003810014AA8E /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
563EF424215F8A88007DAACD /* OrderedDictionary.swift in Sources */,
@@ -2378,6 +2407,7 @@
561408A5221596B100DAD589 /* GRDB-4.0.swift in Sources */,
560FC53A1CB003810014AA8E /* NSNull.swift in Sources */,
56CEB51A1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
56FBFED3221072E500945324 /* SQLRequest.swift in Sources */,
564CE44021AA957000652B19 /* ValueObserver.swift in Sources */,
5674A7011F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
5698AC791DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
@@ -2385,12 +2415,14 @@
566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
5613ED7F21A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */,
5698AD221DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
56E9FACF2210477800C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
564CE5BB21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */,
560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */,
5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */,
5613ED8521A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */,
5653EB9520961FC000F46237 /* HasManyAssociation.swift in Sources */,
560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */,
56E9FADC221053ED00C703A8 /* SQLLiteral.swift in Sources */,
5613ED7B21A95E8400DC7A68 /* ValueObservation.swift in Sources */,
567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */,
560FC53F1CB003810014AA8E /* Row.swift in Sources */,
@@ -2445,6 +2477,7 @@
56EA63CC209C7F31009715B8 /* DerivableRequestTests.swift in Sources */,
560FC5701CB00B880014AA8E /* DatabasePoolCollationTests.swift in Sources */,
560FC5711CB00B880014AA8E /* RecordPrimaryKeySingleTests.swift in Sources */,
567F0B33220F196F00D111FB /* SQLInterpolationTests.swift in Sources */,
5674A7191F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
56B021CA1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
563B07082186280600B38F35 /* ValueObservationRowTests.swift in Sources */,
@@ -2486,6 +2519,7 @@
5657AB3F1D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
560FC57E1CB00B880014AA8E /* MutablePersistableRecordTests.swift in Sources */,
5657AB5F1D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
56B86E7D220FF4F500524C16 /* SQLLiteralTests.swift in Sources */,
560FC57F1CB00B880014AA8E /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5698ACB71DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */,
5672DE5A1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */,
@@ -2625,6 +2659,7 @@
56C3F7551CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */,
5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */,
56B021CB1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
567F0B34220F196F00D111FB /* SQLInterpolationTests.swift in Sources */,
5674A71B1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
56B14E811D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
563B07092186280600B38F35 /* ValueObservationRowTests.swift in Sources */,
@@ -2666,6 +2701,7 @@
5671563C1CB16729007DC145 /* MutablePersistableRecordTests.swift in Sources */,
5671563D1CB16729007DC145 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */,
56B86E7E220FF4F500524C16 /* SQLLiteralTests.swift in Sources */,
5671563F1CB16729007DC145 /* RecordCopyTests.swift in Sources */,
5698ACB81DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */,
567156401CB16729007DC145 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
@@ -2803,6 +2839,7 @@
5653EC18209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */,
564CE52721B312B700652B19 /* ValueObservation+MapReducer.swift in Sources */,
5659F4A41EA8D997004A4992 /* Result.swift in Sources */,
56E9FAC9221046A100C703A8 /* SQLInterpolation.swift in Sources */,
56AFC9F41CB1A8BB00F48B96 /* CGFloat.swift in Sources */,
56AFC9F51CB1A8BB00F48B96 /* Date.swift in Sources */,
563EF425215F8A88007DAACD /* OrderedDictionary.swift in Sources */,
@@ -2859,6 +2896,7 @@
561408A6221596B100DAD589 /* GRDB-4.0.swift in Sources */,
56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */,
56CEB51D1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
56FBFED4221072E500945324 /* SQLRequest.swift in Sources */,
564CE44121AA957000652B19 /* ValueObserver.swift in Sources */,
5674A6FE1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
5698AC7C1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
@@ -2866,12 +2904,14 @@
566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
5613ED8021A95E8400DC7A68 /* ValueObservation+Map.swift in Sources */,
5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
56E9FAD02210477800C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
564CE5BC21B8FBFD00652B19 /* DatabaseRegionObservation.swift in Sources */,
56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */,
5653EB9820961FC000F46237 /* ForeignKey.swift in Sources */,
5613ED8621A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */,
5653EB9620961FC000F46237 /* HasManyAssociation.swift in Sources */,
56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */,
56E9FADD221053ED00C703A8 /* SQLLiteral.swift in Sources */,
5613ED7C21A95E8400DC7A68 /* ValueObservation.swift in Sources */,
56AFCA151CB1A8BB00F48B96 /* PersistableRecord.swift in Sources */,
567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */,
@@ -2926,6 +2966,7 @@
56EA63CE209C7F31009715B8 /* DerivableRequestTests.swift in Sources */,
56AFCA3F1CB1AA9900F48B96 /* RecordPrimaryKeySingleTests.swift in Sources */,
56AFCA421CB1AA9900F48B96 /* DatabasePoolFunctionTests.swift in Sources */,
567F0B35220F196F00D111FB /* SQLInterpolationTests.swift in Sources */,
5674A7181F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
56AFCA441CB1AA9900F48B96 /* RowCopiedFromStatementTests.swift in Sources */,
563B070A2186280600B38F35 /* ValueObservationRowTests.swift in Sources */,
@@ -2967,6 +3008,7 @@
5672DE5D1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */,
56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */,
56FF45451D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */,
56B86E7F220FF4F500524C16 /* SQLLiteralTests.swift in Sources */,
56AFCA521CB1AA9900F48B96 /* PersistableRecordTests.swift in Sources */,
56AFCA531CB1AA9900F48B96 /* DatabaseValueConversionTests.swift in Sources */,
5657AB531D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */,
@@ -3106,6 +3148,7 @@
56EA63CF209C7F31009715B8 /* DerivableRequestTests.swift in Sources */,
5657AB641D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
56FF455C1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */,
567F0B36220F196F00D111FB /* SQLInterpolationTests.swift in Sources */,
56AFCA971CB1ABC800F48B96 /* DatabasePoolCollationTests.swift in Sources */,
5674A7151F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
563B070B2186280600B38F35 /* ValueObservationRowTests.swift in Sources */,
@@ -3147,6 +3190,7 @@
5657AB6C1D108BA9006283EF /* FoundationURLTests.swift in Sources */,
56AFCAA81CB1ABC800F48B96 /* DataMemoryTests.swift in Sources */,
56AFCAA91CB1ABC800F48B96 /* RecordCopyTests.swift in Sources */,
56B86E80220FF4F500524C16 /* SQLLiteralTests.swift in Sources */,
56A8C24B1D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */,
56AFCAAB1CB1ABC800F48B96 /* PersistableRecordTests.swift in Sources */,
56FF45461D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */,
+36
View File
@@ -259,6 +259,8 @@
567DAF211EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
567F0B30220F196400D111FB /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B2F220F196300D111FB /* SQLInterpolationTests.swift */; };
567F0B31220F196400D111FB /* SQLInterpolationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F0B2F220F196300D111FB /* SQLInterpolationTests.swift */; };
567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
@@ -325,6 +327,8 @@
56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; };
56B6EF60208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */; };
56B6EF61208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */; };
56B86E70220FF4C900524C16 /* SQLLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B86E6E220FF4C800524C16 /* SQLLiteralTests.swift */; };
56B86E71220FF4C900524C16 /* SQLLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B86E6E220FF4C800524C16 /* SQLLiteralTests.swift */; };
56B9649F1DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; };
56B964A21DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; };
56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; };
@@ -380,12 +384,20 @@
56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; };
56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; };
56E9FAC42210468500C703A8 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAC32210468500C703A8 /* SQLInterpolation.swift */; };
56E9FAC52210468500C703A8 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAC32210468500C703A8 /* SQLInterpolation.swift */; };
56E9FAD22210479700C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD12210479700C703A8 /* SQLInterpolation+QueryInterface.swift */; };
56E9FAD32210479700C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD12210479700C703A8 /* SQLInterpolation+QueryInterface.swift */; };
56E9FAD52210538400C703A8 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD42210538400C703A8 /* SQLLiteral.swift */; };
56E9FAD62210538400C703A8 /* SQLLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD42210538400C703A8 /* SQLLiteral.swift */; };
56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */; };
56EA63CA209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */; };
56ED8A7F1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; };
56ED8A801DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; };
56F3E74C1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56F3E7501E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
56FBFED62210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; };
56FBFED72210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; };
56FC987A1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
56FC987D1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
@@ -805,6 +817,7 @@
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
567F0B2F220F196300D111FB /* SQLInterpolationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLInterpolationTests.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
@@ -883,6 +896,7 @@
56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = "<group>"; };
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
56B86E6E220FF4C800524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = "<group>"; };
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = "<group>"; };
56B9649C1DA51B4C0002DA19 /* FTS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5.swift; sourceTree = "<group>"; };
56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerDescriptor.swift; sourceTree = "<group>"; };
@@ -918,6 +932,9 @@
56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = "<group>"; };
56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = "<group>"; };
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = "<group>"; };
56E9FAC32210468500C703A8 /* SQLInterpolation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLInterpolation.swift; sourceTree = "<group>"; };
56E9FAD12210479700C703A8 /* SQLInterpolation+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLInterpolation+QueryInterface.swift"; sourceTree = "<group>"; };
56E9FAD42210538400C703A8 /* SQLLiteral.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteral.swift; sourceTree = "<group>"; };
56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = "<group>"; };
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = "<group>"; };
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = "<group>"; };
@@ -925,6 +942,7 @@
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = "<group>"; };
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = "<group>"; };
@@ -1213,6 +1231,7 @@
56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */,
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */,
5653EC072098737400F46237 /* SQLGenerationContext.swift */,
56E9FAD12210479700C703A8 /* SQLInterpolation+QueryInterface.swift */,
56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */,
56D91A9E2205E02300770D8D /* SQLRelation.swift */,
56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */,
@@ -1410,6 +1429,8 @@
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */,
56A2381D1B9C74A90082EB20 /* Row */,
569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */,
567F0B2F220F196300D111FB /* SQLInterpolationTests.swift */,
56B86E6E220FF4C800524C16 /* SQLLiteralTests.swift */,
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */,
56A238201B9C74A90082EB20 /* Statement */,
56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */,
@@ -1503,6 +1524,9 @@
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
56E9FAC32210468500C703A8 /* SQLInterpolation.swift */,
56E9FAD42210538400C703A8 /* SQLLiteral.swift */,
56FBFED52210731000945324 /* SQLRequest.swift */,
56A238781B9C75030082EB20 /* Statement.swift */,
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
@@ -1959,6 +1983,7 @@
F3BA800D1CFB2871003DC1BA /* DatabasePool.swift in Sources */,
F3BA800B1CFB286D003DC1BA /* Database.swift in Sources */,
F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */,
56E9FAC52210468500C703A8 /* SQLInterpolation.swift in Sources */,
563EF421215F8A76007DAACD /* OrderedDictionary.swift in Sources */,
F3BA80161CFB2876003DC1BA /* Row.swift in Sources */,
569EF0E7200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */,
@@ -2015,6 +2040,7 @@
561408A1221596A100DAD589 /* GRDB-4.0.swift in Sources */,
F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */,
56CEB51E1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
56FBFED72210731100945324 /* SQLRequest.swift in Sources */,
564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */,
5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */,
@@ -2022,12 +2048,14 @@
566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
5613ED6621A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */,
5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
56E9FAD32210479700C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
564CE5B821B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */,
F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */,
5653EB4A20961F6100F46237 /* ForeignKey.swift in Sources */,
5613ED6C21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */,
5653EB4820961F6100F46237 /* HasManyAssociation.swift in Sources */,
F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */,
56E9FAD62210538400C703A8 /* SQLLiteral.swift in Sources */,
5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */,
F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */,
567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */,
@@ -2082,6 +2110,7 @@
56EA63CA209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */,
F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */,
562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */,
567F0B31220F196400D111FB /* SQLInterpolationTests.swift in Sources */,
5674A7161F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
56B021D01D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
563B0703218627DF00B38F35 /* ValueObservationRowTests.swift in Sources */,
@@ -2123,6 +2152,7 @@
F3BA81121CFB3059003DC1BA /* DatabaseMigratorTests.swift in Sources */,
56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */,
F3BA80EB1CFB3016003DC1BA /* FetchableRecordTests.swift in Sources */,
56B86E71220FF4C900524C16 /* SQLLiteralTests.swift in Sources */,
F3BA81151CFB305E003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */,
F3BA80DC1CFB300E003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */,
5698AD021DAA8ACB0056AF8C /* FTS5CustomTokenizerTests.swift in Sources */,
@@ -2260,6 +2290,7 @@
F3BA80691CFB2E55003DC1BA /* DatabasePool.swift in Sources */,
F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */,
F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */,
56E9FAC42210468500C703A8 /* SQLInterpolation.swift in Sources */,
563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */,
F3BA80721CFB2E55003DC1BA /* Row.swift in Sources */,
569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */,
@@ -2316,6 +2347,7 @@
561408A0221596A100DAD589 /* GRDB-4.0.swift in Sources */,
F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */,
56CEB51B1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
56FBFED62210731100945324 /* SQLRequest.swift in Sources */,
564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */,
5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */,
@@ -2323,12 +2355,14 @@
566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
5613ED6521A95E6100DC7A68 /* ValueObservation+Map.swift in Sources */,
5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
56E9FAD22210479700C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */,
F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */,
5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */,
5613ED6B21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */,
5653EB4720961F6100F46237 /* HasManyAssociation.swift in Sources */,
F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */,
56E9FAD52210538400C703A8 /* SQLLiteral.swift in Sources */,
5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */,
F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */,
567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */,
@@ -2383,6 +2417,7 @@
56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */,
F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */,
F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */,
567F0B30220F196400D111FB /* SQLInterpolationTests.swift in Sources */,
5698ACB91DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */,
5674A7141F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
563B0702218627DF00B38F35 /* ValueObservationRowTests.swift in Sources */,
@@ -2424,6 +2459,7 @@
562205FD1E420EA2005860AC /* DatabasePoolBackupTests.swift in Sources */,
562206091E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */,
56176C7E1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */,
56B86E70220FF4C900524C16 /* SQLLiteralTests.swift in Sources */,
F3BA811C1CFB305F003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */,
5698ACD11DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */,
562205FB1E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */,
@@ -83,15 +83,17 @@ try dbQueue.write { db in
}
// Demo values: two Foo and one Bar
try db.execute("""
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
""", arguments: [
try db.execute(
sql: """
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
""",
arguments: [
"Foo", "Arthur", nil,
"Bar", nil, 100,
"Foo", "Barbara", nil,
])
])
}
//: We also need a method that decodes database rows into `Foo` or `Bar`
@@ -140,7 +142,7 @@ extension Base {
try dbQueue.read { db in
print("> KISS: Fetch from SQL")
let rows = try Row.fetchAll(db, "SELECT * FROM base") // Fetch database rows
let rows = try Row.fetchAll(db, sql: "SELECT * FROM base") // Fetch database rows
let bases = rows.map { row in // Decode database rows
Base.decode(row: row)
}
@@ -210,13 +212,15 @@ extension Base: MyDatabaseDecoder {
//: **prepared statement**:
//:
//: try dbQueue.read { db in
//: let statement = try db.makeSelectStatement("SELECT ...")
//: let statement = try db.makeSelectStatement(sql: "SELECT ...")
//: try Base.fetchCursor(statement) // Cursor of Base
//: try Base.fetchAll(statement) // [Base]
//: try Base.fetchOne(statement) // Base?
//: }
extension MyDatabaseDecoder {
// MARK: - Fetch from SelectStatement
// SelectStatement, StatementArguments, and RowAdapter are the fundamental
// fetching parameters of GRDB. Make sure to accept them all:
static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
@@ -239,7 +243,7 @@ extension MyDatabaseDecoder {
try dbQueue.read { db in
print("> Fetch from prepared statement")
let statement = try db.makeSelectStatement("SELECT * FROM base")
let statement = try db.makeSelectStatement(sql: "SELECT * FROM base")
let bases = try Base.fetchAll(statement)
for base in bases {
print(base.description)
@@ -258,6 +262,8 @@ try dbQueue.read { db in
//: try Base.fetchOne(db, request) // Base?
//: }
extension MyDatabaseDecoder {
// MARK: - Fetch from FetchRequest
static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> MapCursor<RowCursor, DecodedType> {
let (statement, adapter) = try request.prepare(db)
return try fetchCursor(statement, adapter: adapter)
@@ -293,6 +299,8 @@ try dbQueue.read { db in
//: try request.fetchOne(db) // Base?
//: }
extension FetchRequest where RowDecoder: MyDatabaseDecoder {
// MARK: - FetchRequest fetching methods
func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, RowDecoder.DecodedType> {
return try RowDecoder.fetchCursor(db, self)
}
@@ -324,6 +332,8 @@ try dbQueue.read { db in
//: try Base.fetchOne(db) // Base?
//: }
extension MyDatabaseDecoder where Self: TableRecord {
// MARK: - Static fetching methods
static func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, DecodedType> {
return try all().fetchCursor(db)
}
@@ -345,31 +355,32 @@ try dbQueue.read { db in
}
}
//: Finally, you don't have a true GRDB record unless it allows fetching from
//: raw SQL:
//: Finally, you can support raw SQL as well:
//:
//: try dbQueue.read { db in
//: try Base.fetchCursor(db, "SELECT ...") // Cursor of Base
//: try Base.fetchAll(db, "SELECT ...") // [Base]
//: try Base.fetchOne(db, "SELECT ...") // Base?
//: try Base.fetchAll(db,
//: sql: "SELECT ... WHERE name = ?",
//: arguments: ["O'Brien"]) // [Base]
//: }
extension MyDatabaseDecoder {
static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
return try fetchCursor(db, SQLRequest<Self>(sql, arguments: arguments, adapter: adapter))
// MARK: - Fetch from SQL
static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
return try fetchAll(db, SQLRequest<Self>(sql, arguments: arguments, adapter: adapter))
static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [DecodedType] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
return try fetchOne(db, SQLRequest<Self>(sql, arguments: arguments, adapter: adapter))
static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DecodedType? {
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
try dbQueue.read { db in
print("> Fetch from SQL")
let bases = try Base.fetchAll(db, "SELECT * FROM base")
let bases = try Base.fetchAll(db, sql: "SELECT * FROM base")
for base in bases {
print(base.description)
}
@@ -13,9 +13,9 @@ try! dbQueue.inDatabase { db in
t.column("name", .text)
}
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"])
try db.execute(sql: "INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
try db.execute(sql: "INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"])
let names = try String.fetchAll(db, "SELECT name FROM persons")
let names = try String.fetchAll(db, sql: "SELECT name FROM persons")
print(names)
}
@@ -1,136 +0,0 @@
//: To run this playground:
//:
//: - Open GRDB.xcworkspace
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
//: - Build: menu Product > Build
//: - Select the playground in the Playgrounds Group
//: - Run the playground
//:
//: Record
//: ======
//:
//: This playground is a demo of the Record class, the type that provides fetching methods, persistence methods, and change tracking.
import GRDB
//: ## Setup
//:
//: First open an in-memory database, with a trace function that prints all SQL statements.
var configuration = Configuration()
configuration.trace = { print($0) }
let dbQueue = DatabaseQueue(configuration: configuration)
//: Create a database table which stores persons.
try dbQueue.inDatabase { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"firstName TEXT, " +
"lastName TEXT" +
")")
}
//: ## Subclassing Record
//:
//: The Person class is a subclass of Record, with regular properties, and a regular initializer:
class Person : Record {
var id: Int64?
var firstName: String?
var lastName: String?
var fullName: String {
return [firstName, lastName].flatMap { $0 }.joined(separator: " ")
}
init(firstName: String?, lastName: String?) {
self.id = nil
self.firstName = firstName
self.lastName = lastName
super.init()
}
//: Subclasses of Record have to override the methods that define how they interact with the database.
//:
//: 1. The table name:
override class var databaseTableName: String {
return "persons"
}
//: 2. How to build a Person from a database row:
required init(row: Row) {
id = row["id"]
firstName = row["firstName"]
lastName = row["lastName"]
super.init(row: row)
}
//: 3. The dictionary of values that are stored in the database:
override func encode(to container: inout PersistenceContainer) {
container["id"] = id
container["firstName"] = firstName
container["lastName"] = lastName
}
//: 4. When relevant, update the person's id after a database row has been inserted:
override func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
//: ## Insert Records
//:
//: Persons are regular objects, that you can freely create:
let arthur = Person(firstName: "Arthur", lastName: "Miller")
let barbra = Person(firstName: "Barbra", lastName: "Streisand")
let cinderella = Person(firstName: "Cinderella", lastName: nil)
//: They are not stored in the database yet. Insert them:
try dbQueue.inDatabase { db in
try arthur.insert(db)
try barbra.insert(db)
try cinderella.insert(db)
}
//: ## Fetching Records
try dbQueue.inDatabase { db in
//: Fetch records from the database:
let allPersons = try Person.fetchAll(db)
//: Fetch record by primary key:
let person = try Person.fetchOne(db, key: arthur.id)!
person.fullName
//: Fetch persons with an SQL query:
let millers = try Person.fetchAll(db, "SELECT * FROM persons WHERE lastName = ?", arguments: ["Miller"])
millers.first!.fullName
//: To fetch persons using the query interface, you need some colums that can filter or sort:
struct Col {
static let firstName = Column("firstName")
static let lastName = Column("lastName")
}
//: Sort
let personsSortedByName = try Person.order(Col.firstName, Col.lastName).fetchAll(db)
//: Filter
let streisands = try Person.filter(Col.lastName == "Streisand").fetchAll(db)
}
@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='osx' display-mode='raw'>
<timeline fileName='timeline.xctimeline'/>
</playground>
+32 -31
View File
@@ -9,7 +9,7 @@
//: Tour
//: ======
//:
//: This playground is a tour of GRDB.
//: This playground is a quick tour of GRDB.
import GRDB
import CoreLocation
@@ -26,44 +26,45 @@ let dbQueue = DatabaseQueue(configuration: configuration)
//: Execute SQL queries
try dbQueue.inDatabase { db in
try db.execute(
"CREATE TABLE pointOfInterests (" +
"id INTEGER PRIMARY KEY, " +
"title TEXT, " +
"favorite BOOLEAN NOT NULL, " +
"latitude DOUBLE NOT NULL, " +
"longitude DOUBLE NOT NULL" +
")")
try db.execute(sql: """
CREATE TABLE place (
id INTEGER PRIMARY KEY,
title TEXT,
favorite BOOLEAN NOT NULL,
latitude DOUBLE NOT NULL,
longitude DOUBLE NOT NULL
)
""")
try db.execute(
"INSERT INTO pointOfInterests (title, favorite, latitude, longitude) " +
"VALUES (?, ?, ?, ?)",
arguments: ["Paris", true, 48.85341, 2.3488])
try db.execute(sql: """
INSERT INTO place (title, favorite, latitude, longitude)
VALUES (?, ?, ?, ?)
""", arguments: ["Paris", true, 48.85341, 2.3488])
let parisId = db.lastInsertedRowID
}
//: Fetch database rows and values
try dbQueue.inDatabase { db in
let rows = try Row.fetchCursor(db, "SELECT * FROM pointOfInterests")
try! dbQueue.inDatabase { db in
let rows = try Row.fetchCursor(db, sql: "SELECT * FROM place")
while let row = try rows.next() {
let title: String = row["title"]
let favorite: Bool = row["favorite"]
let coordinate = CLLocationCoordinate2DMake(
row["latitude"],
row["longitude"])
let coordinate = CLLocationCoordinate2D(
latitude: row["latitude"],
longitude: row["longitude"])
print("Fetched", title, favorite, coordinate)
}
let poiCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM pointOfInterests")! // Int
let poiTitles = try String.fetchAll(db, "SELECT title FROM pointOfInterests") // [String]
let placeCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! // Int
let placeTitles = try String.fetchAll(db, sql: "SELECT title FROM place") // [String]
}
//: Insert and fetch records
struct PointOfInterest {
struct Place {
var id: Int64?
var title: String?
var favorite: Bool
@@ -71,7 +72,7 @@ struct PointOfInterest {
}
// Adopt FetchableRecord
extension PointOfInterest : FetchableRecord {
extension Place : FetchableRecord {
init(row: Row) {
id = row["id"]
title = row["title"]
@@ -83,12 +84,12 @@ extension PointOfInterest : FetchableRecord {
}
// Adopt TableRecord
extension PointOfInterest : TableRecord {
static let databaseTableName = "pointOfInterests"
extension Place : TableRecord {
static let databaseTableName = "place"
}
// Adopt MutablePersistableRecord
extension PointOfInterest : MutablePersistableRecord {
extension Place : MutablePersistableRecord {
func encode(to container: inout PersistenceContainer) {
container["id"] = id
container["title"] = title
@@ -103,7 +104,7 @@ extension PointOfInterest : MutablePersistableRecord {
}
try dbQueue.inDatabase { db in
var berlin = PointOfInterest(
var berlin = Place(
id: nil,
title: "Berlin",
favorite: false,
@@ -116,7 +117,7 @@ try dbQueue.inDatabase { db in
try berlin.update(db)
// Fetch from SQL
let pois = try PointOfInterest.fetchAll(db, "SELECT * FROM pointOfInterests") // [PointOfInterest]
let places = try Place.fetchAll(db, sql: "SELECT * FROM place") // [Place]
//: Avoid SQL with the query interface:
@@ -124,10 +125,10 @@ try dbQueue.inDatabase { db in
let title = Column("title")
let favorite = Column("favorite")
berlin = try PointOfInterest.filter(title == "Berlin").fetchOne(db)! // PointOfInterest
let paris = try PointOfInterest.fetchOne(db, key: 1) // PointOfInterest?
let favoritePois = try PointOfInterest // [PointOfInterest]
.filter(favorite)
berlin = try Place.filter(title == "Berlin").fetchOne(db)! // Place
let paris = try Place.fetchOne(db, key: 1) // Place?
let favoritePlaces = try Place // [Place]
.filter(favorite == true)
.order(title)
.fetchAll(db)
}
@@ -13,26 +13,24 @@ import GRDB
let dbQueue = DatabaseQueue() // Memory database
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL " +
")")
migrator.registerMigration("createPerson") { db in
try db.create(table: "person") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
}
migrator.registerMigration("createPets") { db in
try db.execute(
"CREATE TABLE pets (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT, " +
"ownerId INTEGER NOT NULL REFERENCES persons(id) ON DELETE CASCADE" +
")")
migrator.registerMigration("createPet") { db in
try db.create(table: "pet") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("ownerId", .integer).references("person", onDelete: .cascade)
}
}
try! migrator.migrate(dbQueue)
//
/// TableChangeObserver prints on the main thread the changes database tables.
class TableChangeObserver : NSObject, TransactionObserver {
private var changedTableNames: Set<String> = []
@@ -44,9 +42,6 @@ class TableChangeObserver : NSObject, TransactionObserver {
changedTableNames.insert(event.tableName)
}
func databaseWillCommit() throws {
}
func databaseDidCommit(_ db: Database) {
print("Changed table(s): \(changedTableNames.joined(separator: ", "))")
changedTableNames = []
@@ -57,34 +52,35 @@ class TableChangeObserver : NSObject, TransactionObserver {
}
}
// Register observer
let observer = TableChangeObserver()
dbQueue.add(transactionObserver: observer)
//
print("-- Changes 1")
try! dbQueue.inDatabase { db in
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
print("-- Changes without transaction")
try dbQueue.inDatabase { db in
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Arthur"])
let arthurId = db.lastInsertedRowID
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"])
try db.execute("INSERT INTO pets (ownerId, name) VALUES (?, ?)", arguments: [arthurId, "Barbara"])
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Barbara"])
try db.execute(sql: "INSERT INTO pet (ownerId, name) VALUES (?, ?)", arguments: [arthurId, "Barbara"])
try db.execute(sql: "DELETE FROM person WHERE id = ?", arguments: [arthurId])
}
print("-- Changes 2")
print("-- Rollbacked changes")
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO persons (name) VALUES ('Arthur')")
try db.execute("INSERT INTO persons (name) VALUES ('Barbara')")
try db.execute(sql: "INSERT INTO person (name) VALUES ('Arthur')")
try db.execute(sql: "INSERT INTO person (name) VALUES ('Barbara')")
return .rollback
}
print("-- Changes 3")
print("-- Changes wrapped in a transaction")
try dbQueue.write { db in
try db.execute("DELETE FROM persons")
try db.execute("DELETE FROM pets")
try db.execute(sql: "DELETE FROM person")
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Arthur"])
let arthurId = db.lastInsertedRowID
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Barbara"])
try db.execute(sql: "INSERT INTO pet (ownerId, name) VALUES (?, ?)", arguments: [arthurId, "Barbara"])
try db.execute(sql: "DELETE FROM person WHERE id = ?", arguments: [arthurId])
}
+230 -183
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -47,6 +47,8 @@ GRDB 4.0
- [ ] SQLite 3.27.0
- [ ] SQLCipher 4
- [ ] Mark unavailable the deprecated methods
- [ ] FTS: prefix queries
- [ ] Test NOT TESTED methods
- [ ] https://github.com/apple/swift-evolution/blob/master/proposals/0193-cross-module-inlining-and-specialization.md
Swift 4.2
+2 -2
View File
@@ -12,7 +12,7 @@ class DatabasePoolCrashTests: GRDBCrashTestCase {
func testReaderCanNotStartTransaction() {
assertCrash("DatabasePool readers can not start transactions or savepoints.") {
try dbPool.read { db in
let statement = try db.makeUpdateStatement("BEGIN TRANSACTION")
let statement = try db.makeUpdateStatement(sql: "BEGIN TRANSACTION")
}
}
}
@@ -20,7 +20,7 @@ class DatabasePoolCrashTests: GRDBCrashTestCase {
func testReaderCanNotStartSavepoint() {
assertCrash("DatabasePool readers can not start transactions or savepoints.") {
try dbPool.read { db in
let statement = try db.makeUpdateStatement("SAVEPOINT foo")
let statement = try db.makeUpdateStatement(sql: "SAVEPOINT foo")
}
}
}
+3 -3
View File
@@ -51,7 +51,7 @@ class DatabaseQueueCrashTests: GRDBCrashTestCase {
assertCrash("Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.") {
var rows: DatabaseSequence<Row>?
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (name TEXT)")
try db.execute(sql: "CREATE TABLE persons (name TEXT)")
rows = try Row.fetch(db, "SELECT * FROM persons")
}
_ = rows!.makeIterator()
@@ -62,7 +62,7 @@ class DatabaseQueueCrashTests: GRDBCrashTestCase {
assertCrash("Database was not used on the correct thread: execute your statements inside DatabaseQueue.inDatabase() or DatabaseQueue.inTransaction(). If you get this error while iterating the result of a fetch() method, consider using the array returned by fetchAll() instead.") {
var iterator: DatabaseIterator<Row>?
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (name TEXT)")
try db.execute(sql: "CREATE TABLE persons (name TEXT)")
iterator = try Row.fetch(db, "SELECT * FROM persons").makeIterator()
}
_ = iterator!.next()
@@ -79,7 +79,7 @@ class DatabaseQueueCrashTests: GRDBCrashTestCase {
let dbQueue2 = try! makeDatabaseQueue(path: dbQueuepath, configuration: dbConfiguration)
try! dbQueue1.inDatabase { db in
try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE stuffs (id INTEGER PRIMARY KEY)")
}
let queue = NSOperationQueue()
@@ -29,11 +29,11 @@ class DatabaseValueConvertibleCrashTests: GRDBCrashTestCase {
func testCrashFetchDatabaseValueConvertibleFromStatement() {
assertCrash("could not convert NULL to IntConvertible.") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
try db.execute(sql: "CREATE TABLE ints (int Int)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (1)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)")
let statement = try db.makeSelectStatement("SELECT int FROM ints ORDER BY int")
let statement = try db.makeSelectStatement(sql: "SELECT int FROM ints ORDER BY int")
let sequence = IntConvertible.fetch(statement)
for _ in sequence { }
}
@@ -43,11 +43,11 @@ class DatabaseValueConvertibleCrashTests: GRDBCrashTestCase {
func testCrashFetchAllDatabaseValueConvertibleFromStatement() {
assertCrash("could not convert NULL to IntConvertible.") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
try db.execute(sql: "CREATE TABLE ints (int Int)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (1)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)")
let statement = try db.makeSelectStatement("SELECT int FROM ints ORDER BY int")
let statement = try db.makeSelectStatement(sql: "SELECT int FROM ints ORDER BY int")
_ = IntConvertible.fetchAll(statement)
}
}
@@ -56,9 +56,9 @@ class DatabaseValueConvertibleCrashTests: GRDBCrashTestCase {
func testCrashFetchDatabaseValueConvertibleFromDatabase() {
assertCrash("could not convert NULL to IntConvertible.") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
try db.execute(sql: "CREATE TABLE ints (int Int)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (1)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)")
let sequence = IntConvertible.fetch(db, "SELECT int FROM ints ORDER BY int")
for _ in sequence { }
@@ -69,11 +69,11 @@ class DatabaseValueConvertibleCrashTests: GRDBCrashTestCase {
func testCrashFetchAllDatabaseValueConvertibleFromDatabase() {
assertCrash("could not convert NULL to IntConvertible.") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
try db.execute(sql: "CREATE TABLE ints (int Int)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (1)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)")
_ = IntConvertible.fetchAll(db, "SELECT int FROM ints ORDER BY int")
_ = IntConvertible.fetchAll(db, sql: "SELECT int FROM ints ORDER BY int")
}
}
}
+14 -14
View File
@@ -189,7 +189,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordWithEmptyPersistentDictionaryCanNotBeInserted() {
assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithEmptyPersistentDictionary().insert(db)
}
}
@@ -198,7 +198,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordWithEmptyPersistentDictionaryCanNotBeUpdated() {
assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithEmptyPersistentDictionary().update(db)
}
}
@@ -207,7 +207,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordWithEmptyPersistentDictionaryCanNotBeSaved() {
assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithEmptyPersistentDictionary().save(db)
}
}
@@ -216,7 +216,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordWithEmptyPersistentDictionaryCanNotBeDeleted() {
assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithEmptyPersistentDictionary().delete(db)
}
}
@@ -225,7 +225,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordWithEmptyPersistentDictionaryCanNotBeTestedForExistence() {
assertCrash("RecordWithEmptyPersistentDictionary.persistentDictionary: invalid empty dictionary") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE records (id INTEGER PRIMARY KEY)")
RecordWithEmptyPersistentDictionary().exists(db)
}
}
@@ -238,7 +238,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordWithNilPrimaryKeyCanNotBeUpdated() {
assertCrash("invalid primary key in <RecordWithNilPrimaryKey id:nil>") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithNilPrimaryKey().update(db)
}
}
@@ -247,7 +247,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordWithNilPrimaryKeyCanNotBeDeleted() {
assertCrash("invalid primary key in <RecordWithNilPrimaryKey id:nil>") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE records (id INTEGER PRIMARY KEY)")
try RecordWithNilPrimaryKey().delete(db)
}
}
@@ -256,7 +256,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordWithNilPrimaryKeyCanNotBeTestedForExistence() {
assertCrash("invalid primary key in <RecordWithNilPrimaryKey id:nil>") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE records (id INTEGER PRIMARY KEY)")
RecordWithNilPrimaryKey().exists(db)
}
}
@@ -269,7 +269,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordForTableWithoutPrimaryKeyCanNotBeFetchedByID() {
assertCrash("expected single column primary key in table: records") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (name TEXT)")
try db.execute(sql: "CREATE TABLE records (name TEXT)")
_ = RecordForTableWithoutPrimaryKey.fetchOne(db, key: 1)
}
}
@@ -278,7 +278,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordForTableWithoutPrimaryKeyCanNotBeUpdated() {
assertCrash("invalid primary key in <RecordForTableWithoutPrimaryKey name:\"foo\">") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (name TEXT)")
try db.execute(sql: "CREATE TABLE records (name TEXT)")
try RecordForTableWithoutPrimaryKey().update(db)
}
}
@@ -287,7 +287,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordForTableWithoutPrimaryKeyCanNotBeDeleted() {
assertCrash("invalid primary key in <RecordForTableWithoutPrimaryKey name:\"foo\">") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (name TEXT)")
try db.execute(sql: "CREATE TABLE records (name TEXT)")
try RecordForTableWithoutPrimaryKey().delete(db)
}
}
@@ -296,7 +296,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordForTableWithoutPrimaryKeyCanNotBeTestedForExistence() {
assertCrash("invalid primary key in <RecordForTableWithoutPrimaryKey name:\"foo\">") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (name TEXT)")
try db.execute(sql: "CREATE TABLE records (name TEXT)")
RecordForTableWithoutPrimaryKey().exists(db)
}
}
@@ -309,7 +309,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordForTableWithMultipleColumnsPrimaryKeyCanNotBeFetchedByID() {
assertCrash("expected single column primary key in table: records") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (a TEXT, b TEXT, PRIMARY KEY(a,b))")
try db.execute(sql: "CREATE TABLE records (a TEXT, b TEXT, PRIMARY KEY(a,b))")
_ = RecordForTableWithMultipleColumnsPrimaryKey.fetchOne(db, key: 1)
}
}
@@ -322,7 +322,7 @@ class RecordCrashTests: GRDBCrashTestCase {
func testRecordWithRowIDPrimaryKeyNotExposedInPersistentDictionaryCanNotBeInserted() {
assertCrash("invalid primary key in <RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary name:\"foo\">") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE records (id INTEGER PRIMARY KEY, name TEXT)")
try db.execute(sql: "CREATE TABLE records (id INTEGER PRIMARY KEY, name TEXT)")
try RecordWithRowIDPrimaryKeyNotExposedInPersistentDictionary().update(db)
}
}
@@ -12,11 +12,11 @@ class StatementColumnConvertibleCrashTests: GRDBCrashTestCase {
func testCrashFetchStatementColumnConvertibleFromStatement() {
assertCrash("could not convert NULL to Int.") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
try db.execute(sql: "CREATE TABLE ints (int Int)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (1)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)")
let statement = try db.makeSelectStatement("SELECT int FROM ints ORDER BY int")
let statement = try db.makeSelectStatement(sql: "SELECT int FROM ints ORDER BY int")
let sequence = try Int.fetch(statement)
for _ in sequence { }
}
@@ -26,11 +26,11 @@ class StatementColumnConvertibleCrashTests: GRDBCrashTestCase {
func testCrashFetchAllStatementColumnConvertibleFromStatement() {
assertCrash("could not convert NULL to Int.") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
try db.execute(sql: "CREATE TABLE ints (int Int)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (1)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)")
let statement = try db.makeSelectStatement("SELECT int FROM ints ORDER BY int")
let statement = try db.makeSelectStatement(sql: "SELECT int FROM ints ORDER BY int")
_ = try Int.fetchAll(statement)
}
}
@@ -39,9 +39,9 @@ class StatementColumnConvertibleCrashTests: GRDBCrashTestCase {
func testCrashFetchStatementColumnConvertibleFromDatabase() {
assertCrash("could not convert NULL to Int.") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
try db.execute(sql: "CREATE TABLE ints (int Int)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (1)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)")
let sequence = try Int.fetch(db, "SELECT int FROM ints ORDER BY int")
for _ in sequence { }
@@ -52,11 +52,11 @@ class StatementColumnConvertibleCrashTests: GRDBCrashTestCase {
func testCrashFetchAllStatementColumnConvertibleFromDatabase() {
assertCrash("could not convert NULL to Int.") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE ints (int Int)")
try db.execute("INSERT INTO ints (int) VALUES (1)")
try db.execute("INSERT INTO ints (int) VALUES (NULL)")
try db.execute(sql: "CREATE TABLE ints (int Int)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (1)")
try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)")
_ = try Int.fetchAll(db, "SELECT int FROM ints ORDER BY int")
_ = try Int.fetchAll(db, sql: "SELECT int FROM ints ORDER BY int")
}
}
}
+32 -30
View File
@@ -12,66 +12,68 @@ class StatementCrashTests: GRDBCrashTestCase {
func testInvalidStatementArguments() {
assertCrash("SQLite error 1 with statement `INSERT INTO persons (name, age) VALUES (:name, :age)`: missing statement argument(s): age") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try! db.execute("INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur"])
try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)")
try! db.execute(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)", arguments: ["name": "Arthur"])
}
}
assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Arthur', ?);`: wrong number of statement arguments: 0") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);" +
"INSERT INTO persons (name, age) VALUES ('Barbara', ?);")
try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)")
try db.execute(sql: """
INSERT INTO persons (name, age) VALUES ('Arthur', ?);
INSERT INTO persons (name, age) VALUES ('Barbara', ?);
""")
}
}
assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Barbara', ?);`: wrong number of statement arguments: 0") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);" +
"INSERT INTO persons (name, age) VALUES ('Barbara', ?);",
arguments: [41])
try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)")
try db.execute(sql: """
INSERT INTO persons (name, age) VALUES ('Arthur', ?);
INSERT INTO persons (name, age) VALUES ('Barbara', ?);
""", arguments: [41])
}
}
assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Arthur', :age1);`: missing statement argument(s): age1") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
"INSERT INTO persons (name, age) VALUES ('Barbara', :age2);")
try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)")
try db.execute(sql: """
INSERT INTO persons (name, age) VALUES ('Arthur', :age1);
INSERT INTO persons (name, age) VALUES ('Barbara', :age2);
""")
}
}
assertCrash("SQLite error 21 with statement `INSERT INTO persons (name, age) VALUES ('Barbara', :age2);`: missing statement argument(s): age2") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
"INSERT INTO persons (name, age) VALUES ('Barbara', :age2);",
arguments: ["age1": 41])
try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)")
try db.execute(sql: """
INSERT INTO persons (name, age) VALUES ('Arthur', :age1);
INSERT INTO persons (name, age) VALUES ('Barbara', :age2);
""", arguments: ["age1": 41])
}
}
assertCrash("SQLite error 21: wrong number of statement arguments: 3") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', :age1);" +
"INSERT INTO persons (name, age) VALUES ('Arthur', :age2);",
arguments: [41, 32, 17])
try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)")
try db.execute(sql: """
INSERT INTO persons (name, age) VALUES ('Arthur', :age1);
INSERT INTO persons (name, age) VALUES ('Arthur', :age2);
""", arguments: [41, 32, 17])
}
}
assertCrash("SQLite error 21: wrong number of statement arguments: 3") {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (name TEXT, age INT)")
try db.execute(
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);" +
"INSERT INTO persons (name, age) VALUES ('Arthur', ?);",
arguments: [41, 32, 17])
try db.execute(sql: "CREATE TABLE persons (name TEXT, age INT)")
try db.execute(sql: """
INSERT INTO persons (name, age) VALUES ('Arthur', ?);
INSERT INTO persons (name, age) VALUES ('Arthur', ?);
""", arguments: [41, 32, 17])
}
}
}
@@ -55,11 +55,11 @@ class AssociationRowScopeSearchTests: GRDBTestCase {
t.column("id", .integer).primaryKey()
t.column("bid", .integer).references("b")
}
try db.execute("INSERT INTO a (id) VALUES (1)")
try db.execute("INSERT INTO b (id, aid) VALUES (2, 1)")
try db.execute("INSERT INTO c (id, aid, bid) VALUES (3, NULL, 2)")
try db.execute("INSERT INTO c (id, aid, bid) VALUES (4, 1, NULL)")
try db.execute("INSERT INTO d (id, bid) VALUES (5, 2)")
try db.execute(sql: "INSERT INTO a (id) VALUES (1)")
try db.execute(sql: "INSERT INTO b (id, aid) VALUES (2, 1)")
try db.execute(sql: "INSERT INTO c (id, aid, bid) VALUES (3, NULL, 2)")
try db.execute(sql: "INSERT INTO c (id, aid, bid) VALUES (4, 1, NULL)")
try db.execute(sql: "INSERT INTO d (id, bid) VALUES (5, 2)")
}
}
+3 -3
View File
@@ -13,13 +13,13 @@ class CGFloatTests: GRDBTestCase {
func testCGFLoat() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE points (x DOUBLE, y DOUBLE)")
try db.execute(sql: "CREATE TABLE points (x DOUBLE, y DOUBLE)")
let x: CGFloat = 1
let y: CGFloat? = nil
try db.execute("INSERT INTO points VALUES (?,?)", arguments: [x, y])
try db.execute(sql: "INSERT INTO points VALUES (?,?)", arguments: [x, y])
let row = try Row.fetchOne(db, "SELECT * FROM points")!
let row = try Row.fetchOne(db, sql: "SELECT * FROM points")!
let fetchedX: CGFloat = row["x"]
let fetchedY: CGFloat? = row["y"]
XCTAssertEqual(x, fetchedX)
+9 -9
View File
@@ -70,9 +70,9 @@ class ColumnExpressionTests: GRDBTestCase {
// Test FTS3 match expression
let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo"))
let literal = expression.literal
XCTAssertEqual(literal.sql, "(\"name\" MATCH ?)")
XCTAssertEqual(literal.arguments, ["foo"])
let sqlLiteral = expression.sqlLiteral
XCTAssertEqual(sqlLiteral.sql, "(\"name\" MATCH ?)")
XCTAssertEqual(sqlLiteral.arguments, ["foo"])
}
}
@@ -131,9 +131,9 @@ class ColumnExpressionTests: GRDBTestCase {
// Test FTS3 match expression
let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo"))
let literal = expression.literal
XCTAssertEqual(literal.sql, "(\"name\" MATCH ?)")
XCTAssertEqual(literal.arguments, ["foo"])
let sqlLiteral = expression.sqlLiteral
XCTAssertEqual(sqlLiteral.sql, "(\"name\" MATCH ?)")
XCTAssertEqual(sqlLiteral.arguments, ["foo"])
}
}
@@ -180,9 +180,9 @@ class ColumnExpressionTests: GRDBTestCase {
// Test FTS3 match expression
let expression = try Player.CodingKeys.name.match(FTS3Pattern(rawPattern: "foo"))
let literal = expression.literal
XCTAssertEqual(literal.sql, "(\"full_name\" MATCH ?)")
XCTAssertEqual(literal.arguments, ["foo"])
let sqlLiteral = expression.sqlLiteral
XCTAssertEqual(sqlLiteral.sql, "(\"full_name\" MATCH ?)")
XCTAssertEqual(sqlLiteral.arguments, ["foo"])
}
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ class ColumnInfoTests: GRDBTestCase {
func testColumnInfo() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("""
try db.execute(sql: """
CREATE TABLE t (
a INT,
b TEXT,
+2 -2
View File
@@ -22,7 +22,7 @@ class DataMemoryTests: GRDBTestCase {
// https://forums.swift.org/t/swift-5-how-to-test-data-bytesnocopydeallocator/20299/2?u=gwendal.roue
let data = Data(repeating: 0xaa, count: 15)
let rows = try Row.fetchCursor(db, "SELECT ?", arguments: [data])
let rows = try Row.fetchCursor(db, sql: "SELECT ?", arguments: [data])
while let row = try rows.next() {
let blobPointer = sqlite3_column_blob(row.sqliteStatement, 0)
@@ -45,7 +45,7 @@ class DataMemoryTests: GRDBTestCase {
}
}
let row = try Row.fetchOne(db, "SELECT ?", arguments: [data])!
let row = try Row.fetchOne(db, sql: "SELECT ?", arguments: [data])!
let dbValue = row.first!.1 // TODO: think about exposing a (column:,databaseValue:) tuple
switch dbValue.storage {
case .blob(let data):
@@ -62,8 +62,8 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
XCTAssertNotNil(deallocationWitness)
XCTAssertEqual(transactionCount, 0)
try db.execute(startSQL)
try db.execute(endSQL)
try db.execute(sql: startSQL)
try db.execute(sql: endSQL)
switch expectedCompletion {
case .commit:
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
@@ -73,7 +73,7 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
XCTAssertNil(deallocationWitness)
try db.inTransaction {
try db.execute("DROP TABLE IF EXISTS t; CREATE TABLE t(a); ")
try db.execute(sql: "DROP TABLE IF EXISTS t; CREATE TABLE t(a); ")
return .commit
}
switch expectedCompletion {
@@ -91,7 +91,7 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.writeWithoutTransaction { db in
var transactionCount = 0
try db.execute(startSQL)
try db.execute(sql: startSQL)
weak var deallocationWitness: Witness? = nil
do {
@@ -106,7 +106,7 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
XCTAssertNotNil(deallocationWitness)
XCTAssertEqual(transactionCount, 0)
try db.execute(endSQL)
try db.execute(sql: endSQL)
switch expectedCompletion {
case .commit:
XCTAssertEqual(transactionCount, 1, "\(startSQL); \(endSQL)")
@@ -116,7 +116,7 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase {
XCTAssertNil(deallocationWitness)
try db.inTransaction {
try db.execute("DROP TABLE IF EXISTS t; CREATE TABLE t(a); ")
try db.execute(sql: "DROP TABLE IF EXISTS t; CREATE TABLE t(a); ")
return .commit
}
switch expectedCompletion {
+49 -49
View File
@@ -34,7 +34,7 @@ class DatabaseAggregateTests: GRDBTestCase {
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)
XCTAssertTrue(try DatabaseValue.fetchOne(db, sql: "SELECT f()")!.isNull)
}
}
@@ -49,7 +49,7 @@ class DatabaseAggregateTests: GRDBTestCase {
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))
XCTAssertEqual(try Int64.fetchOne(db, sql: "SELECT f()")!, Int64(1))
}
}
@@ -64,7 +64,7 @@ class DatabaseAggregateTests: GRDBTestCase {
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)
XCTAssertEqual(try Double.fetchOne(db, sql: "SELECT f()")!, 1e100)
}
}
@@ -79,7 +79,7 @@ class DatabaseAggregateTests: GRDBTestCase {
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")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT f()")!, "foo")
}
}
@@ -94,7 +94,7 @@ class DatabaseAggregateTests: GRDBTestCase {
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))
XCTAssertEqual(try Data.fetchOne(db, sql: "SELECT f()")!, "foo".data(using: .utf8))
}
}
@@ -109,7 +109,7 @@ class DatabaseAggregateTests: GRDBTestCase {
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)
XCTAssertTrue(try CustomValueType.fetchOne(db, sql: "SELECT f()") != nil)
}
}
@@ -129,12 +129,12 @@ class DatabaseAggregateTests: GRDBTestCase {
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)])!)
XCTAssertFalse(try Bool.fetchOne(db, "SELECT f(?)", arguments: [Data()])!)
XCTAssertTrue(try Bool.fetchOne(db, sql: "SELECT f(NULL)")!)
XCTAssertFalse(try Bool.fetchOne(db, sql: "SELECT f(1)")!)
XCTAssertFalse(try Bool.fetchOne(db, sql: "SELECT f(1.1)")!)
XCTAssertFalse(try Bool.fetchOne(db, sql: "SELECT f('foo')")!)
XCTAssertFalse(try Bool.fetchOne(db, sql: "SELECT f(?)", arguments: ["foo".data(using: .utf8)])!)
XCTAssertFalse(try Bool.fetchOne(db, sql: "SELECT f(?)", arguments: [Data()])!)
}
}
@@ -152,9 +152,9 @@ class DatabaseAggregateTests: GRDBTestCase {
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)
XCTAssertTrue(try Int64.fetchOne(db, sql: "SELECT f(NULL)") == nil)
XCTAssertEqual(try Int64.fetchOne(db, sql: "SELECT f(1)")!, 1)
XCTAssertEqual(try Int64.fetchOne(db, sql: "SELECT f(1.1)")!, 1)
}
}
@@ -172,9 +172,9 @@ class DatabaseAggregateTests: GRDBTestCase {
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)
XCTAssertTrue(try Double.fetchOne(db, sql: "SELECT f(NULL)") == nil)
XCTAssertEqual(try Double.fetchOne(db, sql: "SELECT f(1)")!, 1.0)
XCTAssertEqual(try Double.fetchOne(db, sql: "SELECT f(1.1)")!, 1.1)
}
}
@@ -192,8 +192,8 @@ class DatabaseAggregateTests: GRDBTestCase {
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")
XCTAssertTrue(try String.fetchOne(db, sql: "SELECT f(NULL)") == nil)
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT f('foo')")!, "foo")
}
}
@@ -211,9 +211,9 @@ class DatabaseAggregateTests: GRDBTestCase {
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))
XCTAssertEqual(try Data.fetchOne(db, "SELECT f(?)", arguments: [Data()])!, Data())
XCTAssertTrue(try Data.fetchOne(db, sql: "SELECT f(NULL)") == nil)
XCTAssertEqual(try Data.fetchOne(db, sql: "SELECT f(?)", arguments: ["foo".data(using: .utf8)])!, "foo".data(using: .utf8))
XCTAssertEqual(try Data.fetchOne(db, sql: "SELECT f(?)", arguments: [Data()])!, Data())
}
}
@@ -231,8 +231,8 @@ class DatabaseAggregateTests: GRDBTestCase {
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)
XCTAssertTrue(try CustomValueType.fetchOne(db, sql: "SELECT f(NULL)") == nil)
XCTAssertTrue(try CustomValueType.fetchOne(db, sql: "SELECT f('CustomValueType')") != nil)
}
}
@@ -249,9 +249,9 @@ class DatabaseAggregateTests: GRDBTestCase {
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")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT f()")!, "foo")
do {
try db.execute("SELECT f(1)")
try db.execute(sql: "SELECT f(1)")
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -276,11 +276,11 @@ class DatabaseAggregateTests: GRDBTestCase {
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)
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT upper(?)", arguments: ["Roué"])!, "ROUé")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT f(?)", arguments: ["Roué"])!, "ROUÉ")
XCTAssertTrue(try String.fetchOne(db, sql: "SELECT f(NULL)") == nil)
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -306,9 +306,9 @@ class DatabaseAggregateTests: GRDBTestCase {
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)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f(1, 2)")!, 3)
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -333,9 +333,9 @@ class DatabaseAggregateTests: GRDBTestCase {
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)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f()")!, 0)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f(1)")!, 1)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f(1, 1)")!, 2)
}
}
@@ -355,7 +355,7 @@ class DatabaseAggregateTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -378,7 +378,7 @@ class DatabaseAggregateTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode.rawValue, 123)
@@ -401,7 +401,7 @@ class DatabaseAggregateTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode.rawValue, 123)
@@ -424,7 +424,7 @@ class DatabaseAggregateTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -449,7 +449,7 @@ class DatabaseAggregateTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -470,7 +470,7 @@ class DatabaseAggregateTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode.rawValue, 123)
@@ -491,7 +491,7 @@ class DatabaseAggregateTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode.rawValue, 123)
@@ -512,7 +512,7 @@ class DatabaseAggregateTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -541,7 +541,7 @@ class DatabaseAggregateTests: GRDBTestCase {
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)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f(a) FROM (SELECT 1 AS a UNION ALL SELECT 2 UNION ALL SELECT 3)")!, 6)
}
}
@@ -561,7 +561,7 @@ class DatabaseAggregateTests: GRDBTestCase {
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)")!
let row = try Row.fetchOne(db, sql: "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[0], 6)
XCTAssertEqual(row[1], 12)
}
@@ -596,7 +596,7 @@ class DatabaseAggregateTests: GRDBTestCase {
try dbQueue.inDatabase { db in
XCTAssertEqual(allocationCount, 0)
XCTAssertEqual(aliveCount, 0)
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTAssertEqual(allocationCount, 1)
XCTAssertEqual(aliveCount, 0)
}
@@ -631,7 +631,7 @@ class DatabaseAggregateTests: GRDBTestCase {
dbQueue.inDatabase { db in
XCTAssertEqual(allocationCount, 0)
XCTAssertEqual(aliveCount, 0)
_ = try? db.execute("SELECT f()")
_ = try? db.execute(sql: "SELECT f()")
XCTAssertEqual(allocationCount, 1)
XCTAssertEqual(aliveCount, 0)
}
@@ -665,7 +665,7 @@ class DatabaseAggregateTests: GRDBTestCase {
dbQueue.inDatabase { db in
XCTAssertEqual(allocationCount, 0)
XCTAssertEqual(aliveCount, 0)
_ = try? db.execute("SELECT f()")
_ = try? db.execute(sql: "SELECT f()")
XCTAssertEqual(allocationCount, 1)
XCTAssertEqual(aliveCount, 0)
}
+26 -26
View File
@@ -12,37 +12,37 @@ class DatabaseCollationTests: GRDBTestCase {
func testDefaultCollations() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE strings (id INTEGER PRIMARY KEY, name TEXT)")
try db.execute("INSERT INTO strings VALUES (1, '1')")
try db.execute("INSERT INTO strings VALUES (2, '2')")
try db.execute("INSERT INTO strings VALUES (3, '10')")
try db.execute("INSERT INTO strings VALUES (4, 'a')")
try db.execute("INSERT INTO strings VALUES (5, 'à')")
try db.execute("INSERT INTO strings VALUES (6, 'A')")
try db.execute("INSERT INTO strings VALUES (7, 'Z')")
try db.execute("INSERT INTO strings VALUES (8, 'z')")
try db.execute(sql: "CREATE TABLE strings (id INTEGER PRIMARY KEY, name TEXT)")
try db.execute(sql: "INSERT INTO strings VALUES (1, '1')")
try db.execute(sql: "INSERT INTO strings VALUES (2, '2')")
try db.execute(sql: "INSERT INTO strings VALUES (3, '10')")
try db.execute(sql: "INSERT INTO strings VALUES (4, 'a')")
try db.execute(sql: "INSERT INTO strings VALUES (5, 'à')")
try db.execute(sql: "INSERT INTO strings VALUES (6, 'A')")
try db.execute(sql: "INSERT INTO strings VALUES (7, 'Z')")
try db.execute(sql: "INSERT INTO strings VALUES (8, 'z')")
// Swift 4.2 and Swift 4.1 don't sort strings in the same way
if "z" < "à" {
XCTAssertEqual(
try Int.fetchAll(db, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"),
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"),
[1,3,2,6,7,4,8,5])
} else {
XCTAssertEqual(
try Int.fetchAll(db, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"),
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"),
[1,3,2,6,7,4,5,8])
}
XCTAssertEqual(
try Int.fetchAll(db, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.caseInsensitiveCompare.name), id"),
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.caseInsensitiveCompare.name), id"),
[1,3,2,4,6,5,7,8])
XCTAssertEqual(
try Int.fetchAll(db, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedCaseInsensitiveCompare.name), id"),
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedCaseInsensitiveCompare.name), id"),
[1,3,2,4,6,5,7,8])
XCTAssertEqual(
try Int.fetchAll(db, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedCompare.name), id"),
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedCompare.name), id"),
[1,3,2,4,6,5,8,7])
XCTAssertEqual(
try Int.fetchAll(db, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedStandardCompare.name), id"),
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedStandardCompare.name), id"),
[1,2,3,4,6,5,8,7])
}
}
@@ -63,18 +63,18 @@ class DatabaseCollationTests: GRDBTestCase {
dbQueue.add(collation: collation)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE strings (id INTEGER PRIMARY KEY, name TEXT COLLATE LOCALIZED_STANDARD)")
try db.execute("INSERT INTO strings VALUES (1, 'a')")
try db.execute("INSERT INTO strings VALUES (2, 'aa')")
try db.execute("INSERT INTO strings VALUES (3, 'aaa')")
try db.execute("INSERT INTO strings VALUES (4, 'b')")
try db.execute("INSERT INTO strings VALUES (5, 'bb')")
try db.execute("INSERT INTO strings VALUES (6, 'bbb')")
try db.execute("INSERT INTO strings VALUES (7, 'c')")
try db.execute("INSERT INTO strings VALUES (8, 'cc')")
try db.execute("INSERT INTO strings VALUES (9, 'ccc')")
try db.execute(sql: "CREATE TABLE strings (id INTEGER PRIMARY KEY, name TEXT COLLATE LOCALIZED_STANDARD)")
try db.execute(sql: "INSERT INTO strings VALUES (1, 'a')")
try db.execute(sql: "INSERT INTO strings VALUES (2, 'aa')")
try db.execute(sql: "INSERT INTO strings VALUES (3, 'aaa')")
try db.execute(sql: "INSERT INTO strings VALUES (4, 'b')")
try db.execute(sql: "INSERT INTO strings VALUES (5, 'bb')")
try db.execute(sql: "INSERT INTO strings VALUES (6, 'bbb')")
try db.execute(sql: "INSERT INTO strings VALUES (7, 'c')")
try db.execute(sql: "INSERT INTO strings VALUES (8, 'cc')")
try db.execute(sql: "INSERT INTO strings VALUES (9, 'ccc')")
let ids = try Int.fetchAll(db, "SELECT id FROM strings ORDER BY NAME")
let ids = try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY NAME")
XCTAssertEqual(ids, [1,4,7,2,5,8,3,6,9])
}
}
+5 -5
View File
@@ -14,18 +14,18 @@ class DatabaseCursorTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
let cursor = try Int.fetchCursor(db, "SELECT 1 WHERE 0")
let cursor = try Int.fetchCursor(db, sql: "SELECT 1 WHERE 0")
XCTAssert(try cursor.next() == nil) // end
XCTAssert(try cursor.next() == nil) // past the end
}
do {
let cursor = try Int.fetchCursor(db, "SELECT 1")
let cursor = try Int.fetchCursor(db, sql: "SELECT 1")
XCTAssertEqual(try cursor.next()!, 1)
XCTAssert(try cursor.next() == nil) // end
XCTAssert(try cursor.next() == nil) // past the end
}
do {
let cursor = try Int.fetchCursor(db, "SELECT 1 UNION ALL SELECT 2")
let cursor = try Int.fetchCursor(db, sql: "SELECT 1 UNION ALL SELECT 2")
XCTAssertEqual(try cursor.next()!, 1)
XCTAssertEqual(try cursor.next()!, 2)
XCTAssert(try cursor.next() == nil) // end
@@ -40,7 +40,7 @@ class DatabaseCursorTests: GRDBTestCase {
let customError = NSError(domain: "Custom", code: 0xDEAD)
dbQueue.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError })
try dbQueue.inDatabase { db in
let cursor = try Int.fetchCursor(db, "SELECT throw()")
let cursor = try Int.fetchCursor(db, sql: "SELECT throw()")
do {
_ = try cursor.next()
XCTFail()
@@ -59,7 +59,7 @@ class DatabaseCursorTests: GRDBTestCase {
let customError = DatabaseError(resultCode: ResultCode(rawValue: 0xDEAD), message: "custom error")
dbQueue.add(function: DatabaseFunction("throw", argumentCount: 0, pure: true) { _ in throw customError })
try dbQueue.inDatabase { db in
let cursor = try Int.fetchCursor(db, "SELECT throw()")
let cursor = try Int.fetchCursor(db, sql: "SELECT throw()")
do {
_ = try cursor.next()
XCTFail()
@@ -69,7 +69,7 @@ class DatabaseDateDecodingStrategyTests: GRDBTestCase {
databaseValue: DatabaseValueConvertible?,
with test: (Date?) -> Void) throws
{
let request = SQLRequest<Void>("SELECT ? AS date", arguments: [databaseValue])
let request = SQLRequest<Void>(sql: "SELECT ? AS date", arguments: [databaseValue])
do {
// test decoding straight from SQLite
let record = try T.fetchOne(db, request)!
+14 -14
View File
@@ -24,10 +24,10 @@ class DatabaseErrorTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
do {
try dbQueue.inTransaction { db in
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
sqlQueries.removeAll()
try db.execute("INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"])
try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"])
XCTFail()
return .commit
}
@@ -55,10 +55,10 @@ class DatabaseErrorTests: GRDBTestCase {
do {
try db.inSavepoint {
XCTAssertTrue(db.isInsideTransaction)
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
sqlQueries.removeAll()
try db.execute("INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"])
try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"])
XCTFail()
return .commit
}
@@ -82,14 +82,14 @@ class DatabaseErrorTests: GRDBTestCase {
func testDatabaseErrorThrownByUpdateStatementContainSQLAndArguments() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
}
// db.execute(sql, arguments)
try dbQueue.inDatabase { db in
do {
try db.execute("INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"])
try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"])
XCTFail()
} catch let error as DatabaseError {
// SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
@@ -105,7 +105,7 @@ class DatabaseErrorTests: GRDBTestCase {
// statement.execute(arguments)
try dbQueue.inDatabase { db in
do {
let statement = try db.makeUpdateStatement("INSERT INTO pets (masterId, name) VALUES (?, ?)")
let statement = try db.makeUpdateStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)")
try statement.execute(arguments: [1, "Bobby"])
XCTFail()
} catch let error as DatabaseError {
@@ -122,7 +122,7 @@ class DatabaseErrorTests: GRDBTestCase {
// statement.execute()
try dbQueue.inDatabase { db in
do {
let statement = try db.makeUpdateStatement("INSERT INTO pets (masterId, name) VALUES (?, ?)")
let statement = try db.makeUpdateStatement(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)")
statement.arguments = [1, "Bobby"]
try statement.execute()
XCTFail()
@@ -142,7 +142,7 @@ class DatabaseErrorTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
try db.execute("""
try db.execute(sql: """
CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, age INT);
CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT);
INSERT INTO pets (masterId, name) VALUES (1, 'Bobby')
@@ -166,7 +166,7 @@ class DatabaseErrorTests: GRDBTestCase {
try db.create(table: "parents") { $0.column("id", .integer).primaryKey() }
try db.create(table: "children") { $0.column("parentId", .integer).references("parents") }
do {
try db.execute("INSERT INTO children (parentId) VALUES (1)")
try db.execute(sql: "INSERT INTO children (parentId) VALUES (1)")
} catch let error as DatabaseError {
// SQLITE_CONSTRAINT_FOREIGNKEY was added in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
@@ -182,7 +182,7 @@ class DatabaseErrorTests: GRDBTestCase {
try db.create(table: "parents") { $0.column("id", .integer).primaryKey() }
try db.create(table: "children") { $0.column("parentId", .integer).references("parents") }
do {
try db.execute("INSERT INTO children (parentId) VALUES (1)")
try db.execute(sql: "INSERT INTO children (parentId) VALUES (1)")
} catch let error as NSError {
XCTAssertEqual(DatabaseError.errorDomain, "GRDB.DatabaseError")
XCTAssertEqual(error.domain, DatabaseError.errorDomain)
+47 -47
View File
@@ -31,25 +31,25 @@ class DatabaseFunctionTests: GRDBTestCase {
// See Database.setupDefaultFunctions()
let capitalize = DatabaseFunction.capitalize
XCTAssertEqual(try String.fetchOne(db, "SELECT \(capitalize.name)('jérÔME')"), "Jérôme")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(capitalize.name)('jérÔME')"), "Jérôme")
let lowercase = DatabaseFunction.lowercase
XCTAssertEqual(try String.fetchOne(db, "SELECT \(lowercase.name)('jérÔME')"), "jérôme")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(lowercase.name)('jérÔME')"), "jérôme")
let uppercase = DatabaseFunction.uppercase
XCTAssertEqual(try String.fetchOne(db, "SELECT \(uppercase.name)('jérÔME')"), "JÉRÔME")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(uppercase.name)('jérÔME')"), "JÉRÔME")
if #available(iOS 9.0, OSX 10.11, *) {
// Locale-dependent tests. Are they fragile?
let localizedCapitalize = DatabaseFunction.localizedCapitalize
XCTAssertEqual(try String.fetchOne(db, "SELECT \(localizedCapitalize.name)('jérÔME')"), "Jérôme")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(localizedCapitalize.name)('jérÔME')"), "Jérôme")
let localizedLowercase = DatabaseFunction.localizedLowercase
XCTAssertEqual(try String.fetchOne(db, "SELECT \(localizedLowercase.name)('jérÔME')"), "jérôme")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(localizedLowercase.name)('jérÔME')"), "jérôme")
let localizedUppercase = DatabaseFunction.localizedUppercase
XCTAssertEqual(try String.fetchOne(db, "SELECT \(localizedUppercase.name)('jérÔME')"), "JÉRÔME")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT \(localizedUppercase.name)('jérÔME')"), "JÉRÔME")
}
}
}
@@ -63,7 +63,7 @@ class DatabaseFunctionTests: GRDBTestCase {
}
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
XCTAssertTrue(try DatabaseValue.fetchOne(db, "SELECT f()")!.isNull)
XCTAssertTrue(try DatabaseValue.fetchOne(db, sql: "SELECT f()")!.isNull)
}
}
@@ -74,7 +74,7 @@ class DatabaseFunctionTests: GRDBTestCase {
}
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int64.fetchOne(db, "SELECT f()")!, Int64(1))
XCTAssertEqual(try Int64.fetchOne(db, sql: "SELECT f()")!, Int64(1))
}
}
@@ -85,7 +85,7 @@ class DatabaseFunctionTests: GRDBTestCase {
}
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Double.fetchOne(db, "SELECT f()")!, 1e100)
XCTAssertEqual(try Double.fetchOne(db, sql: "SELECT f()")!, 1e100)
}
}
@@ -96,7 +96,7 @@ class DatabaseFunctionTests: GRDBTestCase {
}
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
XCTAssertEqual(try String.fetchOne(db, "SELECT f()")!, "foo")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT f()")!, "foo")
}
}
@@ -107,7 +107,7 @@ class DatabaseFunctionTests: GRDBTestCase {
}
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Data.fetchOne(db, "SELECT f()")!, "foo".data(using: .utf8))
XCTAssertEqual(try Data.fetchOne(db, sql: "SELECT f()")!, "foo".data(using: .utf8))
}
}
@@ -118,7 +118,7 @@ class DatabaseFunctionTests: GRDBTestCase {
}
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
XCTAssertTrue(try CustomValueType.fetchOne(db, "SELECT f()") != nil)
XCTAssertTrue(try CustomValueType.fetchOne(db, sql: "SELECT f()") != nil)
}
}
@@ -131,12 +131,12 @@ class DatabaseFunctionTests: GRDBTestCase {
}
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)])!)
XCTAssertFalse(try Bool.fetchOne(db, "SELECT f(?)", arguments: [Data()])!)
XCTAssertTrue(try Bool.fetchOne(db, sql: "SELECT f(NULL)")!)
XCTAssertFalse(try Bool.fetchOne(db, sql: "SELECT f(1)")!)
XCTAssertFalse(try Bool.fetchOne(db, sql: "SELECT f(1.1)")!)
XCTAssertFalse(try Bool.fetchOne(db, sql: "SELECT f('foo')")!)
XCTAssertFalse(try Bool.fetchOne(db, sql: "SELECT f(?)", arguments: ["foo".data(using: .utf8)])!)
XCTAssertFalse(try Bool.fetchOne(db, sql: "SELECT f(?)", arguments: [Data()])!)
}
}
@@ -147,9 +147,9 @@ class DatabaseFunctionTests: GRDBTestCase {
}
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)
XCTAssertTrue(try Int64.fetchOne(db, sql: "SELECT f(NULL)") == nil)
XCTAssertEqual(try Int64.fetchOne(db, sql: "SELECT f(1)")!, 1)
XCTAssertEqual(try Int64.fetchOne(db, sql: "SELECT f(1.1)")!, 1)
}
}
@@ -160,9 +160,9 @@ class DatabaseFunctionTests: GRDBTestCase {
}
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)
XCTAssertTrue(try Double.fetchOne(db, sql: "SELECT f(NULL)") == nil)
XCTAssertEqual(try Double.fetchOne(db, sql: "SELECT f(1)")!, 1.0)
XCTAssertEqual(try Double.fetchOne(db, sql: "SELECT f(1.1)")!, 1.1)
}
}
@@ -173,8 +173,8 @@ class DatabaseFunctionTests: GRDBTestCase {
}
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")
XCTAssertTrue(try String.fetchOne(db, sql: "SELECT f(NULL)") == nil)
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT f('foo')")!, "foo")
}
}
@@ -185,9 +185,9 @@ class DatabaseFunctionTests: GRDBTestCase {
}
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))
XCTAssertEqual(try Data.fetchOne(db, "SELECT f(?)", arguments: [Data()])!, Data())
XCTAssertTrue(try Data.fetchOne(db, sql: "SELECT f(NULL)") == nil)
XCTAssertEqual(try Data.fetchOne(db, sql: "SELECT f(?)", arguments: ["foo".data(using: .utf8)])!, "foo".data(using: .utf8))
XCTAssertEqual(try Data.fetchOne(db, sql: "SELECT f(?)", arguments: [Data()])!, Data())
}
}
@@ -198,8 +198,8 @@ class DatabaseFunctionTests: GRDBTestCase {
}
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)
XCTAssertTrue(try CustomValueType.fetchOne(db, sql: "SELECT f(NULL)") == nil)
XCTAssertTrue(try CustomValueType.fetchOne(db, sql: "SELECT f('CustomValueType')") != nil)
}
}
@@ -212,9 +212,9 @@ class DatabaseFunctionTests: GRDBTestCase {
}
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
XCTAssertEqual(try String.fetchOne(db, "SELECT f()")!, "foo")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT f()")!, "foo")
do {
try db.execute("SELECT f(1)")
try db.execute(sql: "SELECT f(1)")
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -232,11 +232,11 @@ class DatabaseFunctionTests: GRDBTestCase {
}
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)
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT upper(?)", arguments: ["Roué"])!, "ROUé")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT f(?)", arguments: ["Roué"])!, "ROUÉ")
XCTAssertTrue(try String.fetchOne(db, sql: "SELECT f(NULL)") == nil)
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -255,9 +255,9 @@ class DatabaseFunctionTests: GRDBTestCase {
}
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT f(1, 2)")!, 3)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f(1, 2)")!, 3)
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -275,9 +275,9 @@ class DatabaseFunctionTests: GRDBTestCase {
}
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)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f()")!, 0)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f(1)")!, 1)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f(1, 1)")!, 2)
}
}
@@ -291,7 +291,7 @@ class DatabaseFunctionTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -308,7 +308,7 @@ class DatabaseFunctionTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode.rawValue, 123)
@@ -325,7 +325,7 @@ class DatabaseFunctionTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode.rawValue, 123)
@@ -342,7 +342,7 @@ class DatabaseFunctionTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
do {
try db.execute("SELECT f()")
try db.execute(sql: "SELECT f()")
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -364,7 +364,7 @@ class DatabaseFunctionTests: GRDBTestCase {
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
x = 321
XCTAssertEqual(try Int.fetchOne(db, "SELECT f()")!, 321)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f()")!, 321)
}
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ class DatabaseLogErrorTests: GRDBTestCase {
func testErrorLog() throws {
let dbQueue = try makeDatabaseQueue()
dbQueue.inDatabase { db in
_ = try? db.execute("Abracadabra")
_ = try? db.execute(sql: "Abracadabra")
}
XCTAssertEqual(lastResultCode!, ResultCode.SQLITE_ERROR)
// Don't check for exact error message because it depends on SQLite version
+32 -32
View File
@@ -14,14 +14,14 @@ class DatabaseMigratorTests : GRDBTestCase {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute("""
try db.execute(sql: """
CREATE TABLE persons (
id INTEGER PRIMARY KEY,
name TEXT)
""")
}
migrator.registerMigration("createPets") { db in
try db.execute("""
try db.execute(sql: """
CREATE TABLE pets (
id INTEGER PRIMARY KEY,
masterID INTEGER NOT NULL
@@ -38,7 +38,7 @@ class DatabaseMigratorTests : GRDBTestCase {
}
migrator.registerMigration("destroyPersons") { db in
try db.execute("DROP TABLE pets")
try db.execute(sql: "DROP TABLE pets")
}
try migrator.migrate(dbQueue)
@@ -53,14 +53,14 @@ class DatabaseMigratorTests : GRDBTestCase {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute("""
try db.execute(sql: """
CREATE TABLE persons (
id INTEGER PRIMARY KEY,
name TEXT)
""")
}
migrator.registerMigration("createPets") { db in
try db.execute("""
try db.execute(sql: """
CREATE TABLE pets (
id INTEGER PRIMARY KEY,
masterID INTEGER NOT NULL
@@ -77,7 +77,7 @@ class DatabaseMigratorTests : GRDBTestCase {
}
migrator.registerMigration("destroyPersons") { db in
try db.execute("DROP TABLE pets")
try db.execute(sql: "DROP TABLE pets")
}
try migrator.migrate(dbPool)
@@ -92,13 +92,13 @@ class DatabaseMigratorTests : GRDBTestCase {
var migrator = DatabaseMigrator()
migrator.registerMigration("a") { db in
try db.execute("CREATE TABLE a (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE a (id INTEGER PRIMARY KEY)")
}
migrator.registerMigration("b") { db in
try db.execute("CREATE TABLE b (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE b (id INTEGER PRIMARY KEY)")
}
migrator.registerMigration("c") { db in
try db.execute("CREATE TABLE c (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE c (id INTEGER PRIMARY KEY)")
}
// one step
@@ -137,15 +137,15 @@ class DatabaseMigratorTests : GRDBTestCase {
func testMigrationFailureTriggersRollback() throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT)")
try db.execute("CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
try db.execute("INSERT INTO persons (name) VALUES ('Arthur')")
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT)")
try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
try db.execute(sql: "INSERT INTO persons (name) VALUES ('Arthur')")
}
migrator.registerMigration("foreignKeyError") { db in
try db.execute("INSERT INTO persons (name) VALUES ('Barbara')")
try db.execute(sql: "INSERT INTO persons (name) VALUES ('Barbara')")
do {
// triggers immediate foreign key error:
try db.execute("INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [123, "Bobby"])
try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [123, "Bobby"])
XCTFail("Expected error")
} catch {
throw error
@@ -169,7 +169,7 @@ class DatabaseMigratorTests : GRDBTestCase {
XCTAssertEqual(error.description.lowercased(), "sqlite error 19 with statement `insert into pets (masterid, name) values (?, ?)` arguments [123, \"bobby\"]: foreign key constraint failed")
let names = try dbQueue.inDatabase { db in
try String.fetchAll(db, "SELECT name FROM persons")
try String.fetchAll(db, sql: "SELECT name FROM persons")
}
XCTAssertEqual(names, ["Arthur"])
}
@@ -183,25 +183,25 @@ class DatabaseMigratorTests : GRDBTestCase {
#endif
var migrator = DatabaseMigrator()
migrator.registerMigration("createPersons") { db in
try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, tmp TEXT)")
try db.execute("CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
try db.execute("INSERT INTO persons (name) VALUES ('Arthur')")
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, tmp TEXT)")
try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)")
try db.execute(sql: "INSERT INTO persons (name) VALUES ('Arthur')")
let personId = db.lastInsertedRowID
try db.execute("INSERT INTO pets (masterId, name) VALUES (?, 'Bobby')", arguments:[personId])
try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, 'Bobby')", arguments:[personId])
}
migrator.registerMigrationWithDeferredForeignKeyCheck("removePersonTmpColumn") { db in
// Test the technique described at https://www.sqlite.org/lang_altertable.html#otheralter
try db.execute("CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT)")
try db.execute("INSERT INTO new_persons SELECT id, name FROM persons")
try db.execute("DROP TABLE persons")
try db.execute("ALTER TABLE new_persons RENAME TO persons")
try db.execute(sql: "CREATE TABLE new_persons (id INTEGER PRIMARY KEY, name TEXT)")
try db.execute(sql: "INSERT INTO new_persons SELECT id, name FROM persons")
try db.execute(sql: "DROP TABLE persons")
try db.execute(sql: "ALTER TABLE new_persons RENAME TO persons")
}
migrator.registerMigrationWithDeferredForeignKeyCheck("foreignKeyError") { db in
// Make sure foreign keys are checked at the end.
try db.execute("INSERT INTO persons (name) VALUES ('Barbara')")
try db.execute(sql: "INSERT INTO persons (name) VALUES ('Barbara')")
do {
// triggers foreign key error, but not now.
try db.execute("INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [123, "Bobby"])
try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [123, "Bobby"])
} catch {
XCTFail("Error not expected at this point")
}
@@ -222,7 +222,7 @@ class DatabaseMigratorTests : GRDBTestCase {
try dbQueue.inDatabase { db in
// Arthur inserted (migration 1), Barbara (migration 3) not inserted.
var rows = try Row.fetchAll(db, "SELECT * FROM persons")
var rows = try Row.fetchAll(db, sql: "SELECT * FROM persons")
XCTAssertEqual(rows.count, 1)
var row = rows.first!
XCTAssertEqual(row["name"] as String, "Arthur")
@@ -231,7 +231,7 @@ class DatabaseMigratorTests : GRDBTestCase {
XCTAssertEqual(Array(row.columnNames), ["id", "name"])
// Bobby inserted (migration 1), not deleted by migration 2.
rows = try Row.fetchAll(db, "SELECT * FROM pets")
rows = try Row.fetchAll(db, sql: "SELECT * FROM pets")
XCTAssertEqual(rows.count, 1)
row = rows.first!
XCTAssertEqual(row["name"] as String, "Bobby")
@@ -259,7 +259,7 @@ class DatabaseMigratorTests : GRDBTestCase {
}
}
migrator2.registerMigration("2") { db in
try db.execute("INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)")
try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)")
}
// Apply 1st migrator
@@ -288,7 +288,7 @@ class DatabaseMigratorTests : GRDBTestCase {
var witness = 1
migrator.registerMigration("1") { db in
try db.execute("""
try db.execute(sql: """
CREATE TABLE t1(id INTEGER PRIMARY KEY);
INSERT INTO t1(id) VALUES (?)
""", arguments: [witness])
@@ -299,16 +299,16 @@ class DatabaseMigratorTests : GRDBTestCase {
// 1st migration
try migrator.migrate(dbQueue)
try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, "SELECT id FROM t1") }, 1)
try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, sql: "SELECT id FROM t1") }, 1)
// 2nd migration does not erase database
migrator.registerMigration("2") { db in
try db.execute("""
try db.execute(sql: """
CREATE TABLE t2(id INTEGER PRIMARY KEY);
""")
}
try migrator.migrate(dbQueue)
try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, "SELECT id FROM t1") }, 1)
try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, sql: "SELECT id FROM t1") }, 1)
try XCTAssertTrue(dbQueue.read { try $0.tableExists("t2") })
}
}
+12 -12
View File
@@ -14,19 +14,19 @@ class DatabasePoolBackupTests: GRDBTestCase {
let destination = try makeDatabasePool(filename: "destination.sqlite")
try source.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute("INSERT INTO items (id) VALUES (NULL)")
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1)
}
try source.backup(to: destination)
try destination.read { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1)
}
try source.write { db in
try db.execute("DROP TABLE items")
try db.execute(sql: "DROP TABLE items")
}
try source.backup(to: destination)
@@ -43,9 +43,9 @@ class DatabasePoolBackupTests: GRDBTestCase {
// let destination = try makeDatabasePool(filename: "destination.sqlite")
//
// try source.write { db in
// try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
// try db.execute("INSERT INTO items (id) VALUES (NULL)")
// XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
// try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
// try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
// XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1)
// }
//
// let s1 = DispatchSemaphore(value: 0)
@@ -53,7 +53,7 @@ class DatabasePoolBackupTests: GRDBTestCase {
// DispatchQueue.global().async {
// _ = s1.wait(timeout: .distantFuture)
// try! source.writeInTransaction(.immediate) { db in
// try db.execute("INSERT INTO items (id) VALUES (NULL)")
// try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
// s2.signal()
// return .commit
// }
@@ -67,18 +67,18 @@ class DatabasePoolBackupTests: GRDBTestCase {
// },
// afterBackupStep: {
// try! source.write { db in
// try db.execute("INSERT INTO items (id) VALUES (NULL)")
// try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
// }
// })
//
// try source.read { db in
// XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 3)
// XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 3)
// }
// try destination.read { db in
// // TODO: understand why the fix for https://github.com/groue/GRDB.swift/issues/102
// // had this value change from 2 to 1.
// // TODO: Worse, this test is fragile. I've seen not 1 but 2 once.
// XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
// XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1)
// }
// }
}
@@ -18,14 +18,14 @@ class DatabasePoolCollationTests: GRDBTestCase {
dbPool.add(collation: collation1)
try dbPool.write { db in
try db.execute("CREATE TABLE items (text TEXT COLLATE collation1)")
try db.execute("INSERT INTO items (text) VALUES ('a')")
try db.execute("INSERT INTO items (text) VALUES ('b')")
try db.execute("INSERT INTO items (text) VALUES ('c')")
try db.execute(sql: "CREATE TABLE items (text TEXT COLLATE collation1)")
try db.execute(sql: "INSERT INTO items (text) VALUES ('a')")
try db.execute(sql: "INSERT INTO items (text) VALUES ('b')")
try db.execute(sql: "INSERT INTO items (text) VALUES ('c')")
}
try dbPool.read { db in
XCTAssertEqual(try String.fetchAll(db, "SELECT text FROM items ORDER BY text"), ["a", "b", "c"])
XCTAssertEqual(try String.fetchAll(db, "SELECT text FROM items ORDER BY text COLLATE collation1"), ["a", "b", "c"])
XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text"), ["a", "b", "c"])
XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation1"), ["a", "b", "c"])
}
let collation2 = DatabaseCollation("collation2") { (string1, string2) in
@@ -34,7 +34,7 @@ class DatabasePoolCollationTests: GRDBTestCase {
dbPool.add(collation: collation2)
try dbPool.read { db in
XCTAssertEqual(try String.fetchAll(db, "SELECT text FROM items ORDER BY text COLLATE collation2"), ["c", "b", "a"])
XCTAssertEqual(try String.fetchAll(db, sql: "SELECT text FROM items ORDER BY text COLLATE collation2"), ["c", "b", "a"])
}
}
}
@@ -33,10 +33,10 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
do {
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.writeWithoutTransaction { db in
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal")
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode = wal")
XCTAssertEqual(journalMode, "wal")
try db.create(table: "moves") { $0.column("value", .integer) }
try db.execute("INSERT INTO moves VALUES (0)")
try db.execute(sql: "INSERT INTO moves VALUES (0)")
}
}
let s0 = DispatchSemaphore(value: 0)
@@ -44,14 +44,14 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite")
s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time
try! dbQueue.writeWithoutTransaction { db in
try db.execute("BEGIN DEFERRED TRANSACTION")
try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 1) // Non-zero balance
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT SUM(value) AS balance FROM moves"), 1) // Non-zero balance
s3.signal()
_ = s4.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 1) // Non-zero balance
try db.execute("END")
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT SUM(value) AS balance FROM moves"), 1) // Non-zero balance
try db.execute(sql: "END")
}
}
let block2 = { () in
@@ -59,10 +59,10 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite")
try! dbQueue.writeWithoutTransaction { db in
_ = s1.wait(timeout: .distantFuture)
try db.execute("INSERT INTO moves VALUES (1)")
try db.execute(sql: "INSERT INTO moves VALUES (1)")
s2.signal()
_ = s3.wait(timeout: .distantFuture)
try db.execute("INSERT INTO moves VALUES (-1)")
try db.execute(sql: "INSERT INTO moves VALUES (-1)")
s4.signal()
}
}
@@ -95,10 +95,10 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
do {
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.writeWithoutTransaction { db in
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal")
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode = wal")
XCTAssertEqual(journalMode, "wal")
try db.create(table: "moves") { $0.column("value", .integer) }
try db.execute("INSERT INTO moves VALUES (0)")
try db.execute(sql: "INSERT INTO moves VALUES (0)")
}
}
let s0 = DispatchSemaphore(value: 0)
@@ -107,29 +107,29 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time
try! dbQueue.writeWithoutTransaction { db in
_ = s1.wait(timeout: .distantFuture)
try db.execute("BEGIN DEFERRED TRANSACTION")
try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
s2.signal()
_ = s3.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance
s4.signal()
_ = s5.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance
try db.execute("END")
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance
try db.execute(sql: "END")
}
}
let block2 = { () in
_ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time
let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite")
try! dbQueue.writeWithoutTransaction { db in
try db.execute("BEGIN DEFERRED TRANSACTION")
try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
s1.signal()
_ = s2.wait(timeout: .distantFuture)
try db.execute("INSERT INTO moves VALUES (1)")
try db.execute(sql: "INSERT INTO moves VALUES (1)")
s3.signal()
_ = s4.wait(timeout: .distantFuture)
try db.execute("INSERT INTO moves VALUES (-1)")
try db.execute(sql: "INSERT INTO moves VALUES (-1)")
s5.signal()
try db.execute("END")
try db.execute(sql: "END")
}
}
let blocks = [block1, block2]
@@ -160,10 +160,10 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
do {
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.writeWithoutTransaction { db in
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal")
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode = wal")
XCTAssertEqual(journalMode, "wal")
try db.create(table: "moves") { $0.column("value", .integer) }
try db.execute("INSERT INTO moves VALUES (0)")
try db.execute(sql: "INSERT INTO moves VALUES (0)")
}
}
let s0 = DispatchSemaphore(value: 0)
@@ -171,14 +171,14 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite")
s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time
try! dbQueue.writeWithoutTransaction { db in
try db.execute("BEGIN DEFERRED TRANSACTION")
try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance
s3.signal()
_ = s4.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance
try db.execute("END")
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT SUM(value) AS balance FROM moves"), 0) // Zero balance
try db.execute(sql: "END")
}
}
let block2 = { () in
@@ -186,13 +186,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite")
try! dbQueue.writeWithoutTransaction { db in
_ = s1.wait(timeout: .distantFuture)
try db.execute("BEGIN DEFERRED TRANSACTION")
try db.execute("INSERT INTO moves VALUES (1)")
try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
try db.execute(sql: "INSERT INTO moves VALUES (1)")
s2.signal()
_ = s3.wait(timeout: .distantFuture)
try db.execute("INSERT INTO moves VALUES (-1)")
try db.execute(sql: "INSERT INTO moves VALUES (-1)")
s4.signal()
try db.execute("END")
try db.execute(sql: "END")
}
}
let blocks = [block1, block2]
@@ -204,11 +204,11 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testWrappedReadWrite() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
let id = try dbPool.read { db in
try Int.fetchOne(db, "SELECT id FROM items")!
try Int.fetchOne(db, sql: "SELECT id FROM items")!
}
XCTAssertEqual(id, 1)
}
@@ -217,14 +217,14 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
do {
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
try dbQueue.writeWithoutTransaction { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
}
do {
let dbPool = try makeDatabasePool(filename: "test.sqlite")
let id = try dbPool.read { db in
try Int.fetchOne(db, "SELECT id FROM items")!
try Int.fetchOne(db, sql: "SELECT id FROM items")!
}
XCTAssertEqual(id, 1)
}
@@ -235,7 +235,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
try dbPool.write { db in
XCTAssertTrue(db.isInsideTransaction)
do {
try db.execute("BEGIN DEFERRED TRANSACTION")
try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -260,7 +260,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
try dbPool.read { db in
XCTAssertTrue(db.isInsideTransaction)
do {
try db.execute("BEGIN DEFERRED TRANSACTION")
try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
XCTFail("Expected error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
@@ -283,8 +283,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block1 = { () in
try! dbPool.writeWithoutTransaction { db in
try db.execute("PRAGMA locking_mode=EXCLUSIVE")
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
s1.signal()
}
}
@@ -311,9 +311,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testConcurrentRead() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
for _ in 0..<3 {
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
}
@@ -333,7 +333,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block1 = { () in
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
@@ -344,7 +344,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
let block2 = { () in
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
_ = s1.wait(timeout: .distantFuture)
XCTAssertTrue(try cursor.next() != nil)
@@ -362,9 +362,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testReadMethodIsolationOfStatement() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
for _ in 0..<2 {
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
}
@@ -383,7 +383,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block1 = { () in
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
@@ -396,7 +396,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
_ = s1.wait(timeout: .distantFuture)
defer { s2.signal() }
try dbPool.writeWithoutTransaction { db in
try db.execute("DELETE FROM items")
try db.execute(sql: "DELETE FROM items")
}
} catch {
XCTFail("error: \(error)")
@@ -411,9 +411,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testReadMethodIsolationOfStatementWithCheckpoint() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
for _ in 0..<2 {
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
}
@@ -433,7 +433,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block1 = { () in
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
@@ -446,7 +446,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
_ = s1.wait(timeout: .distantFuture)
defer { s2.signal() }
try dbPool.writeWithoutTransaction { db in
try db.execute("DELETE FROM items")
try db.execute(sql: "DELETE FROM items")
}
try dbPool.checkpoint()
} catch {
@@ -462,7 +462,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testReadBlockIsolationStartingWithRead() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
// Block 1 Block 2
@@ -485,20 +485,20 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
try! dbPool.read { db in
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1) // Not a bug. The writer did not start a transaction.
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) // Not a bug. The writer did not start a transaction.
s3.signal()
_ = s4.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1)
}
}
let block2 = { () in
do {
_ = s1.wait(timeout: .distantFuture)
try dbPool.writeWithoutTransaction { db in
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
s2.signal()
_ = s3.wait(timeout: .distantFuture)
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
s4.signal()
}
} catch {
@@ -514,7 +514,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testReadBlockIsolationStartingWithSelect() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
// Block 1 Block 2
@@ -531,10 +531,10 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block1 = { () in
try! dbPool.read { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0)
}
}
let block2 = { () in
@@ -542,7 +542,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
_ = s1.wait(timeout: .distantFuture)
defer { s2.signal() }
try dbPool.writeWithoutTransaction { db in
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
try dbPool.checkpoint()
} catch {
@@ -558,7 +558,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testReadBlockIsolationStartingWithWrite() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
// Block 1 Block 2
@@ -583,10 +583,10 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block1 = { () in
do {
try dbPool.writeWithoutTransaction { db in
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
s1.signal()
_ = s2.wait(timeout: .distantFuture)
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
s3.signal()
_ = s4.wait(timeout: .distantFuture)
}
@@ -598,13 +598,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block2 = { () in
try! dbPool.read { db in
_ = s1.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1)
s2.signal()
_ = s3.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1)
s4.signal()
_ = s5.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1)
}
}
let blocks = [block1, block2]
@@ -616,7 +616,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testReadBlockIsolationStartingWithWriteTransaction() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
// Block 1 Block 2
@@ -643,10 +643,10 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block1 = { () in
do {
try dbPool.writeInTransaction(.immediate) { db in
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
s1.signal()
_ = s2.wait(timeout: .distantFuture)
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
s3.signal()
_ = s4.wait(timeout: .distantFuture)
return .commit
@@ -659,13 +659,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block2 = { () in
try! dbPool.read { db in
_ = s1.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0)
s2.signal()
_ = s3.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0)
s4.signal()
_ = s5.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0)
}
}
let blocks = [block1, block2]
@@ -677,9 +677,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testUnsafeReadMethodIsolationOfStatement() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
for _ in 0..<2 {
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
}
@@ -699,13 +699,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block1 = { () in
try! dbPool.unsafeRead { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertTrue(try cursor.next() != nil)
XCTAssertTrue(try cursor.next() == nil)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0)
}
}
let block2 = { () in
@@ -713,7 +713,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
_ = s1.wait(timeout: .distantFuture)
defer { s2.signal() }
try dbPool.writeWithoutTransaction { db in
try db.execute("DELETE FROM items")
try db.execute(sql: "DELETE FROM items")
}
} catch {
XCTFail("error: \(error)")
@@ -728,9 +728,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testUnsafeReadMethodIsolationOfStatementWithCheckpoint() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
for _ in 0..<2 {
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
}
@@ -750,7 +750,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block1 = { () in
try! dbPool.unsafeRead { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
@@ -763,7 +763,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
_ = s1.wait(timeout: .distantFuture)
defer { s2.signal() }
try dbPool.writeWithoutTransaction { db in
try db.execute("DELETE FROM items")
try db.execute(sql: "DELETE FROM items")
}
try dbPool.checkpoint()
} catch {
@@ -779,7 +779,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testUnsafeReadMethodIsolationOfBlock() throws {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
// Block 1 Block 2
@@ -796,10 +796,10 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let block1 = { () in
try! dbPool.unsafeRead { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 0)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 0)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1)
}
}
let block2 = { () in
@@ -807,7 +807,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
_ = s1.wait(timeout: .distantFuture)
defer { s2.signal() }
try dbPool.writeWithoutTransaction { db in
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
try dbPool.checkpoint()
} catch {
@@ -826,7 +826,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
dbPool.concurrentRead { db in
XCTAssertTrue(db.isInsideTransaction)
do {
try db.execute("BEGIN DEFERRED TRANSACTION")
try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
XCTFail("Expected error")
} catch {
}
@@ -858,9 +858,9 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let future: Future<Int> = try dbPool.writeWithoutTransaction { db in
let future: Future<Int> = dbPool.concurrentRead { db in
_ = s1.wait(timeout: .distantFuture)
return try! Int.fetchOne(db, "SELECT COUNT(*) FROM persons")!
return try! Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")!
}
try db.execute("INSERT INTO persons DEFAULT VALUES")
try db.execute(sql: "INSERT INTO persons DEFAULT VALUES")
s1.signal()
return future
}
@@ -870,8 +870,8 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
func testConcurrentReadError() throws {
let dbPool = try makeDatabasePool()
try dbPool.writeWithoutTransaction { db in
try db.execute("PRAGMA locking_mode=EXCLUSIVE")
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
let future = dbPool.concurrentRead { db in
fatalError("Should not run")
}
@@ -896,7 +896,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
try dbPool.write { db in
try db.create(table: "t") { $0.column("id", .integer).primaryKey() }
try db.execute("INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
try dbQueue.writeWithoutTransaction { db in
@@ -904,17 +904,17 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
}
try dbQueue.writeWithoutTransaction { db in
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1)
try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!, 1)
}
try dbPool.write { db in
try db.execute("INSERT INTO t DEFAULT VALUES")
try db.execute(sql: "INSERT INTO t DEFAULT VALUES")
}
try dbQueue.writeWithoutTransaction { db in
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1)
try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!, 1)
try db.rollback()
try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 2)
try XCTAssertEqual(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")!, 2)
}
}
@@ -932,10 +932,10 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE VIRTUAL TABLE search USING fts3(title)")
try db.execute(sql: "CREATE VIRTUAL TABLE search USING fts3(title)")
}
try dbPool.read { db in
_ = try Row.fetchAll(db, "SELECT * FROM search")
_ = try Row.fetchAll(db, sql: "SELECT * FROM search")
}
}
@@ -19,11 +19,11 @@ class DatabasePoolFunctionTests: GRDBTestCase {
dbPool.add(function: function1)
try dbPool.write { db in
try db.execute("CREATE TABLE items (text TEXT)")
try db.execute("INSERT INTO items (text) VALUES (function1('a'))")
try db.execute(sql: "CREATE TABLE items (text TEXT)")
try db.execute(sql: "INSERT INTO items (text) VALUES (function1('a'))")
}
try dbPool.read { db in
XCTAssertEqual(try String.fetchOne(db, "SELECT function1(text) FROM items")!, "a")
XCTAssertEqual(try String.fetchOne(db, sql: "SELECT function1(text) FROM items")!, "a")
}
let function2 = DatabaseFunction("function2", argumentCount: 1, pure: true) { (dbValues: [DatabaseValue]) in
@@ -32,7 +32,7 @@ class DatabasePoolFunctionTests: GRDBTestCase {
dbPool.add(function: function2)
try dbPool.read { db in
XCTAssertTrue(try String.fetchOne(db, "SELECT function2(text) FROM items") == "foo")
XCTAssertTrue(try String.fetchOne(db, sql: "SELECT function2(text) FROM items") == "foo")
}
}
}
@@ -16,9 +16,9 @@ class DatabasePoolReadOnlyTests: GRDBTestCase {
do {
let dbQueue = try makeDatabaseQueue(filename: databaseFileName)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
for _ in 0..<3 {
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
}
}
@@ -29,7 +29,7 @@ class DatabasePoolReadOnlyTests: GRDBTestCase {
// Make sure the database is not in WAL mode
let mode = try dbPool.read { db in
try String.fetchOne(db, "PRAGMA journal_mode")!
try String.fetchOne(db, sql: "PRAGMA journal_mode")!
}
XCTAssertNotEqual(mode.lowercased(), "wal")
@@ -47,7 +47,7 @@ class DatabasePoolReadOnlyTests: GRDBTestCase {
let block1 = { () in
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
@@ -58,7 +58,7 @@ class DatabasePoolReadOnlyTests: GRDBTestCase {
}
let block2 = { () in
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
_ = s1.wait(timeout: .distantFuture)
XCTAssertTrue(try cursor.next() != nil)
@@ -34,7 +34,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
let dbPool = try makeDatabasePool()
// Writer connection
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
// Reader connection
try dbPool.read { _ in }
@@ -67,9 +67,9 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
for _ in 0..<2 {
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
}
@@ -89,7 +89,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
let block1 = { () in
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s1.signal()
_ = s2.wait(timeout: .distantFuture)
@@ -101,7 +101,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
let block2 = { () in
_ = s1.wait(timeout: .distantFuture)
try! dbPool.read { db in
let cursor = try Row.fetchCursor(db, "SELECT * FROM items")
let cursor = try Row.fetchCursor(db, sql: "SELECT * FROM items")
XCTAssertTrue(try cursor.next() != nil)
s2.signal()
XCTAssertTrue(try cursor.next() != nil)
@@ -155,7 +155,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
let (block1, block2) = { () -> (() -> (), () -> ()) in
var dbPool: DatabasePool? = try! self.makeDatabasePool()
try! dbPool!.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
let block1 = { () in
@@ -168,7 +168,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
try! dbPool.read { db in
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items"), 0)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items"), 0)
}
} else {
XCTFail("expect non nil dbPool")
@@ -211,7 +211,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase {
if let dbPool = dbPool {
do {
try dbPool.write { db in
statement = try db.makeUpdateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)")
statement = try db.makeUpdateStatement(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
s1.signal()
}
} catch {
@@ -13,8 +13,8 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, email TEXT UNIQUE, foo INT, bar DOUBLE)")
try db.execute("CREATE INDEX foobar ON items(foo, bar)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY, email TEXT UNIQUE, foo INT, bar DOUBLE)")
try db.execute(sql: "CREATE INDEX foobar ON items(foo, bar)")
}
try dbPool.write { db in
@@ -57,7 +57,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
try dbPool.write { db in
// Empty cache after schema change
try db.execute("DROP TABLE items")
try db.execute(sql: "DROP TABLE items")
// Assert that the writer cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
@@ -94,8 +94,8 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
// correct thread.
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute("INSERT INTO items (id) VALUES (1)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "INSERT INTO items (id) VALUES (1)")
}
// Block 1 Block 2
@@ -106,7 +106,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
let block1 = { () in
try! dbPool.read { db in
let stmt = try! db.cachedSelectStatement("SELECT * FROM items")
let stmt = try! db.cachedSelectStatement(sql: "SELECT * FROM items")
XCTAssertEqual(try Int.fetchOne(stmt)!, 1)
s1.signal()
}
@@ -114,7 +114,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
let block2 = { () in
try! dbPool.read { db in
_ = s1.wait(timeout: .distantFuture)
let stmt = try! db.cachedSelectStatement("SELECT * FROM items")
let stmt = try! db.cachedSelectStatement(sql: "SELECT * FROM items")
XCTAssertEqual(try Int.fetchOne(stmt)!, 1)
}
}
@@ -148,14 +148,14 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
let block1 = { () in
try! dbPool.writeWithoutTransaction { db in
try db.execute("CREATE TABLE foo(id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE foo(id INTEGER PRIMARY KEY)")
// warm cache
_ = try db.primaryKey("foo")
// cache contains the primary key
XCTAssertNotNil(db.schemaCache.primaryKey("foo"))
s1.signal()
_ = s2.wait(timeout: .distantFuture)
try db.execute("DROP TABLE foo")
try db.execute(sql: "DROP TABLE foo")
// cache does not contain the primary key
XCTAssertNil(db.schemaCache.primaryKey("foo"))
s3.signal()
@@ -168,7 +168,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
_ = s1.wait(timeout: .distantFuture)
try! dbPool.read { db in
// activate snapshot isolation so that foo table is visible during the whole read. Any read is enough.
try db.makeSelectStatement("SELECT * FROM sqlite_master").makeCursor().next()
try db.makeSelectStatement(sql: "SELECT * FROM sqlite_master").makeCursor().next()
// warm cache
_ = try db.primaryKey("foo")
// cache contains the primary key
@@ -192,8 +192,8 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase {
let dbPool = try makeDatabasePool()
try dbPool.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, email TEXT UNIQUE, foo INT, bar DOUBLE)")
try db.execute("CREATE INDEX foobar ON items(foo, bar)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY, email TEXT UNIQUE, foo INT, bar DOUBLE)")
try db.execute(sql: "CREATE INDEX foobar ON items(foo, bar)")
}
try dbPool.unsafeRead { db in
@@ -14,19 +14,19 @@ class DatabaseQueueBackupTests: GRDBTestCase {
let destination = try makeDatabaseQueue(filename: "destination.sqlite")
try source.inDatabase { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute("INSERT INTO items (id) VALUES (NULL)")
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1)
}
try source.backup(to: destination)
try destination.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items")!, 1)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1)
}
try source.inDatabase { db in
try db.execute("DROP TABLE items")
try db.execute(sql: "DROP TABLE items")
}
try source.backup(to: destination)
@@ -29,11 +29,11 @@ class ConcurrencyTests: GRDBTestCase {
func testWrappedReadWrite() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute("INSERT INTO items (id) VALUES (NULL)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)")
}
let id = try dbQueue.inDatabase { db in
try Int.fetchOne(db, "SELECT id FROM items")!
try Int.fetchOne(db, sql: "SELECT id FROM items")!
}
XCTAssertEqual(id, 1)
}
@@ -45,7 +45,7 @@ class ConcurrencyTests: GRDBTestCase {
// same empty database: make sure the database is not empty before
// running this test
try dbQueue1.inDatabase { db in
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
@@ -63,7 +63,7 @@ class ConcurrencyTests: GRDBTestCase {
// COMMIT
try dbQueue1.inDatabase { db in
try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE stuffs (id INTEGER PRIMARY KEY)")
}
let queue = DispatchQueue(label: "GRDB", attributes: [.concurrent])
@@ -75,7 +75,7 @@ class ConcurrencyTests: GRDBTestCase {
try dbQueue1.inTransaction(.deferred) { db in
s1.signal()
_ = s2.wait(timeout: .distantFuture)
try db.execute("INSERT INTO stuffs (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO stuffs (id) VALUES (NULL)")
s3.signal()
_ = s4.wait(timeout: .distantFuture)
return .commit
@@ -94,7 +94,7 @@ class ConcurrencyTests: GRDBTestCase {
try dbQueue2.inTransaction(.deferred) { db in
s2.signal()
_ = s3.wait(timeout: .distantFuture)
try db.execute("INSERT INTO stuffs (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO stuffs (id) VALUES (NULL)")
return .commit
}
}
@@ -236,7 +236,7 @@ class ConcurrencyTests: GRDBTestCase {
// same empty database: make sure the database is not empty before
// running this test
try dbQueue1.inDatabase { db in
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
@@ -299,7 +299,7 @@ class ConcurrencyTests: GRDBTestCase {
// same empty database: make sure the database is not empty before
// running this test
try dbQueue1.inDatabase { db in
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
@@ -317,7 +317,7 @@ class ConcurrencyTests: GRDBTestCase {
// SELECT * FROM stuffs <--- 1 result
try dbQueue1.inDatabase { db in
try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE stuffs (id INTEGER PRIMARY KEY)")
}
let queue = DispatchQueue(label: "GRDB", attributes: [.concurrent])
@@ -327,7 +327,7 @@ class ConcurrencyTests: GRDBTestCase {
queue.async(group: group) {
do {
try dbQueue1.inTransaction { db in
try db.execute("INSERT INTO stuffs (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO stuffs (id) VALUES (NULL)")
s1.signal()
_ = s2.wait(timeout: .distantFuture)
return .commit
@@ -345,10 +345,10 @@ class ConcurrencyTests: GRDBTestCase {
queue.async(group: group) {
try! dbQueue2.writeWithoutTransaction { db in
_ = s1.wait(timeout: .distantFuture)
rows1 = try Row.fetchAll(db, "SELECT * FROM stuffs")
rows1 = try Row.fetchAll(db, sql: "SELECT * FROM stuffs")
s2.signal()
_ = s3.wait(timeout: .distantFuture)
rows2 = try Row.fetchAll(db, "SELECT * FROM stuffs")
rows2 = try Row.fetchAll(db, sql: "SELECT * FROM stuffs")
}
}
@@ -365,7 +365,7 @@ class ConcurrencyTests: GRDBTestCase {
// same empty database: make sure the database is not empty before
// running this test
try dbQueue1.inDatabase { db in
try db.execute("CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
try db.execute(sql: "CREATE TABLE SQLCipherWorkAround (foo INTEGER)")
}
#endif
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
@@ -398,7 +398,7 @@ class ConcurrencyTests: GRDBTestCase {
}
try dbQueue1.inDatabase { db in
try db.execute("CREATE TABLE stuffs (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE stuffs (id INTEGER PRIMARY KEY)")
}
let queue = DispatchQueue(label: "GRDB", attributes: [.concurrent])
@@ -408,7 +408,7 @@ class ConcurrencyTests: GRDBTestCase {
queue.async(group: group) {
do {
try dbQueue1.inTransaction { db in
try db.execute("INSERT INTO stuffs (id) VALUES (NULL)")
try db.execute(sql: "INSERT INTO stuffs (id) VALUES (NULL)")
s1.signal()
_ = s2.wait(timeout: .distantFuture)
return .commit
@@ -424,7 +424,7 @@ class ConcurrencyTests: GRDBTestCase {
do {
_ = s1.wait(timeout: .distantFuture)
try dbQueue2.inTransaction(.deferred) { db in
_ = try Row.fetchAll(db, "SELECT * FROM stuffs")
_ = try Row.fetchAll(db, sql: "SELECT * FROM stuffs")
s2.signal()
_ = s3.wait(timeout: .distantFuture)
return .commit
@@ -12,9 +12,9 @@ class DatabaseQueueInMemoryTests : GRDBTestCase
func testInMemoryDatabase() throws {
let dbQueue = DatabaseQueue()
try dbQueue.inTransaction { db in
try db.execute("CREATE TABLE foo (bar TEXT)")
try db.execute("INSERT INTO foo (bar) VALUES ('baz')")
let baz = try String.fetchOne(db, "SELECT bar FROM foo")!
try db.execute(sql: "CREATE TABLE foo (bar TEXT)")
try db.execute(sql: "INSERT INTO foo (bar) VALUES ('baz')")
let baz = try String.fetchOne(db, sql: "SELECT bar FROM foo")!
XCTAssertEqual(baz, "baz")
return .rollback
}
@@ -19,7 +19,7 @@ class DatabaseQueueReadOnlyTests : GRDBTestCase {
dbConfiguration.readonly = true
let dbQueue = try makeDatabaseQueue(filename: "test.sqlite")
let statement = try dbQueue.inDatabase { db in
try db.makeUpdateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.makeUpdateStatement(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
do {
try dbQueue.inDatabase { db in
@@ -70,7 +70,7 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase {
let (block1, block2) = { () -> (() -> (), () -> ()) in
var dbQueue: DatabaseQueue? = try! self.makeDatabaseQueue()
try! dbQueue!.write { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
let block1 = { () in
@@ -83,7 +83,7 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase {
try! dbQueue.write { db in
s1.signal()
_ = s2.wait(timeout: .distantFuture)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items"), 0)
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items"), 0)
}
} else {
XCTFail("expect non nil dbQueue")
@@ -127,7 +127,7 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase {
if let dbQueue = dbQueue {
do {
try dbQueue.write { db in
statement = try db.makeUpdateStatement("CREATE TABLE items (id INTEGER PRIMARY KEY)")
statement = try db.makeUpdateStatement(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
s1.signal()
}
} catch {
@@ -13,7 +13,7 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)")
}
dbQueue.inDatabase { db in
@@ -32,7 +32,7 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
try dbQueue.inDatabase { db in
// Empty cache after schema change
try db.execute("DROP TABLE items")
try db.execute(sql: "DROP TABLE items")
// Assert that cache is empty
XCTAssertTrue(db.schemaCache.primaryKey("items") == nil)
+4 -4
View File
@@ -46,12 +46,12 @@ class DatabaseQueueTests: GRDBTestCase {
}
dbQueue.add(function: fn)
try dbQueue.inDatabase { db in
XCTAssertEqual(try Int.fetchOne(db, "SELECT succ(1)"), 2) // 2
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT succ(1)"), 2) // 2
}
dbQueue.remove(function: fn)
do {
try dbQueue.inDatabase { db in
try db.execute("SELECT succ(1)")
try db.execute(sql: "SELECT succ(1)")
XCTFail("Expected Error")
}
XCTFail("Expected Error")
@@ -73,12 +73,12 @@ class DatabaseQueueTests: GRDBTestCase {
}
dbQueue.add(collation: collation)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE files (name TEXT COLLATE TEST_COLLATION_FOO)")
try db.execute(sql: "CREATE TABLE files (name TEXT COLLATE TEST_COLLATION_FOO)")
}
dbQueue.remove(collation: collation)
do {
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE files_fail (name TEXT COLLATE TEST_COLLATION_FOO)")
try db.execute(sql: "CREATE TABLE files_fail (name TEXT COLLATE TEST_COLLATION_FOO)")
XCTFail("Expected Error")
}
XCTFail("Expected Error")
+2 -2
View File
@@ -25,7 +25,7 @@ class DatabaseReaderTests : GRDBTestCase {
}
}
do {
try dbQueue.read { try $0.execute("INSERT INTO table1 DEFAULT VALUES") }
try dbQueue.read { try $0.execute(sql: "INSERT INTO table1 DEFAULT VALUES") }
XCTFail()
} catch let error as DatabaseError where error.resultCode == .SQLITE_READONLY {
}
@@ -39,7 +39,7 @@ class DatabaseReaderTests : GRDBTestCase {
}
}
do {
try dbPool.read { try $0.execute("INSERT INTO table1 DEFAULT VALUES") }
try dbPool.read { try $0.execute(sql: "INSERT INTO table1 DEFAULT VALUES") }
XCTFail()
} catch let error as DatabaseError where error.resultCode == .SQLITE_READONLY {
}
@@ -16,16 +16,16 @@ class DatabaseRegionObservationTests: GRDBTestCase {
func testDatabaseRegionObservationVariadic() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write {
try $0.execute("CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
try $0.execute("CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
try $0.execute(sql: "CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
try $0.execute(sql: "CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
}
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 3
let request1 = SQLRequest<Row>("SELECT * FROM t1 ORDER BY id")
let request2 = SQLRequest<Row>("SELECT * FROM t2 ORDER BY id")
let request1 = SQLRequest<Row>(sql: "SELECT * FROM t1 ORDER BY id")
let request2 = SQLRequest<Row>(sql: "SELECT * FROM t2 ORDER BY id")
var observation = DatabaseRegionObservation(tracking: request1, request2)
observation.extent = .databaseLifetime
@@ -37,14 +37,14 @@ class DatabaseRegionObservationTests: GRDBTestCase {
}
try dbQueue.write { db in
try db.execute("INSERT INTO t1 (id, name) VALUES (1, 'foo')")
try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (1, 'foo')")
}
try dbQueue.write { db in
try db.execute("INSERT INTO t2 (id, name) VALUES (1, 'foo')")
try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (1, 'foo')")
}
try dbQueue.write { db in
try db.execute("INSERT INTO t1 (id, name) VALUES (2, 'foo')")
try db.execute("INSERT INTO t2 (id, name) VALUES (2, 'foo')")
try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (2, 'foo')")
try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (2, 'foo')")
}
waitForExpectations(timeout: 1, handler: nil)
@@ -54,16 +54,16 @@ class DatabaseRegionObservationTests: GRDBTestCase {
func testDatabaseRegionObservationArray() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write {
try $0.execute("CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
try $0.execute("CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
try $0.execute(sql: "CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
try $0.execute(sql: "CREATE TABLE t2(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
}
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 3
let request1 = SQLRequest<Row>("SELECT * FROM t1 ORDER BY id")
let request2 = SQLRequest<Row>("SELECT * FROM t2 ORDER BY id")
let request1 = SQLRequest<Row>(sql: "SELECT * FROM t1 ORDER BY id")
let request2 = SQLRequest<Row>(sql: "SELECT * FROM t2 ORDER BY id")
var observation = DatabaseRegionObservation(tracking: [request1, request2])
observation.extent = .databaseLifetime
@@ -75,14 +75,14 @@ class DatabaseRegionObservationTests: GRDBTestCase {
}
try dbQueue.write { db in
try db.execute("INSERT INTO t1 (id, name) VALUES (1, 'foo')")
try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (1, 'foo')")
}
try dbQueue.write { db in
try db.execute("INSERT INTO t2 (id, name) VALUES (1, 'foo')")
try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (1, 'foo')")
}
try dbQueue.write { db in
try db.execute("INSERT INTO t1 (id, name) VALUES (2, 'foo')")
try db.execute("INSERT INTO t2 (id, name) VALUES (2, 'foo')")
try db.execute(sql: "INSERT INTO t1 (id, name) VALUES (2, 'foo')")
try db.execute(sql: "INSERT INTO t2 (id, name) VALUES (2, 'foo')")
}
waitForExpectations(timeout: 1, handler: nil)
@@ -91,13 +91,13 @@ class DatabaseRegionObservationTests: GRDBTestCase {
func testDatabaseRegionDefaultExtent() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
let observation = DatabaseRegionObservation(tracking: SQLRequest<Row>("SELECT * FROM t ORDER BY id"))
let observation = DatabaseRegionObservation(tracking: SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id"))
var count = 0
do {
@@ -108,16 +108,16 @@ class DatabaseRegionObservationTests: GRDBTestCase {
try withExtendedLifetime(observer) {
try dbQueue.write { db in
try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
}
try dbQueue.write { db in
try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
}
}
}
// not notified
try dbQueue.write { db in
try db.execute("INSERT INTO t (id, name) VALUES (3, 'baz')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (3, 'baz')")
}
waitForExpectations(timeout: 1, handler: nil)
@@ -126,13 +126,13 @@ class DatabaseRegionObservationTests: GRDBTestCase {
func testDatabaseRegionExtentNextTransaction() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)") }
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 1
var observation = DatabaseRegionObservation(tracking: SQLRequest<Row>("SELECT * FROM t ORDER BY id"))
var observation = DatabaseRegionObservation(tracking: SQLRequest<Row>(sql: "SELECT * FROM t ORDER BY id"))
observation.extent = .nextTransaction
var count = 0
@@ -142,11 +142,11 @@ class DatabaseRegionObservationTests: GRDBTestCase {
}
try dbQueue.write { db in
try db.execute("INSERT INTO t (id, name) VALUES (1, 'foo')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (1, 'foo')")
}
// not notified
try dbQueue.write { db in
try db.execute("INSERT INTO t (id, name) VALUES (2, 'bar')")
try db.execute(sql: "INSERT INTO t (id, name) VALUES (2, 'bar')")
}
waitForExpectations(timeout: 1, handler: nil)
Loaded 100 of 209 files, more files were not shown because too many files have changed in this diff. Show more