mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
Validation of raw FTS5 patterns requires a database connection and a table name
This commit is contained in:
1 parent
56578c7c0c
commit
24c672ddc9
4 files changed
+72
-69
No files matched your search
+41
-50
@@ -3,56 +3,6 @@ public struct FTS5Pattern {
|
||||
/// The raw pattern string. Guaranteed to be a valid FTS5 pattern.
|
||||
public let rawPattern: String
|
||||
|
||||
/// Creates a pattern from a raw pattern string; throws DatabaseError on
|
||||
/// invalid syntax.
|
||||
///
|
||||
/// The pattern syntax is documented at https://www.sqlite.org/fts5.html#full_text_query_syntax
|
||||
///
|
||||
/// try FTS5Pattern(rawPattern: "and") // OK
|
||||
/// try FTS5Pattern(rawPattern: "AND") // malformed MATCH expression: [AND]
|
||||
public init(rawPattern: String) throws {
|
||||
// Correctness above all: use SQLite to validate the pattern.
|
||||
//
|
||||
// Invalid patterns have SQLite return an error on the first
|
||||
// call to sqlite3_step() on a statement that matches against
|
||||
// that pattern.
|
||||
var requiredColumns: [String] = []
|
||||
while true {
|
||||
do {
|
||||
try DatabaseQueue().inDatabase { db in
|
||||
try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
if requiredColumns.isEmpty {
|
||||
t.column("content")
|
||||
} else {
|
||||
for column in requiredColumns {
|
||||
t.column(column)
|
||||
}
|
||||
}
|
||||
}
|
||||
try db.makeSelectStatement("SELECT * FROM documents WHERE documents MATCH ?")
|
||||
.fetchSequence(arguments: [rawPattern], element: { /* void (ignored) sequence element */ })
|
||||
.makeIterator()
|
||||
.step() // <- invokes sqlite3_step(), throws on invalid pattern
|
||||
}
|
||||
break
|
||||
} catch let error as DatabaseError {
|
||||
if let message = error.message, message.hasPrefix("no such column: ") {
|
||||
// Column is message suffix.
|
||||
let characters = message.characters
|
||||
let suffixIndex = characters.index(characters.startIndex, offsetBy: 16)
|
||||
let column = String(characters.suffix(from: suffixIndex))
|
||||
requiredColumns.append(column)
|
||||
} else {
|
||||
// Remove private SQL & arguments from the thrown error
|
||||
throw DatabaseError(code: error.code, message: error.message, sql: nil, arguments: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pattern is valid
|
||||
self.rawPattern = rawPattern
|
||||
}
|
||||
|
||||
/// Creates a pattern that matches any token found in the input string;
|
||||
/// returns nil if no pattern could be built.
|
||||
///
|
||||
@@ -94,6 +44,47 @@ public struct FTS5Pattern {
|
||||
guard !tokens.isEmpty else { return nil }
|
||||
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
|
||||
}
|
||||
|
||||
fileprivate init(rawPattern: String, allowedColumns: [String] = ["__grdb__"]) throws {
|
||||
// Correctness above all: use SQLite to validate the pattern.
|
||||
//
|
||||
// Invalid patterns have SQLite return an error on the first
|
||||
// call to sqlite3_step() on a statement that matches against
|
||||
// that pattern.
|
||||
do {
|
||||
try DatabaseQueue().inDatabase { db in
|
||||
try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
for column in allowedColumns {
|
||||
t.column(column)
|
||||
}
|
||||
}
|
||||
try db.makeSelectStatement("SELECT * FROM documents WHERE documents MATCH ?")
|
||||
.fetchSequence(arguments: [rawPattern], element: { /* void (ignored) sequence element */ })
|
||||
.makeIterator()
|
||||
.step() // <- invokes sqlite3_step(), throws on invalid pattern
|
||||
}
|
||||
} catch let error as DatabaseError {
|
||||
// Remove private SQL & arguments from the thrown error
|
||||
throw DatabaseError(code: error.code, message: error.message, sql: nil, arguments: nil)
|
||||
}
|
||||
|
||||
// Pattern is valid
|
||||
self.rawPattern = rawPattern
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
/// Creates a pattern from a raw pattern string; throws DatabaseError on
|
||||
/// invalid syntax.
|
||||
///
|
||||
/// The pattern syntax is documented at https://www.sqlite.org/fts5.html#full_text_query_syntax
|
||||
///
|
||||
/// try db.fts5Pattern(rawPattern: "and", forTable: "documents") // OK
|
||||
/// try db.fts5Pattern(rawPattern: "AND", forTable: "documents") // malformed MATCH expression: [AND]
|
||||
public func fts5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern {
|
||||
return try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map { $0.name })
|
||||
}
|
||||
}
|
||||
|
||||
extension FTS5Pattern : DatabaseValueConvertible {
|
||||
|
||||
@@ -3220,11 +3220,13 @@ struct FTS3Pattern {
|
||||
}
|
||||
```
|
||||
|
||||
The first initializer may throw a [DatabaseError](#databaseerror): it validates your raw patterns against the query grammar:
|
||||
The first initializer validates your raw patterns against the query grammar, and may throw a [DatabaseError](#databaseerror):
|
||||
|
||||
```swift
|
||||
let pattern = try FTS3Pattern(rawPattern: "sqlite AND database") // OK
|
||||
let pattern = try FTS3Pattern(rawPattern: "AND") // DatabaseError
|
||||
// OK: FTS3Pattern
|
||||
let pattern = try FTS3Pattern(rawPattern: "sqlite AND database")
|
||||
// DatabaseError: malformed MATCH expression: [AND]
|
||||
let pattern = try FTS3Pattern(rawPattern: "AND")
|
||||
```
|
||||
|
||||
The three other initializers don't throw. They build a valid pattern from any string, including strings provided by users of your application. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application:
|
||||
@@ -3397,22 +3399,29 @@ SELECT * FROM documents WHERE documents MATCH '"SQLite database"'
|
||||
GRDB provides the FTS5Pattern type which helps you building **valid patterns**:
|
||||
|
||||
```swift
|
||||
extension Database {
|
||||
func fts5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern
|
||||
}
|
||||
|
||||
struct FTS5Pattern {
|
||||
init(rawPattern: String) throws
|
||||
init?(matchingAnyTokenIn string: String)
|
||||
init?(matchingAllTokensIn string: String)
|
||||
init?(matchingPhrase string: String)
|
||||
}
|
||||
```
|
||||
|
||||
The first initializer may throw a [DatabaseError](#databaseerror): it validates your raw patterns against the query grammar:
|
||||
The `Database.fts5Pattern(rawPattern:forTable:)` method validates your raw patterns against the query grammar and the columns of the targeted table, and may throw a [DatabaseError](#databaseerror):
|
||||
|
||||
```swift
|
||||
let pattern = try FTS5Pattern(rawPattern: "sqlite AND database") // OK
|
||||
let pattern = try FTS5Pattern(rawPattern: "AND") // DatabaseError
|
||||
// OK: FTS5Pattern
|
||||
try db.fts5Pattern(rawPattern: "sqlite", forTable: "books")
|
||||
// DatabaseError: syntax error near \"AND\"
|
||||
try db.fts5Pattern(rawPattern: "AND", forTable: "books")
|
||||
// DatabaseError: no such column: missing
|
||||
try db.fts5Pattern(rawPattern: "missing: sqlite", forTable: "books")
|
||||
```
|
||||
|
||||
The three other initializers don't throw. They build a valid pattern from any string, including strings provided by users of your application. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application:
|
||||
The FTS5Pattern initializers don't throw. They build a valid pattern from any string, including strings provided by users of your application. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application:
|
||||
|
||||
```swift
|
||||
let query = "SQLite database"
|
||||
|
||||
@@ -67,7 +67,6 @@ class FTS3PatternTests: GRDBTestCase {
|
||||
_ = try FTS3Pattern(rawPattern: rawPattern)
|
||||
XCTFail("Expected pattern to be invalid: \(String(reflecting: rawPattern))")
|
||||
} catch is DatabaseError {
|
||||
|
||||
} catch {
|
||||
XCTFail("Expected DatabaseError, not \(error)")
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ class FTS5PatternTests: GRDBTestCase {
|
||||
("title:brest", 1)
|
||||
]
|
||||
for (rawPattern, expectedCount) in validRawPatterns {
|
||||
let pattern = try FTS5Pattern(rawPattern: rawPattern)
|
||||
let pattern = try db.fts5Pattern(rawPattern: rawPattern, forTable: "books")
|
||||
let count = Int.fetchOne(db, "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: [pattern])!
|
||||
XCTAssertEqual(count, expectedCount, "Expected pattern \(String(reflecting: rawPattern)) to yield \(expectedCount) results")
|
||||
}
|
||||
@@ -58,15 +58,19 @@ class FTS5PatternTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func testInvalidFTS5Pattern() {
|
||||
let invalidRawPatterns = ["", "?!", "^", "^foo", "NOT", "(", "AND", "OR", "\""]
|
||||
for rawPattern in invalidRawPatterns {
|
||||
do {
|
||||
_ = try FTS5Pattern(rawPattern: rawPattern)
|
||||
XCTFail("Expected pattern to be invalid: \(String(reflecting: rawPattern))")
|
||||
} catch is DatabaseError {
|
||||
|
||||
} catch {
|
||||
XCTFail("Expected DatabaseError, not \(error)")
|
||||
assertNoError {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
dbQueue.inDatabase { db in
|
||||
let invalidRawPatterns = ["", "?!", "^", "^foo", "NOT", "(", "AND", "OR", "\"", "missing:foo"]
|
||||
for rawPattern in invalidRawPatterns {
|
||||
do {
|
||||
_ = try db.fts5Pattern(rawPattern: rawPattern, forTable: "books")
|
||||
XCTFail("Expected pattern to be invalid: \(String(reflecting: rawPattern))")
|
||||
} catch is DatabaseError {
|
||||
} catch {
|
||||
XCTFail("Expected DatabaseError, not \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user