From 3669fadecbeed8668aa2675db5f2dbe89e6d1631 Mon Sep 17 00:00:00 2001 From: Alexandre Colucci Date: Tue, 28 May 2019 22:53:33 +0200 Subject: [PATCH] Provide one example that lets Swift build the pattern and an example with the query interface. Then provide the second approach using the || operator. --- README.md | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9bd79905a..3dd1418ca 100644 --- a/README.md +++ b/README.md @@ -8659,12 +8659,32 @@ let players = try dbQueue.read { db in What is important to understand here is that SQLite only interprets `?` as a parameter when it is a placeholder for a whole value (int, double, string, blob, null). In this incorrect query, `?` is just a character in the `'%?%'` string value: it is not a query parameter, and is not processed in any way. See [https://www.sqlite.org/lang_expr.html#varparam](https://www.sqlite.org/lang_expr.html#varparam) for more information about SQLite parameters. -To provide the parameter, one option is to let SQLite build the like pattern using the string concatenation operator `||`: +To provide the parameter, one option is to let Swift build the pattern: ```swift let name = textField.text -try dbQueue.read { db in - try db.execute(sql: "SELECT * FROM students where name like '%' || ? || '%'", arguments: [name]) +let players: [Player] = try dbQueue.read { db in + let pattern = "%\(name)%" + return try Player.fetchAll(db, sql: "SELECT * FROM player WHERE name LIKE ?", arguments: [pattern]) +} +``` + +This solution could also be used with the query interface: + +```swift +let name = textField.text +let players: [Player] = try dbQueue.read { db in + let pattern = "%\(name)%" + return try Player.filter(Column("name").like(pattern)).fetchAll(db) +} +``` + +Another option is to let SQLite build the like pattern using the string concatenation operator `||`: + +```swift +let name = textField.text +let players = try dbQueue.read { db in + try Player.fetchAll(db, sql: "SELECT * FROM player WHERE name LIKE '%' || ? || '%'", arguments: [name]) } ```