Documentation

This commit is contained in:
Gwendal Roué committed 2020-05-01 09:43:48 +02:00
1 parent 307c3d5a13
commit fae562f20d
4 files changed
+95 -53

No files matched your search

+56 -6
View File
@@ -302,6 +302,8 @@ The changes can quite impact your application. We'll describe them below, as wel
// NEW: GRDB 5
try Player.updateAll(db, Column("score").set(to: 0))
```
> :question: This change avoids conflicts with other libraries that define the same operator.
2. [SQL Interpolation] does no longer wrap subqueries in parenthesis:
@@ -316,9 +318,58 @@ The changes can quite impact your application. We'll describe them below, as wel
// extra parenthesis required: ^ ^
```
This change makes it possible to concatenate subqueries with the UNION operator.
> :question: This change makes it possible to concatenate subqueries with the UNION operator.
2. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
3. In order to extract raw SQL string from an SQLLiteral, you now need a database connection:
```swift
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
// BEFORE: GRDB 4
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(query.arguments) // prints ["O'Brien", 42]
// NEW: GRDB 5
let (sql, arguments) = try dbQueue.read(query.build)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
```
> :question: This change makes it possible to embed query interface requests as subqueries inside SQLLiteral:
>
> ```swift
> let maximumScore = Player.select(max(Column("score")))
> let query: SQLLiteral = "SELECT * FROM player WHERE score = (\(maximumScore))"
> ```
4. In order to extract raw SQL string from a request (SQLRequest or QueryInterfaceRequest), you now need a database connection:
```swift
// BEFORE: GRDB 4
try dbQueue.read { db in
let request = Player.filter(Column("name") == "O'Brien")
let sqlRequest = try SQLRequest(db, request: request)
print(sqlRequest.sql) // "SELECT * FROM player WHERE name = ?"
print(sqlRequest.arguments) // ["O'Brien"]
}
// NEW: GRDB 5
try dbQueue.read { db in
let request = Player.filter(Column("name") == "O'Brien")
let statement = try request.makePreparedRequest(db).statement
print(statement.sql) // "SELECT * FROM player WHERE name = ?"
print(statement.arguments) // ["O'Brien"]
}
```
> :question: This change makes it possible to embed query interface requests as subqueries inside SQLRequest:
>
> ```swift
> let maximumScore = Player.select(max(Column("score")))
> let request: SQLRequest<Player> = "SELECT * FROM player WHERE score = (\(maximumScore))"
> ```
5. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
```swift
// BEFORE: GRDB 4
@@ -328,7 +379,7 @@ The changes can quite impact your application. We'll describe them below, as wel
Player.select(myFunction(Column("name")))
```
3. If you happen to implement custom fetch requests with the `FetchRequest` protocol, you now have to define the `makePreparedRequest(_:forSingleResult:)` method:
6. If you happen to implement custom fetch requests with the `FetchRequest` protocol, you now have to define the `makePreparedRequest(_:forSingleResult:)` method:
```swift
// BEFORE: GRDB 4
@@ -350,7 +401,7 @@ The changes can quite impact your application. We'll describe them below, as wel
}
```
4. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
7. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
```swift
// BEFORE: GRDB 4
@@ -360,7 +411,7 @@ The changes can quite impact your application. We'll describe them below, as wel
import GRDB
```
5. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library:
8. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library:
```swift
// BEFORE: GRDB 4
@@ -375,7 +426,6 @@ The changes can quite impact your application. We'll describe them below, as wel
```
[ValueObservation]: ../README.md#valueobservation
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
+31 -27
View File
@@ -6,16 +6,17 @@ Your SQL skills are [welcomed] throughout GRDB. Yet writing raw SQL presents com
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])
try dbQueue.write { db in
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.
@@ -34,7 +35,9 @@ SQL Interpolation is an answer to these troubles. It is available in Swift 5.
```swift
let name: String = ...
let id: Int64 = ...
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
try dbQueue.write { db in
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
}
```
SQL interpolation looks and feel just like regular [String interpolation]:
@@ -47,16 +50,12 @@ 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])
try dbQueue.write { db in
// Executes `UPDATE player SET name = 'O''Brien' WHERE id = 42`
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(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:
@@ -79,17 +78,21 @@ Plain SQL strings are indeed still available, and SQL interpolation only kicks i
**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)
try dbQueue.write { db in
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)
try dbQueue.write { db in
let query = "UPDATE player SET name = \(name) WHERE id = \(id)" // a regular String
// Compiler error:
// Cannot convert value of type 'String' to expected argument type 'SQLLiteral'
try db.execute(literal: query)
}
```
SQLLiteral can build your queries step by step, with regular operators and methods:
@@ -113,8 +116,9 @@ 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]
let (sql, arguments) = try dbQueue.read(query.build)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
```
Build a literal from a plain SQL string:
+8 -16
View File
@@ -7841,23 +7841,18 @@ Database accesses that run in background threads postpone the closing of connect
When you want to debug a request that does not deliver the expected results, you may want to print the SQL that is actually executed.
You can turn your request into a `SQLRequest` instance:
You can compile the request into a prepared statement:
```swift
try dbQueue.read { db in
let request = Wine
.filter(originColumn == "Burgundy")
.order(priceColumn)
let sqlRequest = try SQLRequest(db, request: request)
print(sqlRequest.sql)
// Prints SELECT * FROM wine WHERE origin = ? ORDER BY price
print(sqlRequest.arguments)
// Prints ["Burgundy"]
let request = Player.filter(Column("name") == "O'Brien")
let statement = try request.makePreparedRequest(db).statement
print(statement.sql) // "SELECT * FROM player WHERE name = ?"
print(statement.arguments) // ["O'Brien"]
}
```
Another option is to setup a tracing function that will print out all SQL requests executed by your application. You provide the trace function when you connect to the database:
Another option is to setup a tracing function that prints out all SQL requests executed by your application. You provide the trace function when you connect to the database:
```swift
var config = Configuration()
@@ -7865,11 +7860,8 @@ config.trace = { print($0) } // Prints all SQL statements
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
try dbQueue.read { db in
let wines = Wine
.filter(originColumn == "Burgundy")
.order(priceColumn)
.fetchAll(db)
// Prints SELECT * FROM wine WHERE origin = 'Burgundy' ORDER BY price
let players = try Player.filter(Column("name") == "O'Brien").fetchAll(db)
// Prints SELECT * FROM player WHERE name = 'O''Brien'
}
```
-4
View File
@@ -22,10 +22,6 @@
- [ ] HasAndBelongsToMany: https://github.com/groue/GRDB.swift/issues/711
- [ ] Support UNION https://github.com/groue/GRDB.swift/issues/671
- [ ] Support Subqueries: WHERE EXISTS (SELECT ...)
- [ ] Support Subqueries: document breaking change: interpolated requests are no longer wrapped in parenthesis
- [ ] Support Subqueries: document breaking change: how to extract sql from SQLLiteral
- [ ] Support Subqueries: document breaking change: how to extract sql from SQLRequest
- [ ] Support Subqueries: document breaking change: how to extract sql from QueryInterfaceRequest (SQLRequest initializer has been removed)
- [ ] Support Subqueries: document breaking change: TableRecord.selectionSQL removals
- [ ] request.exists(db) as an alternative to fetchOne(db) != nil. Can generate optimized SQL.
- [ ] Measure the duration of transactions