-
-
Notifications
You must be signed in to change notification settings - Fork 745
/
Copy pathFTS5Tokenizer.swift
325 lines (292 loc) · 12 KB
/
FTS5Tokenizer.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import Foundation
/// A low-level SQLite function that lets FTS5Tokenizer notify tokens.
///
/// See ``FTS5Tokenizer/tokenize(context:tokenization:pText:nText:tokenCallback:)``.
public typealias FTS5TokenCallback = @convention(c) (
_ context: UnsafeMutableRawPointer?,
_ flags: CInt,
_ pToken: UnsafePointer<CChar>?,
_ nToken: CInt,
_ iStart: CInt,
_ iEnd: CInt)
-> CInt
/// The reason why FTS5 is requesting tokenization.
///
/// See the `FTS5_TOKENIZE_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
public struct FTS5Tokenization: OptionSet, Sendable {
public let rawValue: CInt
public init(rawValue: CInt) {
self.rawValue = rawValue
}
/// `FTS5_TOKENIZE_QUERY`
public static let query = FTS5Tokenization(rawValue: FTS5_TOKENIZE_QUERY)
/// `FTS5_TOKENIZE_PREFIX`
public static let prefix = FTS5Tokenization(rawValue: FTS5_TOKENIZE_PREFIX)
/// `FTS5_TOKENIZE_DOCUMENT`
public static let document = FTS5Tokenization(rawValue: FTS5_TOKENIZE_DOCUMENT)
/// `FTS5_TOKENIZE_AUX`
public static let aux = FTS5Tokenization(rawValue: FTS5_TOKENIZE_AUX)
}
/// 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.
///
/// It matches the `xTokenize` function documented at <https://www.sqlite.org/fts5.html#custom_tokenizers>
///
/// - parameters:
/// - context: An opaque pointer that is the first argument to
/// the `tokenCallback` function
/// - 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?,
tokenization: FTS5Tokenization,
pText: UnsafePointer<CChar>?,
nText: CInt,
tokenCallback: @escaping FTS5TokenCallback)
-> CInt
}
private class TokenizeContext {
var tokens: [(String, FTS5TokenFlags)] = []
}
extension FTS5Tokenizer {
/// Tokenizes the string argument as a document that would be inserted into
/// an FTS5 table.
///
/// For example:
///
/// ```swift
/// let tokenizer = try db.makeTokenizer(.ascii())
/// try tokenizer.tokenize(document: "foo bar") // [("foo", flags), ("bar", flags)]
/// ```
///
/// See also `tokenize(query:)`.
///
/// - parameter string: The string to tokenize.
/// - returns: An array of tokens and flags.
/// - throws: An error if tokenization fails.
public func tokenize(document string: String) throws -> [(token: String, flags: FTS5TokenFlags)] {
try tokenize(string, for: .document)
}
/// Tokenizes the string argument as an FTS5 query.
///
/// For example:
///
/// ```swift
/// let tokenizer = try db.makeTokenizer(.ascii())
/// try tokenizer.tokenize(query: "foo bar") // [("foo", flags), ("bar", flags)]
/// ```
///
/// See also `tokenize(document:)`.
///
/// - parameter string: The string to tokenize.
/// - returns: An array of tokens and flags.
/// - throws: An error if tokenization fails.
public func tokenize(query string: String) throws -> [(token: String, flags: FTS5TokenFlags)] {
try tokenize(string, for: .query)
}
/// Tokenizes the string argument.
///
/// let tokenizer = try db.makeTokenizer(.ascii())
/// try tokenizer.tokenize("foo bar", for: .document) // [("foo", flags), ("bar", flags)]
///
/// - parameter string: The string to tokenize
/// - 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()
private func tokenize(_ string: String, for tokenization: FTS5Tokenization)
throws -> [(token: String, flags: FTS5TokenFlags)]
{
try string.utf8CString.withUnsafeBufferPointer { buffer -> [(String, FTS5TokenFlags)] in
guard let addr = buffer.baseAddress else {
return []
}
let pText = addr
let nText = CInt(buffer.count)
var context = TokenizeContext()
try withUnsafeMutablePointer(to: &context) { contextPointer in
let code = tokenize(
context: UnsafeMutableRawPointer(contextPointer),
tokenization: tokenization,
pText: pText,
nText: nText,
tokenCallback: { (contextPointer, flags, pToken, nToken, _ /* iStart */, _ /* iEnd */) in
guard let contextPointer else {
return SQLITE_ERROR
}
// Extract token
guard let token = pToken.flatMap({ String(
data: Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: $0),
count: Int(nToken),
deallocator: .none),
encoding: .utf8) })
else {
return SQLITE_OK
}
let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee
context.tokens.append((token, FTS5TokenFlags(rawValue: flags)))
return SQLITE_OK
})
if code != SQLITE_OK {
throw DatabaseError(resultCode: code)
}
}
return context.tokens
}
}
}
extension Database {
// MARK: - FTS5
/// Private type that makes a pre-registered FTS5 tokenizer available
/// through the FTS5Tokenizer protocol.
private final class FTS5RegisteredTokenizer: FTS5Tokenizer {
let xTokenizer: fts5_tokenizer
let tokenizerPointer: OpaquePointer
init(xTokenizer: fts5_tokenizer, contextPointer: UnsafeMutableRawPointer?, arguments: [String]) throws {
guard let xCreate = xTokenizer.xCreate else {
throw DatabaseError(message: "nil fts5_tokenizer.xCreate")
}
self.xTokenizer = xTokenizer
var tokenizerPointer: OpaquePointer? = nil
let code: CInt
if arguments.isEmpty {
code = xCreate(contextPointer, nil, 0, &tokenizerPointer)
} else {
func withArrayOfCStrings<Result>(
_ input: [String],
_ output: inout ContiguousArray<UnsafePointer<CChar>>,
_ accessor: (ContiguousArray<UnsafePointer<CChar>>) -> Result)
-> Result
{
if output.count == input.count {
return accessor(output)
} else {
return input[output.count].withCString { (cString) -> Result in
output.append(cString)
return withArrayOfCStrings(input, &output, accessor)
}
}
}
var cStrings = ContiguousArray<UnsafePointer<CChar>>()
cStrings.reserveCapacity(arguments.count)
code = withArrayOfCStrings(arguments, &cStrings) { (cStrings) in
cStrings.withUnsafeBufferPointer { azArg in
xCreate(
contextPointer,
UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)),
CInt(cStrings.count),
&tokenizerPointer)
}
}
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: "failed fts5_tokenizer.xCreate")
}
if let tokenizerPointer {
self.tokenizerPointer = tokenizerPointer
} else {
throw DatabaseError(resultCode: code, message: "nil tokenizer")
}
}
deinit {
if let delete = xTokenizer.xDelete {
delete(tokenizerPointer)
}
}
func tokenize(
context: UnsafeMutableRawPointer?,
tokenization: FTS5Tokenization,
pText: UnsafePointer<CChar>?,
nText: CInt,
tokenCallback: @escaping FTS5TokenCallback)
-> CInt
{
guard let xTokenize = xTokenizer.xTokenize else {
return SQLITE_ERROR
}
return xTokenize(tokenizerPointer, context, tokenization.rawValue, pText, nText, tokenCallback)
}
}
/// Creates an FTS5 tokenizer, given its descriptor.
///
/// 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.
public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> any FTS5Tokenizer {
let api = FTS5.api(self)
let xTokenizerPointer: UnsafeMutablePointer<fts5_tokenizer> = .allocate(capacity: 1)
defer { xTokenizerPointer.deallocate() }
let contextHandle: UnsafeMutablePointer<UnsafeMutableRawPointer?> = .allocate(capacity: 1)
defer { contextHandle.deallocate() }
let code = api.pointee.xFindTokenizer!(
UnsafeMutablePointer(mutating: api),
descriptor.name,
contextHandle,
xTokenizerPointer)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code)
}
let contextPointer = contextHandle.pointee
return try FTS5RegisteredTokenizer(
xTokenizer: xTokenizerPointer.pointee,
contextPointer: contextPointer,
arguments: descriptor.arguments)
}
}
#endif