FTS5 DocC

This commit is contained in:
Gwendal Roué committed 2023-02-19 17:38:19 +01:00
1 parent dc4f10ecb0
commit 3b0cf1fb0b
13 files changed
+529 -285

No files matched your search

@@ -12,3 +12,4 @@ Please refer to the [Full-Text Search](https://github.com/groue/GRDB.swift/blob/
- ``FTS3``
- ``FTS4``
- ``FTS5``
+17 -12
View File
@@ -1,7 +1,14 @@
/// The virtual table module for the FTS3 full-text engine.
///
/// To create FTS3 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``.
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts3(content)
/// try db.create(virtualTable: "document", using: FTS3()) { t in
/// t.column("content")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/fts3.html>
///
@@ -23,25 +30,23 @@
public struct FTS3 {
/// Options for Latin script characters.
public enum Diacritics {
/// Do not remove diacritics from Latin script characters.
/// Do not remove diacritics from Latin script characters. This option
/// matches the `remove_diacritics=0` tokenizer argument.
///
/// This option matches the `remove_diacritics=0` tokenizer argument.
/// Related SQLite documentation: <https://www.sqlite.org/fts3.html#tokenizer>
case keep
/// Remove diacritics from Latin script characters.
///
/// This option matches the `remove_diacritics=1` tokenizer argument.
/// Remove diacritics from Latin script characters. This option matches
/// the `remove_diacritics=1` tokenizer argument.
case removeLegacy
#if GRDBCUSTOMSQLITE
/// Remove diacritics from Latin script characters.
///
/// This option matches the `remove_diacritics=2` tokenizer argument.
/// Remove diacritics from Latin script characters. This option matches
/// the `remove_diacritics=2` tokenizer argument.
case remove
#elseif !GRDBCIPHER
/// Remove diacritics from Latin script characters.
///
/// This option matches the `remove_diacritics=2` tokenizer argument.
/// Remove diacritics from Latin script characters. This option matches
/// the `remove_diacritics=2` tokenizer argument.
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.27+
case remove
#endif
+6 -6
View File
@@ -1,11 +1,11 @@
/// An ``FTS3`` tokenizer.
/// The descriptor for an ``FTS3`` tokenizer.
///
/// `FTS3TokenizerDescriptor` can be used in both ``FTS3`` and ``FTS4`` tables.
///
/// For example:
///
/// ```swift
/// db.create(virtualTable: "book", using: FTS4()) { t in
/// try db.create(virtualTable: "book", using: FTS4()) { t in
/// t.tokenizer = .simple // FTS3TokenizerDescriptor
/// }
/// ```
@@ -14,7 +14,7 @@
///
/// ## Topics
///
/// ### Creating Tokenizers
/// ### Creating Tokenizer Descriptors
///
/// - ``porter``
/// - ``simple``
@@ -34,7 +34,7 @@ public struct FTS3TokenizerDescriptor {
/// For example:
///
/// ```swift
/// db.create(virtualTable: "book", using: FTS4()) { t in
/// try db.create(virtualTable: "book", using: FTS4()) { t in
/// t.tokenizer = .simple
/// }
/// ```
@@ -47,7 +47,7 @@ public struct FTS3TokenizerDescriptor {
/// For example:
///
/// ```swift
/// db.create(virtualTable: "book", using: FTS4()) { t in
/// try db.create(virtualTable: "book", using: FTS4()) { t in
/// t.tokenizer = .porter
/// }
/// ```
@@ -60,7 +60,7 @@ public struct FTS3TokenizerDescriptor {
/// For example:
///
/// ```swift
/// db.create(virtualTable: "book", using: FTS4()) { t in
/// try db.create(virtualTable: "book", using: FTS4()) { t in
/// t.tokenizer = .unicode61()
/// }
/// ```
+10 -3
View File
@@ -1,7 +1,14 @@
/// The virtual table module for the FTS4 full-text engine.
///
/// To create FTS4 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``.
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts4(content)
/// try db.create(virtualTable: "document", using: FTS4()) { t in
/// t.column("content")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/fts3.html>
///
@@ -234,7 +241,7 @@ public final class FTS4TableDefinition {
/// The FTS4 `prefix` option.
///
/// // CREATE VIRTUAL TABLE document USING FTS4(content, prefix='2 4');
/// db.create(virtualTable: "document", using:FTS4()) { t in
/// try db.create(virtualTable: "document", using:FTS4()) { t in
/// t.prefixes = [2, 4]
/// t.column("content")
/// }
@@ -300,7 +307,7 @@ public final class FTS4TableDefinition {
/// try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/fts5.html#external_content_tables>
/// Related SQLite documentation: <https://www.sqlite.org/fts3.html#_external_content_fts4_tables_>
public func synchronize(withTable tableName: String) {
contentMode = .synchronized(contentTable: tableName)
}
+215 -122
View File
@@ -1,19 +1,45 @@
#if SQLITE_ENABLE_FTS5
import Foundation
/// FTS5 lets you define "fts5" virtual tables.
/// The virtual table module for the FTS5 full-text engine.
///
/// // CREATE VIRTUAL TABLE document USING fts5(content)
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content")
/// }
/// To create FTS5 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
///
/// See <https://www.sqlite.org/fts5.html>
public struct FTS5: VirtualTableModule {
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts5(content)
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html>
///
/// ## Topics
///
/// ### The FTS5 Module
///
/// - ``init()``
/// - ``FTS5TableDefinition``
/// - ``FTS5ColumnDefinition``
/// - ``FTS5TokenizerDescriptor``
///
/// ### Full-Text Search Pattern
///
/// - ``FTS5Pattern``
///
/// ### FTS5 Tokenizers
///
/// - ``FTS5Tokenizer``
/// - ``FTS5CustomTokenizer``
/// - ``FTS5WrapperTokenizer``
/// - ``FTS5TokenFlags``
/// - ``FTS5Tokenization``
public struct FTS5 {
/// Options for Latin script characters. Matches the raw "remove_diacritics"
/// tokenizer argument.
///
/// See <https://www.sqlite.org/fts5.html>
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#unicode61_tokenizer>
public enum Diacritics {
/// Do not remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=0" tokenizer argument.
@@ -35,15 +61,18 @@ public struct FTS5: VirtualTableModule {
#endif
}
/// Creates a FTS5 module suitable for the Database
/// `create(virtualTable:using:)` method.
/// Creates an FTS5 module.
///
/// // CREATE VIRTUAL TABLE document USING fts5(content)
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content")
/// }
/// For example:
///
/// See <https://www.sqlite.org/fts5.html>
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts5(content)
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content")
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
public init() { }
// Support for FTS5Pattern initializers. Don't make public. Users tokenize
@@ -71,10 +100,70 @@ public struct FTS5: VirtualTableModule {
}
}
// MARK: - VirtualTableModule Adoption
static func api(_ db: Database) -> UnsafePointer<fts5_api> {
// Access to FTS5 is one of the rare SQLite api which was broken in
// SQLite 3.20.0+, for security reasons:
//
// Starting SQLite 3.20.0+, we need to use the new sqlite3_bind_pointer api.
// The previous way to access FTS5 does not work any longer.
//
// So let's see which SQLite version we are linked against:
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// GRDB is linked against SQLCipher or a custom SQLite build: SQLite 3.20.0 or more.
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
#else
// GRDB is linked against the system SQLite.
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
} else {
return api_v1(db)
}
#endif
}
private static func api_v1(_ db: Database) -> UnsafePointer<fts5_api> {
guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else {
fatalError("FTS5 is not available")
}
return data.withUnsafeBytes {
$0.bindMemory(to: UnsafePointer<fts5_api>.self).first!
}
}
// Technique given by Jordan Rose:
// https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4
private static func api_v2(
_ db: Database,
// swiftlint:disable:next line_length
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> CInt,
// swiftlint:disable:next line_length
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt)
-> UnsafePointer<fts5_api>
{
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
let type: StaticString = "fts5_api_ptr"
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
guard code == SQLITE_OK else {
fatalError("FTS5 is not available")
}
defer { sqlite3_finalize(statement) }
type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
}
sqlite3_step(statement)
guard let api else {
fatalError("FTS5 is not available")
}
return api
}
}
extension FTS5: VirtualTableModule {
/// The virtual table module name
public let moduleName = "fts5"
public var moduleName: String { "fts5" }
/// Reserved; part of the VirtualTableModule protocol.
///
@@ -203,78 +292,38 @@ public struct FTS5: VirtualTableModule {
try db.execute(sql: "INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')")
}
}
static func api(_ db: Database) -> UnsafePointer<fts5_api> {
// Access to FTS5 is one of the rare SQLite api which was broken in
// SQLite 3.20.0+, for security reasons:
//
// Starting SQLite 3.20.0+, we need to use the new sqlite3_bind_pointer api.
// The previous way to access FTS5 does not work any longer.
//
// So let's see which SQLite version we are linked against:
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// GRDB is linked against SQLCipher or a custom SQLite build: SQLite 3.20.0 or more.
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
#else
// GRDB is linked against the system SQLite.
if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
} else {
return api_v1(db)
}
#endif
}
private static func api_v1(_ db: Database) -> UnsafePointer<fts5_api> {
guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else {
fatalError("FTS5 is not available")
}
return data.withUnsafeBytes {
$0.bindMemory(to: UnsafePointer<fts5_api>.self).first!
}
}
// Technique given by Jordan Rose:
// https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4
private static func api_v2(
_ db: Database,
// swiftlint:disable:next line_length
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> CInt,
// swiftlint:disable:next line_length
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt)
-> UnsafePointer<fts5_api>
{
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
let type: StaticString = "fts5_api_ptr"
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
guard code == SQLITE_OK else {
fatalError("FTS5 is not available")
}
defer { sqlite3_finalize(statement) }
type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
}
sqlite3_step(statement)
guard let api else {
fatalError("FTS5 is not available")
}
return api
}
}
/// The FTS5TableDefinition class lets you define columns of a FTS5 virtual table.
/// A `FTS5TableDefinition` lets you define the components of an FTS5
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the Database
/// `create(virtualTable:using:)` method:
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
/// t.column("content")
/// }
/// ```swift
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
/// t.column("content")
/// }
/// ```
///
/// See <https://www.sqlite.org/fts5.html>
/// ## Topics
///
/// ### Define Columns
///
/// - ``column(_:)``
///
/// ### External Content Tables
///
/// - ``synchronize(withTable:)``
///
/// ### FTS5 Options
///
/// - ``columnSize``
/// - ``content``
/// - ``contentRowID``
/// - ``detail``
/// - ``prefixes``
/// - ``tokenizer``
public final class FTS5TableDefinition {
enum ContentMode {
case raw(content: String?, contentRowID: String?)
@@ -285,25 +334,30 @@ public final class FTS5TableDefinition {
fileprivate var columns: [FTS5ColumnDefinition] = []
fileprivate var contentMode: ContentMode = .raw(content: nil, contentRowID: nil)
/// The virtual table tokenizer
/// The virtual table tokenizer.
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.tokenizer = .porter()
/// }
/// For example:
///
/// See <https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization>
/// ```swift
/// // CREATE VIRTUAL TABLE "documents" USING fts5(tokenize=porter)
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.tokenizer = .porter()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization>
public var tokenizer: FTS5TokenizerDescriptor?
/// The FTS5 `content` option
/// The FTS5 `content` option.
///
/// When you want the full-text table to be synchronized with the
/// content of an external table, prefer the `synchronize(withTable:)`
/// method.
/// content of an external table, prefer the
/// ``synchronize(withTable:)`` method.
///
/// Setting this property invalidates any synchronization previously
/// established with the `synchronize(withTable:)` method.
/// established with the ``synchronize(withTable:)`` method.
///
/// See <https://www.sqlite.org/fts5.html#external_content_and_contentless_tables>
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#external_content_and_contentless_tables>
public var content: String? {
get {
switch contentMode {
@@ -326,13 +380,13 @@ public final class FTS5TableDefinition {
/// The FTS5 `content_rowid` option
///
/// When you want the full-text table to be synchronized with the
/// content of an external table, prefer the `synchronize(withTable:)`
/// method.
/// content of an external table, prefer the
/// ``synchronize(withTable:)`` method.
///
/// Setting this property invalidates any synchronization previously
/// established with the `synchronize(withTable:)` method.
/// established with the ``synchronize(withTable:)`` method.
///
/// See <https://sqlite.org/fts5.html#external_content_tables>
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#external_content_tables>
public var contentRowID: String? {
get {
switch contentMode {
@@ -352,19 +406,19 @@ public final class FTS5TableDefinition {
}
}
/// Support for the FTS5 `prefix` option
/// The FTS5 `prefix` option.
///
/// See <https://www.sqlite.org/fts5.html#prefix_indexes>
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#prefix_indexes>
public var prefixes: Set<Int>?
/// Support for the FTS5 `columnsize` option
/// The FTS5 `columnsize` option.
///
/// <https://www.sqlite.org/fts5.html#the_columnsize_option>
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#the_columnsize_option>
public var columnSize: Int?
/// Support for the FTS5 `detail` option
/// The FTS5 `detail` option.
///
/// <https://www.sqlite.org/fts5.html#the_detail_option>
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#the_detail_option>
public var detail: String?
init(configuration: VirtualTableConfiguration) {
@@ -373,11 +427,18 @@ public final class FTS5TableDefinition {
/// Appends a table column.
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content")
/// }
/// For example:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts5(content)
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content")
/// }
/// ```
///
/// - parameter name: the column name.
/// - returns: A ``FTS5ColumnDefinition`` that allows you to refine the
/// column definition.
@discardableResult
public func column(_ name: String) -> FTS5ColumnDefinition {
let column = FTS5ColumnDefinition(name: name)
@@ -392,22 +453,50 @@ public final class FTS5TableDefinition {
/// content in the external table. SQL triggers make sure that the
/// full-text table is kept up to date with the external table.
///
/// See <https://sqlite.org/fts5.html#external_content_tables>
/// SQLite automatically deletes those triggers when the content
/// (not full-text) table is dropped.
///
/// However, those triggers remain after the full-text table has been
/// dropped. Unless they are dropped too, they will prevent future
/// insertion, updates, and deletions in the content table, and the creation
/// of a new full-text table.
///
/// To drop those triggers, call the `Database`
/// ``Database/dropFTS5SynchronizationTriggers(forTable:)`` method:
///
/// ```swift
/// // Create tables
/// try db.create(table: "book") { t in
/// ...
/// }
/// try db.create(virtualTable: "book_ft", using: FTS5()) { t in
/// t.synchronize(withTable: "book")
/// ...
/// }
///
/// // Drop full-text table
/// try db.drop(table: "book_ft")
/// try db.dropFTS5SynchronizationTriggers(forTable: "book_ft")
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/fts5.html#external_content_tables>
public func synchronize(withTable tableName: String) {
contentMode = .synchronized(contentTable: tableName)
}
}
/// The FTS5ColumnDefinition class lets you refine a column of an FTS5
/// virtual table.
/// Describes a column in an ``FTS5`` virtual table.
///
/// You get instances of this class when you create an FTS5 table:
/// You get instances of `FTS5ColumnDefinition` when you create an ``FTS5``
/// virtual table. For example:
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content") // FTS5ColumnDefinition
/// }
/// ```swift
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content") // FTS5ColumnDefinition
/// }
/// ```
///
/// See <https://www.sqlite.org/fts5.html>
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html>
public final class FTS5ColumnDefinition {
fileprivate let name: String
fileprivate var isIndexed: Bool
@@ -419,14 +508,18 @@ public final class FTS5ColumnDefinition {
/// Excludes the column from the full-text index.
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("a")
/// t.column("b").notIndexed()
/// }
/// For example:
///
/// See <https://www.sqlite.org/fts5.html#the_unindexed_column_option>
/// ```swift
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("a")
/// t.column("b").notIndexed()
/// }
/// ```
///
/// - returns: Self so that you can further refine the column definition.
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#the_unindexed_column_option>
///
/// - returns: `self` so that you can further refine the column definition.
@discardableResult
public func notIndexed() -> Self {
self.isIndexed = false
@@ -435,7 +528,7 @@ public final class FTS5ColumnDefinition {
}
extension Column {
/// The FTS5 rank column
/// The ``FTS5`` rank column.
public static let rank = Column("rank")
}
+9 -5
View File
@@ -1,9 +1,13 @@
#if SQLITE_ENABLE_FTS5
/// The protocol for custom FTS5 tokenizers.
/// A type that implements a custom tokenizer for the ``FTS5`` full-text engine.
///
/// See [FTS5 Tokenizers](https://github.com/groue/GRDB.swift/blob/master/Documentation/FTS5Tokenizers.md)
/// for more information.
public protocol FTS5CustomTokenizer: FTS5Tokenizer {
/// The name of the tokenizer; should uniquely identify your custom
/// tokenizer.
/// The name of the tokenizer.
///
/// The name should uniquely identify the tokenizer: don't use a built-in
/// name such as `ascii`, `porter` or `unicode61`.
static var name: String { get }
/// Creates a custom tokenizer.
@@ -27,7 +31,7 @@ extension FTS5CustomTokenizer {
///
/// class MyTokenizer : FTS5CustomTokenizer { ... }
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// try db.create(virtualTable: "book", using: FTS5()) { t in
/// let tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["unicode61", "remove_diacritics", "0"])
/// t.tokenizer = tokenizer
/// }
+90 -32
View File
@@ -1,17 +1,40 @@
#if SQLITE_ENABLE_FTS5
/// A full text pattern for querying FTS5 virtual tables.
/// A full text pattern for querying ``FTS5`` virtual tables.
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#full_text_query_syntax>
///
/// ## Topics
///
/// ### Creating Raw FTS5 Patterns
///
/// - ``Database/makeFTS5Pattern(rawPattern:forTable:)``
///
/// ### Creating FTS5 Patterns from User Input
///
/// - ``init(matchingAllPrefixesIn:)``
/// - ``init(matchingAllTokensIn:)``
/// - ``init(matchingAnyTokenIn:)``
/// - ``init(matchingPhrase:)``
/// - ``init(matchingPrefixPhrase:)``
public struct FTS5Pattern {
/// The raw pattern string. Guaranteed to be a valid FTS5 pattern.
/// The raw pattern string.
///
/// It is guaranteed to be a valid FTS5 pattern.
public let rawPattern: String
/// Creates a pattern that matches any token found in the input string;
/// returns nil if no pattern could be built.
/// Creates a pattern that matches any token found in the input string.
///
/// FTS5Pattern(matchingAnyTokenIn: "") // nil
/// FTS5Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
/// The result is nil if no pattern could be built.
///
/// - parameter string: The string to turn into an FTS5 pattern
/// For example:
///
/// ```swift
/// FTS5Pattern(matchingAnyTokenIn: "") // nil
/// FTS5Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
/// ```
///
/// - parameter string: The string to turn into an FTS5 pattern.
public init?(matchingAnyTokenIn string: String) {
guard let tokens = try? FTS5.tokenize(query: string), !tokens.isEmpty else {
return nil
@@ -19,13 +42,18 @@ public struct FTS5Pattern {
try? self.init(rawPattern: tokens.joined(separator: " OR "))
}
/// Creates a pattern that matches all tokens found in the input string;
/// returns nil if no pattern could be built.
/// Creates a pattern that matches all tokens found in the input string.
///
/// FTS5Pattern(matchingAllTokensIn: "") // nil
/// FTS5Pattern(matchingAllTokensIn: "foo bar") // foo bar
/// The result is nil if no pattern could be built.
///
/// - parameter string: The string to turn into an FTS5 pattern
/// For example:
///
/// ```swift
/// FTS5Pattern(matchingAllTokensIn: "") // nil
/// FTS5Pattern(matchingAllTokensIn: "foo bar") // foo bar
/// ```
///
/// - parameter string: The string to turn into an FTS5 pattern.
public init?(matchingAllTokensIn string: String) {
guard let tokens = try? FTS5.tokenize(query: string), !tokens.isEmpty else {
return nil
@@ -34,12 +62,18 @@ public struct FTS5Pattern {
}
/// Creates a pattern that matches all token prefixes found in the input
/// string; returns nil if no pattern could be built.
/// string.
///
/// FTS3Pattern(matchingAllTokensIn: "") // nil
/// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo* bar*
/// The result is nil if no pattern could be built.
///
/// - parameter string: The string to turn into an FTS3 pattern
/// For example:
///
/// ```swift
/// FTS5Pattern(matchingAllTokensIn: "") // nil
/// FTS5Pattern(matchingAllTokensIn: "foo bar") // foo* bar*
/// ```
///
/// - parameter string: The string to turn into an FTS5 pattern.
public init?(matchingAllPrefixesIn string: String) {
guard let tokens = try? FTS5.tokenize(query: string), !tokens.isEmpty else {
return nil
@@ -47,13 +81,18 @@ public struct FTS5Pattern {
try? self.init(rawPattern: tokens.map { "\($0)*" }.joined(separator: " "))
}
/// Creates a pattern that matches a contiguous string; returns nil if no
/// pattern could be built.
/// Creates a pattern that matches a contiguous string.
///
/// FTS5Pattern(matchingPhrase: "") // nil
/// FTS5Pattern(matchingPhrase: "foo bar") // "foo bar"
/// The result is nil if no pattern could be built.
///
/// - parameter string: The string to turn into an FTS5 pattern
/// For example:
///
/// ```swift
/// FTS5Pattern(matchingPhrase: "") // nil
/// FTS5Pattern(matchingPhrase: "foo bar") // "foo bar"
/// ```
///
/// - parameter string: The string to turn into an FTS5 pattern.
public init?(matchingPhrase string: String) {
guard let tokens = try? FTS5.tokenize(query: string), !tokens.isEmpty else {
return nil
@@ -61,14 +100,20 @@ public struct FTS5Pattern {
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
/// Creates a pattern that matches the prefix of an indexed document;
/// returns nil if no pattern could be built.
/// Creates a pattern that matches the prefix of an indexed document.
///
/// FTS5Pattern(matchingPrefixPhrase: "") // nil
/// FTS5Pattern(matchingPrefixPhrase: "the word") // ^"the word"
/// The result is nil if no pattern could be built.
///
/// This pattern matches a prefix made of full tokens: "the bat" matches
/// "the bat is happy", but not "mind the bat", or "the batcave is dark".
/// The returned pattern matches a prefix made of full tokens: "the bat"
/// matches "the bat is happy", but not "mind the bat", or "the batcave
/// is dark".
///
/// For example:
///
/// ```swift
/// FTS5Pattern(matchingPrefixPhrase: "") // nil
/// FTS5Pattern(matchingPrefixPhrase: "the word") // ^"the word"
/// ```
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingPrefixPhrase string: String) {
@@ -113,13 +158,26 @@ extension Database {
// MARK: - FTS5
/// Creates a pattern from a raw pattern string; throws DatabaseError on
/// invalid syntax.
/// Creates an FTS5 pattern from a raw pattern string.
///
/// The pattern syntax is documented at <https://www.sqlite.org/fts5.html#full_text_query_syntax>
/// For example:
///
/// try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK
/// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND]
/// ```swift
/// try dbQueue.read { db in
/// // OK
/// let pattern = try db.makeFTS5Pattern(rawPattern: "and", forTable: "document")
///
/// // Throws error: malformed MATCH expression: [AND]
/// let pattern = try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document")
/// }
/// ```
///
/// - parameter rawPattern: A pattern that follows the
/// [Full-text Query Syntax](https://www.sqlite.org/fts5.html#full_text_query_syntax).
/// - parameter table: The full-text table that the pattern is intended to
/// match against.
/// - returns: A valid FTS5 pattern.
/// - throws: A ``DatabaseError`` if the raw pattern is invalid.
public func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern {
try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map(\.name))
}
+55 -22
View File
@@ -3,7 +3,7 @@ import Foundation
/// A low-level SQLite function that lets FTS5Tokenizer notify tokens.
///
/// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:)
/// See ``FTS5Tokenizer/tokenize(context:tokenization:pText:nText:tokenCallback:)``.
public typealias FTS5TokenCallback = @convention(c) (
_ context: UnsafeMutableRawPointer?,
_ flags: CInt,
@@ -15,7 +15,7 @@ public typealias FTS5TokenCallback = @convention(c) (
/// The reason why FTS5 is requesting tokenization.
///
/// See <https://www.sqlite.org/fts5.html#custom_tokenizers>
/// See the `FTS5_TOKENIZE_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
public struct FTS5Tokenization: OptionSet {
public let rawValue: CInt
@@ -23,20 +23,42 @@ public struct FTS5Tokenization: OptionSet {
self.rawValue = rawValue
}
/// FTS5_TOKENIZE_QUERY
/// `FTS5_TOKENIZE_QUERY`
public static let query = FTS5Tokenization(rawValue: FTS5_TOKENIZE_QUERY)
/// FTS5_TOKENIZE_PREFIX
/// `FTS5_TOKENIZE_PREFIX`
public static let prefix = FTS5Tokenization(rawValue: FTS5_TOKENIZE_PREFIX)
/// FTS5_TOKENIZE_DOCUMENT
/// `FTS5_TOKENIZE_DOCUMENT`
public static let document = FTS5Tokenization(rawValue: FTS5_TOKENIZE_DOCUMENT)
/// FTS5_TOKENIZE_AUX
/// `FTS5_TOKENIZE_AUX`
public static let aux = FTS5Tokenization(rawValue: FTS5_TOKENIZE_AUX)
}
/// The protocol for FTS5 tokenizers
/// A type that implements a tokenizer for the ``FTS5`` full-text engine.
///
/// You can instantiate tokenizers, including
/// [built-in tokenizers](https://www.sqlite.org/fts5.html#tokenizers),
/// with the ``Database/makeTokenizer(_:)`` method:
///
/// ```swift
/// try dbQueue.read { db in
/// let unicode61 = try db.makeTokenizer(.unicode61()) // FTS5Tokenizer
/// }
/// ```
///
/// See [FTS5 Tokenizers](https://github.com/groue/GRDB.swift/blob/master/Documentation/FTS5Tokenizers.md)
/// for more information.
///
/// ## Topics
///
/// ### Tokenizing Text
///
/// - ``tokenize(document:)``
/// - ``tokenize(query:)``
/// - ``tokenize(context:tokenization:pText:nText:tokenCallback:)``
/// - ``FTS5TokenCallback``
public protocol FTS5Tokenizer: AnyObject {
/// Tokenizes the text described by `pText` and `nText`, and
/// notifies found tokens to the `tokenCallback` function.
@@ -72,8 +94,10 @@ extension FTS5Tokenizer {
///
/// For example:
///
/// let tokenizer = try db.makeTokenizer(.ascii())
/// try tokenizer.tokenize(document: "foo bar") // [("foo", flags), ("bar", flags)]
/// ```swift
/// let tokenizer = try db.makeTokenizer(.ascii())
/// try tokenizer.tokenize(document: "foo bar") // [("foo", flags), ("bar", flags)]
/// ```
///
/// See also `tokenize(query:)`.
///
@@ -88,8 +112,10 @@ extension FTS5Tokenizer {
///
/// For example:
///
/// let tokenizer = try db.makeTokenizer(.ascii())
/// try tokenizer.tokenize(query: "foo bar") // [("foo", flags), ("bar", flags)]
/// ```swift
/// let tokenizer = try db.makeTokenizer(.ascii())
/// try tokenizer.tokenize(query: "foo bar") // [("foo", flags), ("bar", flags)]
/// ```
///
/// See also `tokenize(document:)`.
///
@@ -240,20 +266,27 @@ extension Database {
/// Creates an FTS5 tokenizer, given its descriptor.
///
/// let unicode61 = try db.makeTokenizer(.unicode61())
/// For example:
///
/// ```swift
/// let unicode61 = try db.makeTokenizer(.unicode61())
/// ```
///
/// You can use this method when you implement a custom wrapper tokenizer
/// with ``FTS5WrapperTokenizer``:
///
/// ```swift
/// final class MyTokenizer : FTS5WrapperTokenizer {
/// var wrappedTokenizer: FTS5Tokenizer
///
/// init(db: Database, arguments: [String]) throws {
/// wrappedTokenizer = try db.makeTokenizer(.unicode61())
/// }
/// }
/// ```
///
/// It is a programmer error to use the tokenizer outside of a protected
/// database queue, or after the database has been closed.
///
/// Use this method when you implement a custom wrapper tokenizer:
///
/// final class MyTokenizer : FTS5WrapperTokenizer {
/// var wrappedTokenizer: FTS5Tokenizer
///
/// init(db: Database, arguments: [String]) throws {
/// wrappedTokenizer = try db.makeTokenizer(.unicode61())
/// }
/// }
public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> any FTS5Tokenizer {
let api = FTS5.api(self)
+95 -40
View File
@@ -1,61 +1,109 @@
#if SQLITE_ENABLE_FTS5
/// An FTS5 tokenizer, suitable for FTS5 table definitions:
/// The descriptor for an ``FTS5`` tokenizer.
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor
/// }
/// For example:
///
/// See <https://www.sqlite.org/fts5.html#tokenizers>
/// ```swift
/// try db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#tokenizers>
///
/// ## Topics
///
/// ### Creating Tokenizer Descriptors
///
/// - ``init(components:)``
/// - ``ascii(separators:tokenCharacters:)``
/// - ``porter(wrapping:)``
/// - ``unicode61(diacritics:categories:separators:tokenCharacters:)``
/// - ``FTS5/Diacritics``
///
/// ### Instantiating Tokenizers
///
/// - ``Database/makeTokenizer(_:)``
public struct FTS5TokenizerDescriptor {
/// The tokenizer components
/// The tokenizer components.
///
/// // ["unicode61"]
/// FTS5TokenizerDescriptor.unicode61().components
/// For example:
///
/// // ["unicode61", "remove_diacritics", "0"]
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components
/// ```swift
/// // ["unicode61"]
/// FTS5TokenizerDescriptor.unicode61().components
///
/// // ["unicode61", "remove_diacritics", "0"]
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components
/// ```
public let components: [String]
/// The tokenizer name
/// The tokenizer name.
///
/// // "unicode61"
/// FTS5TokenizerDescriptor.unicode61().name
/// For example:
///
/// // "unicode61"
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).name
/// ```swift
/// // "unicode61"
/// FTS5TokenizerDescriptor.unicode61().name
///
/// // "unicode61"
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).name
/// ```
var name: String { components[0] }
/// The tokenizer arguments.
///
/// For example:
///
/// ```swift
/// // []
/// FTS5TokenizerDescriptor.unicode61().components
///
/// // ["remove_diacritics", "0"]
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components
/// ```
var arguments: [String] {
Array(components.suffix(from: 1))
}
/// Creates an FTS5 tokenizer descriptor.
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// let tokenizer = FTS5TokenizerDescriptor(components: ["porter", "unicode61", "remove_diacritics", "0"])
/// t.tokenizer = tokenizer
/// }
/// For example:
///
/// - precondition: Components is not empty
/// ```swift
/// try db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = FTS5TokenizerDescriptor(components: [
/// "porter",
/// "unicode61",
/// "remove_diacritics",
/// "0"])
/// }
/// ```
///
/// - precondition: Components is not empty.
public init(components: [String]) {
GRDBPrecondition(!components.isEmpty, "FTS5TokenizerDescriptor requires at least one component")
assert(!components.isEmpty)
self.components = components
}
/// The "ascii" tokenizer
/// The "ascii" tokenizer.
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .ascii()
/// }
/// For example:
///
/// ```swift
/// try db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .ascii()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#ascii_tokenizer>
///
/// - parameters:
/// - separators: Unless empty (the default), SQLite will consider
/// these characters as token separators.
/// - tokenCharacters: Unless empty (the default), SQLite will
/// consider these characters as token characters.
///
/// See <https://www.sqlite.org/fts5.html#ascii_tokenizer>
public static func ascii(
separators: Set<Character> = [],
tokenCharacters: Set<Character> = [])
@@ -78,17 +126,20 @@ public struct FTS5TokenizerDescriptor {
return FTS5TokenizerDescriptor(components: components)
}
/// The "porter" tokenizer
/// The "porter" tokenizer.
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .porter()
/// }
/// For example:
///
/// - parameters:
/// - base: An eventual wrapping tokenizer which replaces the
/// default unicode61() base tokenizer.
/// ```swift
/// try db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .porter()
/// }
/// ```
///
/// See <https://www.sqlite.org/fts5.html#porter_tokenizer>
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#porter_tokenizer>
///
/// - parameter base: An eventual wrapping tokenizer which replaces the
/// default unicode61() base tokenizer.
public static func porter(wrapping base: FTS5TokenizerDescriptor? = nil) -> FTS5TokenizerDescriptor {
if let base {
return FTS5TokenizerDescriptor(components: ["porter"] + base.components)
@@ -97,11 +148,17 @@ public struct FTS5TokenizerDescriptor {
}
}
/// An "unicode61" tokenizer
/// The "unicode61" tokenizer.
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .unicode61()
/// }
/// For example:
///
/// ```swift
/// try db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .unicode61()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#unicode61_tokenizer>
///
/// - parameters:
/// - diacritics: By default SQLite will strip diacritics from
@@ -112,8 +169,6 @@ public struct FTS5TokenizerDescriptor {
/// these characters as token separators.
/// - tokenCharacters: Unless empty (the default), SQLite will
/// consider these characters as token characters.
///
/// See <https://www.sqlite.org/fts5.html#unicode61_tokenizer>
public static func unicode61(
diacritics: FTS5.Diacritics = .removeLegacy,
categories: String = "",
+23 -39
View File
@@ -3,7 +3,7 @@ import Foundation
/// Flags that tell SQLite how to register a token.
///
/// See the `FTS5_TOKEN_*` flags in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
/// See the `FTS5_TOKEN_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
public struct FTS5TokenFlags: OptionSet {
public let rawValue: CInt
@@ -11,7 +11,7 @@ public struct FTS5TokenFlags: OptionSet {
self.rawValue = rawValue
}
/// FTS5_TOKEN_COLOCATED
/// `FTS5_TOKEN_COLOCATED`
public static let colocated = FTS5TokenFlags(rawValue: FTS5_TOKEN_COLOCATED)
}
@@ -20,34 +20,18 @@ public struct FTS5TokenFlags: OptionSet {
/// See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:)
public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> Void
/// The protocol for custom FTS5 tokenizers that wrap another tokenizer.
/// A type that implements a custom tokenizer for the ``FTS5`` full-text engine
/// by wrapping another tokenizer.
///
/// Types that adopt FTS5WrapperTokenizer don't have to implement the
/// low-level FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:).
/// See [FTS5 Tokenizers](https://github.com/groue/GRDB.swift/blob/master/Documentation/FTS5Tokenizers.md)
/// for more information.
///
/// Instead, they process regular Swift strings.
/// ## Topics
///
/// Here is the implementation for a trivial tokenizer that wraps the
/// built-in ascii tokenizer without any custom processing:
/// ### Tokenizing Text
///
/// class TrivialAsciiTokenizer : FTS5WrapperTokenizer {
/// static let name = "trivial"
/// let wrappedTokenizer: FTS5Tokenizer
///
/// init(db: Database, arguments: [String]) throws {
/// wrappedTokenizer = try db.makeTokenizer(.ascii())
/// }
///
/// func accept(
/// token: String,
/// flags: FTS5TokenFlags,
/// for tokenization: FTS5Tokenization,
/// tokenCallback: FTS5WrapperTokenCallback)
/// throws
/// {
/// try tokenCallback(token, flags)
/// }
/// }
/// - ``accept(token:flags:for:tokenCallback:)``
/// - ``FTS5WrapperTokenCallback``
public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer {
/// The wrapped tokenizer
var wrappedTokenizer: any FTS5Tokenizer { get }
@@ -57,16 +41,17 @@ public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer {
///
/// For example:
///
/// func accept(
/// token: String,
/// flags: FTS5TokenFlags,
/// for tokenization: FTS5Tokenization,
/// tokenCallback: FTS5WrapperTokenCallback)
/// throws
/// {
/// // pass through:
/// try tokenCallback(token, flags)
/// }
/// ```swift
/// func accept(
/// token: String,
/// flags: FTS5TokenFlags,
/// for tokenization: FTS5Tokenization,
/// tokenCallback: FTS5WrapperTokenCallback
/// ) throws {
/// // pass through:
/// try tokenCallback(token, flags)
/// }
/// ```
///
/// When implementing the accept method, there are a two rules
/// to observe:
@@ -74,8 +59,8 @@ public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer {
/// 1. Errors thrown by the tokenCallback function must not be caught.
///
/// 2. The input `flags` should be given unmodified to the tokenCallback
/// function, unless you union it with the .colocated flag when the
/// tokenizer produces synonyms (see
/// function, unless you union it with the ``FTS5TokenFlags/colocated`` flag
/// when the tokenizer produces synonyms (see
/// <https://www.sqlite.org/fts5.html#synonym_support>).
///
/// - parameters:
@@ -99,7 +84,6 @@ private struct FTS5WrapperContext {
}
extension FTS5WrapperTokenizer {
/// Default implementation
public func tokenize(
context: UnsafeMutableRawPointer?,
tokenization: FTS5Tokenization,
@@ -316,7 +316,8 @@ extension FilteredRequest {
/// - ``filter(key:)-2te6v``
/// - ``filter(keys:)-6ggt1``
/// - ``filter(keys:)-8fbn9``
/// - ``matching(_:)``
/// - ``matching(_:)-3s3zr``
/// - ``matching(_:)-7c1e8``
///
/// ### The GROUP BY and HAVING Clauses
///
@@ -1337,7 +1338,8 @@ extension JoinableRequest where Self: SelectionRequest {
/// - ``FilteredRequest/filter(literal:)``
/// - ``FilteredRequest/filter(sql:arguments:)``
/// - ``FilteredRequest/filterWhenConnected(_:)``
/// - ``TableRequest/matching(_:)``
/// - ``TableRequest/matching(_:)-3s3zr``
/// - ``TableRequest/matching(_:)-7c1e8``
/// - ``FilteredRequest/none()``
///
/// ### The GROUP BY and HAVING Clauses
+2 -1
View File
@@ -9,7 +9,8 @@
/// ### Deriving SQL Expressions
///
/// - ``detached``
/// - ``match(_:)``
/// - ``match(_:)-727nk``
/// - ``match(_:)-1vvo8``
///
/// ### Creating Column Assignments
///
+2 -1
View File
@@ -80,7 +80,8 @@ import Foundation
/// - ``joining(optional:)``
/// - ``joining(required:)``
/// - ``limit(_:offset:)``
/// - ``matching(_:)``
/// - ``matching(_:)-22m4o``
/// - ``matching(_:)-1t8ph``
/// - ``none()``
/// - ``order(_:)-9rc11``
/// - ``order(_:)-2033k``