Documentation

This commit is contained in:
Gwendal Roué committed 2016-10-11 08:52:03 +02:00
1 parent 37eab31b40
commit 26bf91e1da
7 files changed
+144 -124

No files matched your search

+59 -23
View File
@@ -70,7 +70,7 @@ It only requires a tokenization method that matches the `xTokenize` C function d
```swift
protocol FTS5Tokenizer : class {
func tokenize(context: UnsafeMutableRawPointer?, flags: FTS5TokenizationFlags, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32
}
```
@@ -83,7 +83,7 @@ let ascii = try db.makeTokenizer(.ascii()) // FTS5Tokenizer
Tokenizers can tokenize (and can produce different tokens depending on whether they are tokenizing a *document*, or a *query*):
```swift
let tokens = try ascii.tokenize("foo bar", flags: .query) // ["foo", "bar"]
let tokens = try ascii.tokenize("foo bar", for: .query) // ["foo", "bar"]
```
@@ -121,12 +121,12 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
}
```
FTS5CustomTokenizer inherits from [FTS5Tokenizer](#fts5tokenizer), and performs its tokenization job in its `tokenize(context:flags:pText:nText:tokenCallback:)` method. This low-level method matches the `xTokenize` function documented at https://www.sqlite.org/fts5.html#custom_tokenizers.
FTS5CustomTokenizer inherits from [FTS5Tokenizer](#fts5tokenizer), and performs its tokenization job in its `tokenize(context:tokenization:pText:nText:tokenCallback:)` method. This low-level method matches the `xTokenize` function documented at https://www.sqlite.org/fts5.html#custom_tokenizers.
This method arguments are:
- `context`: An opaque pointer that is the first argument to the `tokenCallback` function
- `flags`: Flags that indicate the reason why FTS5 is requesting tokenization.
- `tokenization`: The reason why FTS5 is requesting tokenization.
- `pText`: The tokenized text bytes. May or may not be nul-terminated.
- `nText`: The number of bytes in the tokenized text.
- `tokenCallback`: The function to call for each found token. It matches the `xToken` callback at https://www.sqlite.org/fts5.html#custom_tokenizers:
@@ -146,7 +146,7 @@ final class BlackHoleTokenizer : FTS5CustomTokenizer {
init(db: Database, arguments: [String]) throws {
}
func tokenize(context: UnsafeMutableRawPointer?, flags: FTS5TokenizationFlags, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32 {
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32 {
return 0 // SQLITE_OK
}
}
@@ -159,13 +159,12 @@ Since tokenization is hard, and pointers to bytes buffers uneasy to deal with, y
**FTS5WrapperTokenizer** is the high-level protocol for your custom tokenizers.
With this protocol, a custom tokenizer post-processes the tokens produced by another tokenizer, the "wrapped tokenizer", and does not have to implement the dreadful low-level `tokenize(context:flags:pText:nText:tokenCallback:)` method.
With this protocol, a custom tokenizer post-processes the tokens produced by another tokenizer, the "wrapped tokenizer", and does not have to implement the dreadful low-level `tokenize(context:tokenization:pText:nText:tokenCallback:)` method.
```swift
protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
var wrappedTokenizer: FTS5Tokenizer { get }
func customizesTokenization(flags: FTS5TokenizationFlags) -> Bool
func accept(token: String, flags: FTS5TokenFlags, tokenCallback: FTS5WrapperTokenCallback) throws
func accept(token: String, flags: FTS5TokenFlags, forTokenization tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws
}
```
@@ -190,21 +189,11 @@ final class MyTokenizer : FTS5WrapperTokenizer {
}
```
Some wrapper tokenizers sometimes want to opt-out token customization (see [Synonyms](#synonyms)). Most of them return true from their customizesTokenization method:
Wrapper tokenizers process tokens produced by their wrapped tokenizer in their `accept(token:flags:forTokenization:tokenCallback)` method. They can ignore tokens, modify tokens, and even notify several tokens to the FTS5 engine:
```swift
final class MyTokenizer : FTS5WrapperTokenizer {
func customizesTokenization(flags: FTS5TokenizationFlags) -> Bool {
return true
}
}
```
Finally, wrapper tokenizers can process tokens produced by their wrapped tokenizer. They can ignore tokens, modify tokens, and even notify several tokens to the FTS5 engine:
```swift
final class MyTokenizer : FTS5WrapperTokenizer {
func accept(token: String, flags: FTS5TokenFlags, tokenCallback: FTS5WrapperTokenCallback) throws {
func accept(token: String, flags: FTS5TokenFlags, forTokenization tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
// pass through
try tokenCallback(token, flags)
}
@@ -213,8 +202,8 @@ final class MyTokenizer : FTS5WrapperTokenizer {
When implementing the accept method, there are a two rules to observe:
- Errors thrown by `tokenCallback` must not be caught.
- The input `flags` should be given unmodified to the tokenCallback function, with one exception: [synonyms tokens](#synonyms).
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](#synonyms).
### Choosing the Wrapped Tokenizer
@@ -255,4 +244,51 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
### Synonyms
TODO
**FTS5 lets tokenizers produce synonyms**, so that, for example, "first" can match "1st".
The topic of synonyms is documented at https://www.sqlite.org/fts5.html#synonym_support, which describes several methods. You should read this, and pick the method you prefer.
In the example below, we'll pick method (3), and implement a tokenizer that adds multiple synonyms for a single term to the FTS index. Using this method, when tokenizing document text, the tokenizer provides multiple synonyms for each token. So that when a document such as "I won first place" is tokenized, entries are added to the FTS index for "i", "won", "first", "1st" and "place".
We'll also take care of the SQLite advice:
> When using methods (2) or (3), it is important that the tokenizer only provide synonyms when tokenizing document text or query text, not both. Doing so will not cause any errors, but is inefficient.
```swift
private final class SynonymsTokenizer : FTS5WrapperTokenizer {
static let name = "synonyms"
let wrappedTokenizer: FTS5Tokenizer
let synonyms: [Set<String>] = [["first", "1st"]]
init(db: Database, arguments: [String]) throws {
wrappedTokenizer = try db.makeTokenizer(.unicode61())
}
func synonyms(for token: String) -> Set<String>? {
return synonyms.first(where: { $0.contains(token) })
}
func accept(token: String, flags: FTS5TokenFlags, forTokenization tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
guard !tokenization.contains(.query) else {
// Don't look for synonyms when tokenizing queries
try tokenCallback(token, flags)
return
}
guard let synonyms = synonyms(for: token) else {
// Token has no synonym
try tokenCallback(token, flags)
return
}
for (index, synonym) in synonyms.enumerated() {
// Notify each synonym, and set the colocated flag for all but
// the first, as documented by
// https://www.sqlite.org/fts5.html#synonym_support
let synonymFlags = (index == 0) ? flags : flags.union(.colocated)
try tokenCallback(synonym, synonymFlags)
}
}
}
```
+1 -1
View File
@@ -124,7 +124,7 @@
guard let tokenizer = object as? FTS5Tokenizer else {
return SQLITE_ERROR
}
return tokenizer.tokenize(context: context, flags: FTS5TokenizationFlags(rawValue: flags), pText: pText, nText: nText, tokenCallback: tokenCallback)
return tokenizer.tokenize(context: context, tokenization: FTS5Tokenization(rawValue: flags), pText: pText, nText: nText, tokenCallback: tokenCallback)
}
var xTokenizer = fts5_tokenizer(xCreate: xCreateTokenizer, xDelete: xDeleteTokenizer, xTokenize: xTokenize)
+3 -3
View File
@@ -13,7 +13,7 @@
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingAnyTokenIn string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).tokenize(string, flags: .query) }) else { return nil }
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).tokenize(string, for: .query) }) else { return nil }
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " OR "))
}
@@ -26,7 +26,7 @@
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingAllTokensIn string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).tokenize(string, flags: .query) }) else { return nil }
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).tokenize(string, for: .query) }) else { return nil }
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " "))
}
@@ -39,7 +39,7 @@
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingPhrase string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).tokenize(string, flags: .query) }) else { return nil }
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).tokenize(string, for: .query) }) else { return nil }
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
+14 -15
View File
@@ -4,10 +4,10 @@
/// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:)
public typealias FTS5TokenCallback = @convention(c) (_ context: UnsafeMutableRawPointer?, _ flags: Int32, _ pToken: UnsafePointer<Int8>?, _ nToken: Int32, _ iStart: Int32, _ iEnd: Int32) -> Int32
/// Flags that indicate the reason why FTS5 is requesting tokenization.
/// The reason why FTS5 is requesting tokenization.
///
/// See https://www.sqlite.org/fts5.html#custom_tokenizers
public struct FTS5TokenizationFlags : OptionSet {
public struct FTS5Tokenization : OptionSet {
public let rawValue: Int32
public init(rawValue: Int32) {
@@ -15,16 +15,16 @@
}
/// FTS5_TOKENIZE_QUERY
public static let query = FTS5TokenizationFlags(rawValue: FTS5_TOKENIZE_QUERY)
public static let query = FTS5Tokenization(rawValue: FTS5_TOKENIZE_QUERY)
/// FTS5_TOKENIZE_PREFIX
public static let prefix = FTS5TokenizationFlags(rawValue: FTS5_TOKENIZE_PREFIX)
public static let prefix = FTS5Tokenization(rawValue: FTS5_TOKENIZE_PREFIX)
/// FTS5_TOKENIZE_DOCUMENT
public static let document = FTS5TokenizationFlags(rawValue: FTS5_TOKENIZE_DOCUMENT)
public static let document = FTS5Tokenization(rawValue: FTS5_TOKENIZE_DOCUMENT)
/// FTS5_TOKENIZE_AUX
public static let aux = FTS5TokenizationFlags(rawValue: FTS5_TOKENIZE_AUX)
public static let aux = FTS5Tokenization(rawValue: FTS5_TOKENIZE_AUX)
}
/// The protocol for FTS5 tokenizers
@@ -37,14 +37,13 @@
/// - parameters:
/// - context: An opaque pointer that is the first argument to
/// the `tokenCallback` function
/// - flags: Flags that indicate the reason why FTS5 is
/// requesting tokenization.
/// - tokenization: The reason why FTS5 is requesting tokenization.
/// - pText: The tokenized text bytes. May or may not be
/// nul-terminated.
/// - nText: The number of bytes in the tokenized text.
/// - tokenCallback: The function to call for each found token.
/// It matches the `xToken` callback at https://www.sqlite.org/fts5.html#custom_tokenizers
func tokenize(context: UnsafeMutableRawPointer?, flags: FTS5TokenizationFlags, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32
}
extension FTS5Tokenizer {
@@ -52,14 +51,14 @@
/// Returns an array of tokens found in the string argument.
///
/// let tokenizer = try db.makeTokenizer(.ascii())
/// try tokenizer.tokenize("foo bar", flags: .document) // ["foo", "bar"]
/// try tokenizer.tokenize("foo bar", for: .document) // ["foo", "bar"]
///
/// - parameter string: The string to tokenize
/// - parameter flags: Tokenization flags
/// - parameter tokenization: The reason why tokenization is requested:
/// - .document: Tokenize like a document being inserted into an FTS table.
/// - .query: Tokenize like the search pattern of the MATCH operator.
/// - parameter tokenizer: A FTS5TokenizerDescriptor such as .ascii()
public func tokenize(_ string: String, flags: FTS5TokenizationFlags) throws -> [String] {
public func tokenize(_ string: String, for tokenization: FTS5Tokenization) throws -> [String] {
return try ContiguousArray(string.utf8).withUnsafeBufferPointer { buffer -> [String] in
guard let addr = buffer.baseAddress else {
return []
@@ -69,7 +68,7 @@
var context = TokenizeContext()
try withUnsafeMutablePointer(to: &context) { contextPointer in
let code = tokenize(context: UnsafeMutableRawPointer(contextPointer), flags: flags, pText: pText, nText: nText, tokenCallback: { (contextPointer, flags, pToken, nToken, iStart, iEnd) -> Int32 in
let code = tokenize(context: UnsafeMutableRawPointer(contextPointer), tokenization: tokenization, pText: pText, nText: nText, tokenCallback: { (contextPointer, flags, pToken, nToken, iStart, iEnd) -> Int32 in
guard let contextPointer = contextPointer else { return SQLITE_ERROR }
// Extract token
@@ -150,11 +149,11 @@
}
}
func tokenize(context: UnsafeMutableRawPointer?, flags: FTS5TokenizationFlags, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32 {
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32 {
guard let xTokenize = xTokenizer.xTokenize else {
return SQLITE_ERROR
}
return xTokenize(tokenizerPointer, context, flags.rawValue, pText, nText, tokenCallback)
return xTokenize(tokenizerPointer, context, tokenization.rawValue, pText, nText, tokenCallback)
}
}
+38 -47
View File
@@ -36,11 +36,7 @@
/// wrappedTokenizer = try db.makeTokenizer(.ascii())
/// }
///
/// func customizesTokenization(flags: FTS5TokenizationFlags) -> Bool {
/// return true
/// }
///
/// func accept(token: String, flags: FTS5TokenFlags, tokenCallback: FTS5WrapperTokenCallback) throws {
/// func accept(token: String, flags: FTS5TokenFlags, forTokenization tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
/// try tokenCallback(token, flags)
/// }
/// }
@@ -48,64 +44,54 @@
/// The wrapped tokenizer
var wrappedTokenizer: FTS5Tokenizer { get }
/// Returns whether the tokens emitted by the wrapped tokenizer should
/// be processed by `accept(token:flags:tokenCallback:)`.
///
/// - parameter flags: Flags that indicate the reason why FTS5 is
/// requesting tokenization.
func customizesTokenization(flags: FTS5TokenizationFlags) -> Bool
/// Given a token produced by the wrapped tokenizer, notifies customized
/// tokens to the `tokenCallback` function.
///
/// For example:
///
/// func accept(token: String, flags: FTS5TokenFlags, tokenCallback: FTS5WrapperTokenCallback) throws {
/// func accept(token: String, flags: FTS5TokenFlags, forTokenization tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
/// // pass through:
/// try tokenCallback(token, flags)
/// }
///
/// Errors thrown by `tokenCallback` must not be caught.
/// When implementing the accept method, there are a two rules
/// to observe:
///
/// Union `flags` with `.colocated` when your tokenizer produces synonyms
/// (see https://www.sqlite.org/fts5.html#synonym_support):
/// 1. Errors thrown by the tokenCallback function must not be caught.
///
/// func accept(token: String, flags: FTS5TokenFlags, tokenCallback: FTS5WrapperTokenCallback) throws {
/// if token = "first" {
/// tokenCallback("first", flags)
/// tokenCallback("1st", flags.union(.colocated))
/// } else {
/// tokenCallback(token, flags)
/// }
/// }
/// 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
/// https://www.sqlite.org/fts5.html#synonym_support).
///
/// - parameters:
/// - token: A token produced by the wrapped tokenizer
/// - flags: Flags that tell SQLite how to register a token.
/// - tokenization: The reason why FTS5 is requesting tokenization.
/// - tokenCallback: The function to call for each customized token.
func accept(token: String, flags: FTS5TokenFlags, tokenCallback: FTS5WrapperTokenCallback) throws
func accept(token: String, flags: FTS5TokenFlags, forTokenization tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws
}
private struct FTS5WrapperContext {
let tokenizer: FTS5WrapperTokenizer
let context: UnsafeMutableRawPointer?
let tokenization: FTS5Tokenization
let tokenCallback: FTS5TokenCallback
}
extension FTS5WrapperTokenizer {
/// Default implementation
public func tokenize(context: UnsafeMutableRawPointer?, flags: FTS5TokenizationFlags, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32 {
// Let wrappedTokenizer do the job unless we customize
guard customizesTokenization(flags: flags) else {
return wrappedTokenizer.tokenize(context: context, flags: flags, pText: pText, nText: nText, tokenCallback: tokenCallback)
}
public func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32 {
// `tokenCallback` is @convention(c). This requires a little setup
// in order to transfer context.
var customContext = FTS5WrapperContext(tokenizer: self, context: context, tokenCallback: tokenCallback!)
var customContext = FTS5WrapperContext(
tokenizer: self,
context: context,
tokenization: tokenization,
tokenCallback: tokenCallback!)
return withUnsafeMutablePointer(to: &customContext) { customContextPointer in
// Invoke wrappedTokenizer
return wrappedTokenizer.tokenize(context: customContextPointer, flags: flags, pText: pText, nText: nText) { (customContextPointer, flags, pToken, nToken, iStart, iEnd) in
return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in
// Extract token produced by wrapped tokenizer
guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else {
@@ -116,25 +102,30 @@
let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee
let tokenizer = customContext.tokenizer
let context = customContext.context
let tokenization = customContext.tokenization
let tokenCallback = customContext.tokenCallback
// Process token produced by wrapped tokenizer
do {
try tokenizer.accept(token: token, flags: FTS5TokenFlags(rawValue: flags), tokenCallback: { (token, flags) in
// Turn token into bytes
return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in
guard let addr = buffer.baseAddress else {
return
try tokenizer.accept(
token: token,
flags: FTS5TokenFlags(rawValue: tokenFlags),
forTokenization: tokenization,
tokenCallback: { (token, flags) in
// Turn token into bytes
return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in
guard let addr = buffer.baseAddress else {
return
}
let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self)
let nToken = Int32(buffer.count)
// Inject token bytes into SQLite
let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd)
guard code == SQLITE_OK else {
throw DatabaseError(code: code, message: "token callback failed")
}
}
let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self)
let nToken = Int32(buffer.count)
// Inject token into SQLite
let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd)
guard code == SQLITE_OK else {
throw DatabaseError(code: code, message: "token consumer failed")
}
}
})
return SQLITE_OK
@@ -28,7 +28,7 @@ private final class StopWordsTokenizer : FTS5CustomTokenizer {
// TODO: test that deinit is called
}
func tokenize(context: UnsafeMutableRawPointer?, flags: FTS5TokenizationFlags, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32 {
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32 {
// The way we implement stop words is by letting wrappedTokenizer do its
// job but intercepting its tokens before they feed SQLite.
@@ -43,7 +43,7 @@ private final class StopWordsTokenizer : FTS5CustomTokenizer {
var customContext = CustomContext(ignoredTokens: ignoredTokens, context: context!, tokenCallback: tokenCallback!)
return withUnsafeMutablePointer(to: &customContext) { customContextPointer in
// Invoke wrappedTokenizer, but intercept raw tokens
return wrappedTokenizer.tokenize(context: customContextPointer, flags: flags, pText: pText, nText: nText) { (customContextPointer, flags, pToken, nToken, iStart, iEnd) in
return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, flags, pToken, nToken, iStart, iEnd) in
// Extract context
let customContext = customContextPointer!.assumingMemoryBound(to: CustomContext.self).pointee
@@ -81,7 +81,7 @@ private final class NFKCTokenizer : FTS5CustomTokenizer {
// TODO: test that deinit is called
}
func tokenize(context: UnsafeMutableRawPointer?, flags: FTS5TokenizationFlags, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32 {
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32 {
// The way we implement NFKC conversion is by letting wrappedTokenizer
// do its job, but intercepting its tokens before they feed SQLite.
@@ -95,7 +95,7 @@ private final class NFKCTokenizer : FTS5CustomTokenizer {
var customContext = CustomContext(context: context!, tokenCallback: tokenCallback!)
return withUnsafeMutablePointer(to: &customContext) { customContextPointer in
// Invoke wrappedTokenizer, but intercept raw tokens
return wrappedTokenizer.tokenize(context: customContextPointer, flags: flags, pText: pText, nText: nText) { (customContextPointer, flags, pToken, nToken, iStart, iEnd) in
return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, flags, pToken, nToken, iStart, iEnd) in
// Extract context
let customContext = customContextPointer!.assumingMemoryBound(to: CustomContext.self).pointee
@@ -140,11 +140,11 @@ private final class SynonymsTokenizer : FTS5CustomTokenizer {
// TODO: test that deinit is called
}
func tokenize(context: UnsafeMutableRawPointer?, flags: FTS5TokenizationFlags, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32 {
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: FTS5TokenCallback?) -> Int32 {
// Don't look for synonyms when tokenizing queries, as advised by
// https://www.sqlite.org/fts5.html#synonym_support
if flags.contains(.query) {
return wrappedTokenizer.tokenize(context: context, flags: flags, pText: pText, nText: nText, tokenCallback: tokenCallback)
if tokenization.contains(.query) {
return wrappedTokenizer.tokenize(context: context, tokenization: tokenization, pText: pText, nText: nText, tokenCallback: tokenCallback)
}
// The way we implement synonyms support is by letting wrappedTokenizer
@@ -161,7 +161,7 @@ private final class SynonymsTokenizer : FTS5CustomTokenizer {
return withUnsafeMutablePointer(to: &customContext) { customContextPointer in
// Invoke wrappedTokenizer, but intercept raw tokens
return wrappedTokenizer.tokenize(context: customContextPointer, flags: flags, pText: pText, nText: nText) { (customContextPointer, flags, pToken, nToken, iStart, iEnd) in
return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, flags, pToken, nToken, iStart, iEnd) in
// Extract context
let customContext = customContextPointer!.assumingMemoryBound(to: CustomContext.self).pointee
@@ -25,11 +25,7 @@ private final class StopWordsTokenizer : FTS5WrapperTokenizer {
return token == "bar"
}
func customizesTokenization(flags: FTS5TokenizationFlags) -> Bool {
return true
}
func accept(token: String, flags: FTS5TokenFlags, tokenCallback: FTS5WrapperTokenCallback) throws {
func accept(token: String, flags: FTS5TokenFlags, forTokenization tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
// Notify token unless ignored
if !ignores(token){
try tokenCallback(token, flags)
@@ -50,11 +46,7 @@ private final class NFKCTokenizer : FTS5WrapperTokenizer {
}
}
func customizesTokenization(flags: FTS5TokenizationFlags) -> Bool {
return true
}
func accept(token: String, flags: FTS5TokenFlags, tokenCallback: FTS5WrapperTokenCallback) throws {
func accept(token: String, flags: FTS5TokenFlags, forTokenization tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
// Convert token to NFKC
try tokenCallback(token.precomposedStringWithCompatibilityMapping, flags)
}
@@ -64,6 +56,7 @@ private final class NFKCTokenizer : FTS5WrapperTokenizer {
private final class SynonymsTokenizer : FTS5WrapperTokenizer {
static let name = "synonyms"
let wrappedTokenizer: FTS5Tokenizer
let synonyms: [Set<String>] = [["first", "1st"]]
init(db: Database, arguments: [String]) throws {
if arguments.isEmpty {
@@ -74,28 +67,29 @@ private final class SynonymsTokenizer : FTS5WrapperTokenizer {
}
func synonyms(for token: String) -> Set<String>? {
let synonyms: [Set<String>] = [["first", "1st"]]
return synonyms.first(where: { $0.contains(token) })
}
func customizesTokenization(flags: FTS5TokenizationFlags) -> Bool {
// Don't look for synonyms when tokenizing queries, as advised by
// https://www.sqlite.org/fts5.html#synonym_support
return !flags.contains(.query)
}
func accept(token: String, flags: FTS5TokenFlags, tokenCallback: FTS5WrapperTokenCallback) throws {
if let synonyms = synonyms(for: token) {
for (index, synonym) in synonyms.enumerated() {
// Notify each synonym, and set the colocated flag for all but
// the first, as documented by
// https://www.sqlite.org/fts5.html#synonym_support
let synonymFlags = (index == 0) ? flags : flags.union(.colocated)
try tokenCallback(synonym, synonymFlags)
}
} else {
func accept(token: String, flags: FTS5TokenFlags, forTokenization tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
guard !tokenization.contains(.query) else {
// Don't look for synonyms when tokenizing queries, as advised by
// https://www.sqlite.org/fts5.html#synonym_support
try tokenCallback(token, flags)
return
}
guard let synonyms = synonyms(for: token) else {
// Token has no synonym
try tokenCallback(token, flags)
return
}
for (index, synonym) in synonyms.enumerated() {
// Notify each synonym, and set the colocated flag for all but
// the first, as documented by
// https://www.sqlite.org/fts5.html#synonym_support
let synonymFlags = (index == 0) ? flags : flags.union(.colocated)
try tokenCallback(synonym, synonymFlags)
}
}
}