diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 1f3096ae0..871c4ac41 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -1,5 +1,16 @@ #if SQLITE_ENABLE_FTS5 - /// FTS5 lets you define "fts5" virtual tables. +/// FTS5 lets you define "fts5" virtual tables. +/// +/// // CREATE VIRTUAL TABLE document USING fts5(content) +/// try db.create(virtualTable: "document", using: FTS5()) { t in +/// t.column("content") +/// } +/// +/// See https://www.sqlite.org/fts5.html +public struct FTS5 : VirtualTableModule { + + /// Creates a FTS5 module suitable for the Database + /// `create(virtualTable:using:)` method. /// /// // CREATE VIRTUAL TABLE document USING fts5(content) /// try db.create(virtualTable: "document", using: FTS5()) { t in @@ -7,375 +18,364 @@ /// } /// /// See https://www.sqlite.org/fts5.html - public struct FTS5 : VirtualTableModule { + public init() { + } + + // MARK: - VirtualTableModule Adoption + + /// The virtual table module name + public let moduleName = "fts5" + + /// Don't use this method. + public func makeTableDefinition() -> FTS5TableDefinition { + return FTS5TableDefinition() + } + + /// Don't use this method. + public func moduleArguments(for definition: FTS5TableDefinition, in db: Database) throws -> [String] { + var arguments: [String] = [] - /// Creates a FTS5 module suitable for the Database - /// `create(virtualTable:using:)` method. - /// - /// // CREATE VIRTUAL TABLE document USING fts5(content) - /// try db.create(virtualTable: "document", using: FTS5()) { t in - /// t.column("content") - /// } - /// - /// See https://www.sqlite.org/fts5.html - public init() { + if definition.columns.isEmpty { + // Programmer error + fatalError("FTS5 virtual table requires at least one column.") } - // MARK: - VirtualTableModule Adoption - - /// The virtual table module name - public let moduleName = "fts5" - - /// Don't use this method. - public func makeTableDefinition() -> FTS5TableDefinition { - return FTS5TableDefinition() - } - - /// Don't use this method. - public func moduleArguments(for definition: FTS5TableDefinition, in db: Database) throws -> [String] { - var arguments: [String] = [] - - if definition.columns.isEmpty { - // Programmer error - fatalError("FTS5 virtual table requires at least one column.") - } - - for column in definition.columns { - if column.isIndexed { - arguments.append("\(column.name)") - } else { - arguments.append("\(column.name) UNINDEXED") - } - } - - if let tokenizer = definition.tokenizer { - arguments.append("tokenize=\(tokenizer.components.joined(separator: " ").sqlExpression.quotedSQL())") - } - - switch definition.contentMode { - case .raw(let content, let contentRowID): - if let content = content { - arguments.append("content=\(content.sqlExpression.quotedSQL())") - } - if let contentRowID = contentRowID { - arguments.append("content_rowid=\(contentRowID.sqlExpression.quotedSQL())") - } - case .synchronized(let contentTable): - arguments.append("content=\(contentTable.sqlExpression.quotedSQL())") - if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn { - arguments.append("content_rowid=\(rowIDColumn.sqlExpression.quotedSQL())") - } - } - - - if let prefixes = definition.prefixes { - arguments.append("prefix=\(prefixes.sorted().map { "\($0)" }.joined(separator: " ").sqlExpression.quotedSQL())") - } - - if let columnSize = definition.columnSize { - arguments.append("columnSize=\(columnSize)") - } - - if let detail = definition.detail { - arguments.append("detail=\(detail)") - } - - return arguments - } - - /// Reserved; part of the VirtualTableModule protocol. - /// - /// See Database.create(virtualTable:using:) - public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws { - switch definition.contentMode { - case .raw: - break - case .synchronized(let contentTable): - // https://sqlite.org/fts5.html#external_content_tables - - let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name - let ftsTable = tableName.quotedDatabaseIdentifier - let content = contentTable.quotedDatabaseIdentifier - let indexedColumns = definition.columns.map { $0.name } - - let ftsColumns = (["rowid"] + indexedColumns) - .map { $0.quotedDatabaseIdentifier } - .joined(separator: ", ") - - let newContentColumns = ([rowIDColumn] + indexedColumns) - .map { "new.\($0.quotedDatabaseIdentifier)" } - .joined(separator: ", ") - - let oldContentColumns = ([rowIDColumn] + indexedColumns) - .map { "old.\($0.quotedDatabaseIdentifier)" } - .joined(separator: ", ") - - try db.execute(sql: """ - CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); - END; - CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); - END; - CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN - INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); - INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); - END; - """) - - // https://sqlite.org/fts5.html#the_rebuild_command - - try db.execute(sql: "INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')") - } - } - - static func api(_ db: Database) -> UnsafePointer { - // 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. - // - // Do we use SQLite 3.19.3 (iOS 11.4), or SQLite 3.24.0 (iOS 12.0)? - if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) { - // SQLite 3.24.0 or more - return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer) + for column in definition.columns { + if column.isIndexed { + arguments.append("\(column.name)") } else { - // SQLite 3.19.3 or less - return api_v1(db) + arguments.append("\(column.name) UNINDEXED") } - #endif } - private static func api_v1(_ db: Database) -> UnsafePointer { - guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else { - fatalError("FTS5 is not available") - } - #if swift(>=5.0) - return data.withUnsafeBytes { - $0.bindMemory(to: UnsafePointer.self).first! - } - #else - return data.withUnsafeBytes { - $0.pointee - } - #endif + if let tokenizer = definition.tokenizer { + arguments.append("tokenize=\(tokenizer.components.joined(separator: " ").sqlExpression.quotedSQL())") } - // 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, - _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer?, Int32, UInt32, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> Int32, - _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32) - -> UnsafePointer - { - let sqliteConnection = db.sqliteConnection - var statement: SQLiteStatement? = nil - var api: UnsafePointer? = nil - let type: StaticString = "fts5_api_ptr" + switch definition.contentMode { + case .raw(let content, let contentRowID): + if let content = content { + arguments.append("content=\(content.sqlExpression.quotedSQL())") + } + if let contentRowID = contentRowID { + arguments.append("content_rowid=\(contentRowID.sqlExpression.quotedSQL())") + } + case .synchronized(let contentTable): + arguments.append("content=\(contentTable.sqlExpression.quotedSQL())") + if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn { + arguments.append("content_rowid=\(rowIDColumn.sqlExpression.quotedSQL())") + } + } + + + if let prefixes = definition.prefixes { + arguments.append("prefix=\(prefixes.sorted().map { "\($0)" }.joined(separator: " ").sqlExpression.quotedSQL())") + } + + if let columnSize = definition.columnSize { + arguments.append("columnSize=\(columnSize)") + } + + if let detail = definition.detail { + arguments.append("detail=\(detail)") + } + + return arguments + } + + /// Reserved; part of the VirtualTableModule protocol. + /// + /// See Database.create(virtualTable:using:) + public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws { + switch definition.contentMode { + case .raw: + break + case .synchronized(let contentTable): + // https://sqlite.org/fts5.html#external_content_tables - 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 result = api else { - fatalError("FTS5 is not available") - } - return result + let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name + let ftsTable = tableName.quotedDatabaseIdentifier + let content = contentTable.quotedDatabaseIdentifier + let indexedColumns = definition.columns.map { $0.name } + + let ftsColumns = (["rowid"] + indexedColumns) + .map { $0.quotedDatabaseIdentifier } + .joined(separator: ", ") + + let newContentColumns = ([rowIDColumn] + indexedColumns) + .map { "new.\($0.quotedDatabaseIdentifier)" } + .joined(separator: ", ") + + let oldContentColumns = ([rowIDColumn] + indexedColumns) + .map { "old.\($0.quotedDatabaseIdentifier)" } + .joined(separator: ", ") + + try db.execute(sql: """ + CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN + INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); + END; + CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN + INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); + END; + CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN + INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns)); + INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns)); + END; + """) + + // https://sqlite.org/fts5.html#the_rebuild_command + + try db.execute(sql: "INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')") } } - /// The FTS5TableDefinition class lets you define columns of a FTS5 virtual table. + static func api(_ db: Database) -> UnsafePointer { + // 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. + // + // Do we use SQLite 3.19.3 (iOS 11.4), or SQLite 3.24.0 (iOS 12.0)? + if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) { + // SQLite 3.24.0 or more + return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer) + } else { + // SQLite 3.19.3 or less + return api_v1(db) + } + #endif + } + + private static func api_v1(_ db: Database) -> UnsafePointer { + guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else { + fatalError("FTS5 is not available") + } + #if swift(>=5.0) + return data.withUnsafeBytes { + $0.bindMemory(to: UnsafePointer.self).first! + } + #else + return data.withUnsafeBytes { + $0.pointee + } + #endif + } + + // 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, + _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer?, Int32, UInt32, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> Int32, + _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32) + -> UnsafePointer + { + let sqliteConnection = db.sqliteConnection + var statement: SQLiteStatement? = nil + var api: UnsafePointer? = 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 result = api else { + fatalError("FTS5 is not available") + } + return result + } +} + +/// The FTS5TableDefinition class lets you define columns of a FTS5 virtual table. +/// +/// You don't create instances of this class. Instead, you use the Database +/// `create(virtualTable:using:)` method: +/// +/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition +/// t.column("content") +/// } +/// +/// See https://www.sqlite.org/fts5.html +public final class FTS5TableDefinition { + enum ContentMode { + case raw(content: String?, contentRowID: String?) + case synchronized(contentTable: String) + } + + fileprivate var columns: [FTS5ColumnDefinition] = [] + fileprivate var contentMode: ContentMode = .raw(content: nil, contentRowID: nil) + + /// The virtual table tokenizer /// - /// You don't create instances of this class. Instead, you use the Database - /// `create(virtualTable:using:)` method: + /// try db.create(virtualTable: "document", using: FTS5()) { t in + /// t.tokenizer = .porter() + /// } /// - /// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition + /// See https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization + public var tokenizer: FTS5TokenizerDescriptor? + + /// 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. + /// + /// Setting this property invalidates any synchronization previously + /// established with the `synchronize(withTable:)` method. + /// + /// See https://www.sqlite.org/fts5.html#external_content_and_contentless_tables + public var content: String? { + get { + switch contentMode { + case .raw(let content, _): + return content + case .synchronized(let contentTable): + return contentTable + } + } + set { + switch contentMode { + case .raw(_, let contentRowID): + contentMode = .raw(content: newValue, contentRowID: contentRowID) + case .synchronized: + contentMode = .raw(content: newValue, contentRowID: nil) + } + } + } + + /// 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. + /// + /// Setting this property invalidates any synchronization previously + /// established with the `synchronize(withTable:)` method. + /// + /// See https://sqlite.org/fts5.html#external_content_tables + public var contentRowID: String? { + get { + switch contentMode { + case .raw(_, let contentRowID): + return contentRowID + case .synchronized: + return nil + } + } + set { + switch contentMode { + case .raw(let content, _): + contentMode = .raw(content: content, contentRowID: newValue) + case .synchronized: + contentMode = .raw(content: nil, contentRowID: newValue) + } + } + } + + /// Support for the FTS5 `prefix` option + /// + /// See https://www.sqlite.org/fts5.html#prefix_indexes + public var prefixes: Set? + + /// Support for the FTS5 `columnsize` option + /// + /// https://www.sqlite.org/fts5.html#the_columnsize_option + public var columnSize: Int? + + /// Support for the FTS5 `detail` option + /// + /// https://www.sqlite.org/fts5.html#the_detail_option + public var detail: String? + + /// Appends a table column. + /// + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// - /// See https://www.sqlite.org/fts5.html - public final class FTS5TableDefinition { - enum ContentMode { - case raw(content: String?, contentRowID: String?) - case synchronized(contentTable: String) - } - - fileprivate var columns: [FTS5ColumnDefinition] = [] - fileprivate var contentMode: ContentMode = .raw(content: nil, contentRowID: nil) - - /// The virtual table tokenizer - /// - /// try db.create(virtualTable: "document", using: FTS5()) { t in - /// t.tokenizer = .porter() - /// } - /// - /// See https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization - public var tokenizer: FTS5TokenizerDescriptor? - - /// 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. - /// - /// Setting this property invalidates any synchronization previously - /// established with the `synchronize(withTable:)` method. - /// - /// See https://www.sqlite.org/fts5.html#external_content_and_contentless_tables - public var content: String? { - get { - switch contentMode { - case .raw(let content, _): - return content - case .synchronized(let contentTable): - return contentTable - } - } - set { - switch contentMode { - case .raw(_, let contentRowID): - contentMode = .raw(content: newValue, contentRowID: contentRowID) - case .synchronized: - contentMode = .raw(content: newValue, contentRowID: nil) - } - } - } - - /// 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. - /// - /// Setting this property invalidates any synchronization previously - /// established with the `synchronize(withTable:)` method. - /// - /// See https://sqlite.org/fts5.html#external_content_tables - public var contentRowID: String? { - get { - switch contentMode { - case .raw(_, let contentRowID): - return contentRowID - case .synchronized: - return nil - } - } - set { - switch contentMode { - case .raw(let content, _): - contentMode = .raw(content: content, contentRowID: newValue) - case .synchronized: - contentMode = .raw(content: nil, contentRowID: newValue) - } - } - } - - /// Support for the FTS5 `prefix` option - /// - /// See https://www.sqlite.org/fts5.html#prefix_indexes - public var prefixes: Set? - - /// Support for the FTS5 `columnsize` option - /// - /// https://www.sqlite.org/fts5.html#the_columnsize_option - public var columnSize: Int? - - /// Support for the FTS5 `detail` option - /// - /// https://www.sqlite.org/fts5.html#the_detail_option - public var detail: String? - - /// Appends a table column. - /// - /// try db.create(virtualTable: "document", using: FTS5()) { t in - /// t.column("content") - /// } - /// - /// - parameter name: the column name. - @discardableResult - public func column(_ name: String) -> FTS5ColumnDefinition { - let column = FTS5ColumnDefinition(name: name) - columns.append(column) - return column - } - - /// Synchronizes the full-text table with the content of an external - /// table. - /// - /// The full-text table is initially populated with the existing - /// 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 - public func synchronize(withTable tableName: String) { - contentMode = .synchronized(contentTable: tableName) - } + /// - parameter name: the column name. + @discardableResult + public func column(_ name: String) -> FTS5ColumnDefinition { + let column = FTS5ColumnDefinition(name: name) + columns.append(column) + return column } - /// The FTS5ColumnDefinition class lets you refine a column of an FTS5 - /// virtual table. + /// Synchronizes the full-text table with the content of an external + /// table. /// - /// You get instances of this class when you create an FTS5 table: + /// The full-text table is initially populated with the existing + /// 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 + public func synchronize(withTable tableName: String) { + contentMode = .synchronized(contentTable: tableName) + } +} + +/// The FTS5ColumnDefinition class lets you refine a column of an FTS5 +/// virtual table. +/// +/// You get instances of this class when you create an FTS5 table: +/// +/// try db.create(virtualTable: "document", using: FTS5()) { t in +/// t.column("content") // FTS5ColumnDefinition +/// } +/// +/// See https://www.sqlite.org/fts5.html +public final class FTS5ColumnDefinition { + fileprivate let name: String + fileprivate var isIndexed: Bool + + init(name: String) { + self.name = name + self.isIndexed = true + } + + /// Excludes the column from the full-text index. /// /// try db.create(virtualTable: "document", using: FTS5()) { t in - /// t.column("content") // FTS5ColumnDefinition + /// t.column("a") + /// t.column("b").notIndexed() /// } /// - /// See https://www.sqlite.org/fts5.html - public final class FTS5ColumnDefinition { - fileprivate let name: String - fileprivate var isIndexed: Bool - - init(name: String) { - self.name = name - self.isIndexed = true - } - - /// Excludes the column from the full-text index. - /// - /// try db.create(virtualTable: "document", using: FTS5()) { t in - /// t.column("a") - /// t.column("b").notIndexed() - /// } - /// - /// See 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 - return self - } - } - - extension Column { - /// The FTS5 rank column - public static let rank = Column("rank") + /// See 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 + return self } +} - extension Database { - /// Deletes the synchronization triggers for a synchronized FTS5 table - public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws { - try execute(sql: """ - DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier); - DROP TRIGGER IF EXISTS \("__\(tableName)_ad".quotedDatabaseIdentifier); - DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier); - """) - } +extension Column { + /// The FTS5 rank column + public static let rank = Column("rank") +} + +extension Database { + /// Deletes the synchronization triggers for a synchronized FTS5 table + public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws { + try execute(sql: """ + DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier); + DROP TRIGGER IF EXISTS \("__\(tableName)_ad".quotedDatabaseIdentifier); + DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier); + """) } +} #endif diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index b7834e225..5d8dc31fd 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -1,153 +1,153 @@ #if SQLITE_ENABLE_FTS5 - /// The protocol for custom FTS5 tokenizers. - public protocol FTS5CustomTokenizer : FTS5Tokenizer { - /// The name of the tokenizer; should uniquely identify your custom - /// tokenizer. - static var name: String { get } - - /// Creates a custom tokenizer. - /// - /// The arguments parameter is an array of String built from the CREATE - /// VIRTUAL TABLE statement. In the example below, the arguments will - /// be `["arg1", "arg2"]`. - /// - /// CREATE VIRTUAL TABLE document USING fts5( - /// tokenize='custom arg1 arg2' - /// ) - /// - /// - parameter db: A Database connection - /// - parameter arguments: An array of string arguments - init(db: Database, arguments: [String]) throws - } +/// The protocol for custom FTS5 tokenizers. +public protocol FTS5CustomTokenizer : FTS5Tokenizer { + /// The name of the tokenizer; should uniquely identify your custom + /// tokenizer. + static var name: String { get } - extension FTS5CustomTokenizer { - - /// Creates an FTS5 tokenizer descriptor. - /// - /// class MyTokenizer : FTS5CustomTokenizer { ... } - /// - /// db.create(virtualTable: "book", using: FTS5()) { t in - /// let tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["unicode61", "remove_diacritics", "0"]) - /// t.tokenizer = tokenizer - /// } - public static func tokenizerDescriptor(arguments: [String] = []) -> FTS5TokenizerDescriptor { - return FTS5TokenizerDescriptor(components: [name] + arguments) - } + /// Creates a custom tokenizer. + /// + /// The arguments parameter is an array of String built from the CREATE + /// VIRTUAL TABLE statement. In the example below, the arguments will + /// be `["arg1", "arg2"]`. + /// + /// CREATE VIRTUAL TABLE document USING fts5( + /// tokenize='custom arg1 arg2' + /// ) + /// + /// - parameter db: A Database connection + /// - parameter arguments: An array of string arguments + init(db: Database, arguments: [String]) throws +} +extension FTS5CustomTokenizer { + + /// Creates an FTS5 tokenizer descriptor. + /// + /// class MyTokenizer : FTS5CustomTokenizer { ... } + /// + /// db.create(virtualTable: "book", using: FTS5()) { t in + /// let tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["unicode61", "remove_diacritics", "0"]) + /// t.tokenizer = tokenizer + /// } + public static func tokenizerDescriptor(arguments: [String] = []) -> FTS5TokenizerDescriptor { + return FTS5TokenizerDescriptor(components: [name] + arguments) } - extension Database { +} + +extension Database { + + // MARK: - FTS5 + + private class FTS5TokenizerConstructor { + let db: Database + let constructor: (Database, [String], UnsafeMutablePointer?) -> Int32 - // MARK: - FTS5 - - private class FTS5TokenizerConstructor { - let db: Database - let constructor: (Database, [String], UnsafeMutablePointer?) -> Int32 - - init(db: Database, constructor: @escaping (Database, [String], UnsafeMutablePointer?) -> Int32) { - self.db = db - self.constructor = constructor - } - } - - /// Add a custom FTS5 tokenizer. - /// - /// class MyTokenizer : FTS5CustomTokenizer { ... } - /// db.add(tokenizer: MyTokenizer.self) - public func add(tokenizer: Tokenizer.Type) { - let api = FTS5.api(self) - - // Swift won't let the @convention(c) xCreate() function below create - // an instance of the generic Tokenizer type. - // - // We thus hide the generic Tokenizer type inside a neutral type: - // FTS5TokenizerConstructor - let constructor = FTS5TokenizerConstructor( - db: self, - constructor: { (db, arguments, tokenizerHandle) in - guard let tokenizerHandle = tokenizerHandle else { - return SQLITE_ERROR - } - do { - let tokenizer = try Tokenizer(db: db, arguments: arguments) - - // Tokenizer must remain alive until xDeleteTokenizer() - // is called, as the xDelete member of xTokenizer - let tokenizerPointer = OpaquePointer(Unmanaged.passRetained(tokenizer).toOpaque()) - - tokenizerHandle.pointee = tokenizerPointer - return SQLITE_OK - } catch let error as DatabaseError { - return error.extendedResultCode.rawValue - } catch { - return SQLITE_ERROR - } - }) - - // Constructor must remain alive until deleteConstructor() is - // called, as the last argument of the xCreateTokenizer() function. - let constructorPointer = Unmanaged.passRetained(constructor).toOpaque() - - func deleteConstructor(constructorPointer: UnsafeMutableRawPointer?) { - guard let constructorPointer = constructorPointer else { return } - Unmanaged.fromOpaque(constructorPointer).release() - } - - func xCreateTokenizer(constructorPointer: UnsafeMutableRawPointer?, azArg: UnsafeMutablePointer?>?, nArg: Int32, tokenizerHandle: UnsafeMutablePointer?) -> Int32 { - guard let constructorPointer = constructorPointer else { - return SQLITE_ERROR - } - let constructor = Unmanaged.fromOpaque(constructorPointer).takeUnretainedValue() - var arguments: [String] = [] - if let azArg = azArg { - for i in 0...fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).release() - } - - func xTokenize(tokenizerPointer: OpaquePointer?, context: UnsafeMutableRawPointer?, flags: Int32, pText: UnsafePointer?, nText: Int32, tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer?, Int32, Int32, Int32) -> Int32)?) -> Int32 { - guard let tokenizerPointer = tokenizerPointer else { - return SQLITE_ERROR - } - let object = Unmanaged.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).takeUnretainedValue() - guard let tokenizer = object as? FTS5Tokenizer else { - return SQLITE_ERROR - } - 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) - let code = withUnsafeMutablePointer(to: &xTokenizer) { xTokenizerPointer in - api.pointee.xCreateTokenizer(UnsafeMutablePointer(mutating: api), Tokenizer.name, constructorPointer, xTokenizerPointer, deleteConstructor) - } - guard code == SQLITE_OK else { - // Assume a GRDB bug: there is no point throwing any error. - fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description) - } + init(db: Database, constructor: @escaping (Database, [String], UnsafeMutablePointer?) -> Int32) { + self.db = db + self.constructor = constructor } } - extension DatabaseQueue { + /// Add a custom FTS5 tokenizer. + /// + /// class MyTokenizer : FTS5CustomTokenizer { ... } + /// db.add(tokenizer: MyTokenizer.self) + public func add(tokenizer: Tokenizer.Type) { + let api = FTS5.api(self) - // MARK: - Custom FTS5 Tokenizers + // Swift won't let the @convention(c) xCreate() function below create + // an instance of the generic Tokenizer type. + // + // We thus hide the generic Tokenizer type inside a neutral type: + // FTS5TokenizerConstructor + let constructor = FTS5TokenizerConstructor( + db: self, + constructor: { (db, arguments, tokenizerHandle) in + guard let tokenizerHandle = tokenizerHandle else { + return SQLITE_ERROR + } + do { + let tokenizer = try Tokenizer(db: db, arguments: arguments) + + // Tokenizer must remain alive until xDeleteTokenizer() + // is called, as the xDelete member of xTokenizer + let tokenizerPointer = OpaquePointer(Unmanaged.passRetained(tokenizer).toOpaque()) + + tokenizerHandle.pointee = tokenizerPointer + return SQLITE_OK + } catch let error as DatabaseError { + return error.extendedResultCode.rawValue + } catch { + return SQLITE_ERROR + } + }) - /// Add a custom FTS5 tokenizer. - /// - /// class MyTokenizer : FTS5CustomTokenizer { ... } - /// dbQueue.add(tokenizer: MyTokenizer.self) - public func add(tokenizer: Tokenizer.Type) { - inDatabase { db in - db.add(tokenizer: Tokenizer.self) + // Constructor must remain alive until deleteConstructor() is + // called, as the last argument of the xCreateTokenizer() function. + let constructorPointer = Unmanaged.passRetained(constructor).toOpaque() + + func deleteConstructor(constructorPointer: UnsafeMutableRawPointer?) { + guard let constructorPointer = constructorPointer else { return } + Unmanaged.fromOpaque(constructorPointer).release() + } + + func xCreateTokenizer(constructorPointer: UnsafeMutableRawPointer?, azArg: UnsafeMutablePointer?>?, nArg: Int32, tokenizerHandle: UnsafeMutablePointer?) -> Int32 { + guard let constructorPointer = constructorPointer else { + return SQLITE_ERROR } + let constructor = Unmanaged.fromOpaque(constructorPointer).takeUnretainedValue() + var arguments: [String] = [] + if let azArg = azArg { + for i in 0...fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).release() + } + + func xTokenize(tokenizerPointer: OpaquePointer?, context: UnsafeMutableRawPointer?, flags: Int32, pText: UnsafePointer?, nText: Int32, tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer?, Int32, Int32, Int32) -> Int32)?) -> Int32 { + guard let tokenizerPointer = tokenizerPointer else { + return SQLITE_ERROR + } + let object = Unmanaged.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).takeUnretainedValue() + guard let tokenizer = object as? FTS5Tokenizer else { + return SQLITE_ERROR + } + 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) + let code = withUnsafeMutablePointer(to: &xTokenizer) { xTokenizerPointer in + api.pointee.xCreateTokenizer(UnsafeMutablePointer(mutating: api), Tokenizer.name, constructorPointer, xTokenizerPointer, deleteConstructor) + } + guard code == SQLITE_OK else { + // Assume a GRDB bug: there is no point throwing any error. + fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description) } } +} + +extension DatabaseQueue { + + // MARK: - Custom FTS5 Tokenizers + + /// Add a custom FTS5 tokenizer. + /// + /// class MyTokenizer : FTS5CustomTokenizer { ... } + /// dbQueue.add(tokenizer: MyTokenizer.self) + public func add(tokenizer: Tokenizer.Type) { + inDatabase { db in + db.add(tokenizer: Tokenizer.self) + } + } +} #endif diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index 1e5e52a1e..c67558f10 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -1,121 +1,121 @@ #if SQLITE_ENABLE_FTS5 - /// A full text pattern that can query FTS5 virtual tables. - public struct FTS5Pattern { - - /// The raw pattern string. 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. - /// - /// 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? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } - guard !tokens.isEmpty else { return nil } - 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. - /// - /// 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? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } - guard !tokens.isEmpty else { return nil } - try? self.init(rawPattern: tokens.joined(separator: " ")) - } - - /// Creates a pattern that matches a contiguous string; returns nil if no - /// pattern could be built. - /// - /// 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? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } - guard !tokens.isEmpty else { return nil } - try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") - } - - /// Creates a pattern that matches a contiguous string prefix; returns - /// nil if no pattern could be built. - /// - /// FTS5Pattern(matchingPrefixPhrase: "") // nil - /// FTS5Pattern(matchingPrefixPhrase: "foo bar") // ^"foo bar" - /// - /// - parameter string: The string to turn into an FTS5 pattern - public init?(matchingPrefixPhrase string: String) { - guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } - guard !tokens.isEmpty else { return nil } - try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"") - } - - init(rawPattern: String, allowedColumns: [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. - do { - try DatabaseQueue().inDatabase { db in - try db.create(virtualTable: "document", using: FTS5()) { t in - if allowedColumns.isEmpty { - t.column("__grdb__") - } else { - for column in allowedColumns { - t.column(column) - } +/// A full text pattern that can query FTS5 virtual tables. +public struct FTS5Pattern { + + /// The raw pattern string. 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. + /// + /// 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? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard !tokens.isEmpty else { return nil } + 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. + /// + /// 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? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard !tokens.isEmpty else { return nil } + try? self.init(rawPattern: tokens.joined(separator: " ")) + } + + /// Creates a pattern that matches a contiguous string; returns nil if no + /// pattern could be built. + /// + /// 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? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard !tokens.isEmpty else { return nil } + try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"") + } + + /// Creates a pattern that matches a contiguous string prefix; returns + /// nil if no pattern could be built. + /// + /// FTS5Pattern(matchingPrefixPhrase: "") // nil + /// FTS5Pattern(matchingPrefixPhrase: "foo bar") // ^"foo bar" + /// + /// - parameter string: The string to turn into an FTS5 pattern + public init?(matchingPrefixPhrase string: String) { + guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil } + guard !tokens.isEmpty else { return nil } + try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"") + } + + init(rawPattern: String, allowedColumns: [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. + do { + try DatabaseQueue().inDatabase { db in + try db.create(virtualTable: "document", using: FTS5()) { t in + if allowedColumns.isEmpty { + t.column("__grdb__") + } else { + for column in allowedColumns { + t.column(column) } } - try db.makeSelectStatement(sql: "SELECT * FROM document WHERE document MATCH ?") - .makeCursor(arguments: [rawPattern]) - .next() // error on next() for invalid patterns } - } catch let error as DatabaseError { - // Remove private SQL & arguments from the thrown error - throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil) + try db.makeSelectStatement(sql: "SELECT * FROM document WHERE document MATCH ?") + .makeCursor(arguments: [rawPattern]) + .next() // error on next() for invalid patterns } - - // Pattern is valid - self.rawPattern = rawPattern + } catch let error as DatabaseError { + // Remove private SQL & arguments from the thrown error + throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil) } + + // Pattern is valid + self.rawPattern = rawPattern } +} - extension Database { - - // MARK: - FTS5 - - /// 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.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK - /// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND] - public func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern { - return try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map { $0.name }) - } +extension Database { + + // MARK: - FTS5 + + /// 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.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK + /// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND] + public func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern { + return try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map { $0.name }) } +} - extension FTS5Pattern : DatabaseValueConvertible { - /// Returns a value that can be stored in the database. - public var databaseValue: DatabaseValue { - return rawPattern.databaseValue - } - - /// Returns an FTS5Pattern initialized from *dbValue*, if it - /// contains a suitable value. - public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS5Pattern? { - return String - .fromDatabaseValue(dbValue) - .flatMap { try? FTS5Pattern(rawPattern: $0) } - } +extension FTS5Pattern : DatabaseValueConvertible { + /// Returns a value that can be stored in the database. + public var databaseValue: DatabaseValue { + return rawPattern.databaseValue } + + /// Returns an FTS5Pattern initialized from *dbValue*, if it + /// contains a suitable value. + public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS5Pattern? { + return String + .fromDatabaseValue(dbValue) + .flatMap { try? FTS5Pattern(rawPattern: $0) } + } +} #endif diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index 20efcdad3..684f548dc 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -1,214 +1,214 @@ #if SQLITE_ENABLE_FTS5 - /// A low-level SQLite function that lets FTS5Tokenizer notify tokens. - /// - /// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:) - public typealias FTS5TokenCallback = @convention(c) (_ context: UnsafeMutableRawPointer?, _ flags: Int32, _ pToken: UnsafePointer?, _ nToken: Int32, _ iStart: Int32, _ iEnd: Int32) -> Int32 - - /// The reason why FTS5 is requesting tokenization. - /// - /// See https://www.sqlite.org/fts5.html#custom_tokenizers - public struct FTS5Tokenization : OptionSet { - public let rawValue: Int32 - - public init(rawValue: Int32) { - 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) - } - - /// The protocol for FTS5 tokenizers - public protocol FTS5Tokenizer : class { - /// 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?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 - } - - private class TokenizeContext { - var tokens: [(String, FTS5TokenFlags)] = [] - } - - extension FTS5Tokenizer { - - /// Tokenizes the string argument into an array of - /// (String, FTS5TokenFlags) pairs. - /// - /// 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() - func tokenize(_ string: String, for tokenization: FTS5Tokenization) throws -> [(String, FTS5TokenFlags)] { - return try ContiguousArray(string.utf8).withUnsafeBufferPointer { buffer -> [(String, FTS5TokenFlags)] in - guard let addr = buffer.baseAddress else { - return [] - } - let pText = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self) - let nText = Int32(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) -> Int32 in - guard let contextPointer = 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 - } - } - - func nonSynonymTokens(in string: String, for tokenization: FTS5Tokenization) throws -> [String] { - var tokens: [String] = [] - for (token, flags) in try tokenize(string, for: tokenization) { - if !flags.contains(.colocated) { - tokens.append(token) - } - } - return tokens - } - } - - extension Database { - - // MARK: - FTS5 +/// A low-level SQLite function that lets FTS5Tokenizer notify tokens. +/// +/// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:) +public typealias FTS5TokenCallback = @convention(c) (_ context: UnsafeMutableRawPointer?, _ flags: Int32, _ pToken: UnsafePointer?, _ nToken: Int32, _ iStart: Int32, _ iEnd: Int32) -> Int32 - /// 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 +/// The reason why FTS5 is requesting tokenization. +/// +/// See https://www.sqlite.org/fts5.html#custom_tokenizers +public struct FTS5Tokenization : OptionSet { + public let rawValue: Int32 + + public init(rawValue: Int32) { + 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) +} + +/// The protocol for FTS5 tokenizers +public protocol FTS5Tokenizer : class { + /// 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?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 +} + +private class TokenizeContext { + var tokens: [(String, FTS5TokenFlags)] = [] +} + +extension FTS5Tokenizer { + + /// Tokenizes the string argument into an array of + /// (String, FTS5TokenFlags) pairs. + /// + /// 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() + func tokenize(_ string: String, for tokenization: FTS5Tokenization) throws -> [(String, FTS5TokenFlags)] { + return try ContiguousArray(string.utf8).withUnsafeBufferPointer { buffer -> [(String, FTS5TokenFlags)] in + guard let addr = buffer.baseAddress else { + return [] + } + let pText = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self) + let nText = Int32(buffer.count) - init(xTokenizer: fts5_tokenizer, contextPointer: UnsafeMutableRawPointer?, arguments: [String]) throws { - guard let xCreate = xTokenizer.xCreate else { - throw DatabaseError(resultCode: .SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate") - } - - self.xTokenizer = xTokenizer - - var tokenizerPointer: OpaquePointer? = nil - let code: Int32 - if let argument = arguments.first { - // Turn [String] into ContiguousArray> - // (for an alternative implementation see https://oleb.net/blog/2016/10/swift-array-of-c-strings/) - func convertArguments(_ array: inout ContiguousArray>, _ car: String, _ cdr: [String], _ body: (ContiguousArray>) -> Result) -> Result { - return car.withCString { cString in - if let car = cdr.first { - array.append(cString) - return convertArguments(&array, car, Array(cdr.suffix(from: 1)), body) - } else { - return body(array) - } - } + 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) -> Int32 in + guard let contextPointer = 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 } - var cStrings = ContiguousArray>() - code = convertArguments(&cStrings, argument, Array(arguments.suffix(from: 1))) { cStrings in - cStrings.withUnsafeBufferPointer { azArg in - xCreate(contextPointer, UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), Int32(cStrings.count), &tokenizerPointer) - } - } - } else { - code = xCreate(contextPointer, nil, 0, &tokenizerPointer) - } - - guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code, message: "failed fts5_tokenizer.xCreate") - } - - if let tokenizerPointer = tokenizerPointer { - self.tokenizerPointer = tokenizerPointer - } else { - throw DatabaseError(resultCode: code, message: "nil tokenizer") + + 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) } } - - deinit { - if let delete = xTokenizer.xDelete { - delete(tokenizerPointer) - } - } - - func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { - guard let xTokenize = xTokenizer.xTokenize else { - return SQLITE_ERROR - } - return xTokenize(tokenizerPointer, context, tokenization.rawValue, pText, nText, tokenCallback) + return context.tokens + } + } + + func nonSynonymTokens(in string: String, for tokenization: FTS5Tokenization) throws -> [String] { + var tokens: [String] = [] + for (token, flags) in try tokenize(string, for: tokenization) { + if !flags.contains(.colocated) { + tokens.append(token) } } + return 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 - /// Creates an FTS5 tokenizer, given its descriptor. - /// - /// let unicode61 = 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 -> FTS5Tokenizer { - let api = FTS5.api(self) + init(xTokenizer: fts5_tokenizer, contextPointer: UnsafeMutableRawPointer?, arguments: [String]) throws { + guard let xCreate = xTokenizer.xCreate else { + throw DatabaseError(resultCode: .SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate") + } - let xTokenizerPointer: UnsafeMutablePointer = .allocate(capacity: 1) - defer { xTokenizerPointer.deallocate() } + self.xTokenizer = xTokenizer - let contextHandle: UnsafeMutablePointer = .allocate(capacity: 1) - defer { contextHandle.deallocate() } - - let code = api.pointee.xFindTokenizer!( - UnsafeMutablePointer(mutating: api), - descriptor.name, - contextHandle, - xTokenizerPointer) + var tokenizerPointer: OpaquePointer? = nil + let code: Int32 + if let argument = arguments.first { + // Turn [String] into ContiguousArray> + // (for an alternative implementation see https://oleb.net/blog/2016/10/swift-array-of-c-strings/) + func convertArguments(_ array: inout ContiguousArray>, _ car: String, _ cdr: [String], _ body: (ContiguousArray>) -> Result) -> Result { + return car.withCString { cString in + if let car = cdr.first { + array.append(cString) + return convertArguments(&array, car, Array(cdr.suffix(from: 1)), body) + } else { + return body(array) + } + } + } + var cStrings = ContiguousArray>() + code = convertArguments(&cStrings, argument, Array(arguments.suffix(from: 1))) { cStrings in + cStrings.withUnsafeBufferPointer { azArg in + xCreate(contextPointer, UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), Int32(cStrings.count), &tokenizerPointer) + } + } + } else { + code = xCreate(contextPointer, nil, 0, &tokenizerPointer) + } guard code == SQLITE_OK else { - throw DatabaseError(resultCode: code) + throw DatabaseError(resultCode: code, message: "failed fts5_tokenizer.xCreate") } - let contextPointer = contextHandle.pointee - return try FTS5RegisteredTokenizer(xTokenizer: xTokenizerPointer.pointee, contextPointer: contextPointer, arguments: descriptor.arguments) + if let tokenizerPointer = 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?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { + 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. + /// + /// let unicode61 = 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 -> FTS5Tokenizer { + let api = FTS5.api(self) + + let xTokenizerPointer: UnsafeMutablePointer = .allocate(capacity: 1) + defer { xTokenizerPointer.deallocate() } + + let contextHandle: UnsafeMutablePointer = .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 diff --git a/GRDB/FTS/FTS5TokenizerDescriptor.swift b/GRDB/FTS/FTS5TokenizerDescriptor.swift index 128b62a64..31f3907b8 100644 --- a/GRDB/FTS/FTS5TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS5TokenizerDescriptor.swift @@ -1,132 +1,132 @@ #if SQLITE_ENABLE_FTS5 - /// An FTS5 tokenizer, suitable for FTS5 table definitions: +/// An FTS5 tokenizer, suitable for FTS5 table definitions: +/// +/// db.create(virtualTable: "book", using: FTS5()) { t in +/// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor +/// } +/// +/// See https://www.sqlite.org/fts5.html#tokenizers +public struct FTS5TokenizerDescriptor { + /// The tokenizer components + /// + /// // ["unicode61"] + /// FTS5TokenizerDescriptor.unicode61().components + /// + /// // ["unicode61", "remove_diacritics", "0"] + /// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components + public let components: [String] + + /// The tokenizer name + /// + /// // "unicode61" + /// FTS5TokenizerDescriptor.unicode61().name + /// + /// // "unicode61" + /// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).name + var name: String { + return components[0] + } + + var arguments: [String] { + return Array(components.suffix(from: 1)) + } + + /// Creates an FTS5 tokenizer descriptor. /// /// db.create(virtualTable: "book", using: FTS5()) { t in - /// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor + /// let tokenizer = FTS5TokenizerDescriptor(components: ["porter", "unicode61", "remove_diacritics", "0"]) + /// t.tokenizer = tokenizer /// } /// - /// See https://www.sqlite.org/fts5.html#tokenizers - public struct FTS5TokenizerDescriptor { - /// The tokenizer components - /// - /// // ["unicode61"] - /// FTS5TokenizerDescriptor.unicode61().components - /// - /// // ["unicode61", "remove_diacritics", "0"] - /// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components - public let components: [String] - - /// The tokenizer name - /// - /// // "unicode61" - /// FTS5TokenizerDescriptor.unicode61().name - /// - /// // "unicode61" - /// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).name - var name: String { - return components[0] - } - - var arguments: [String] { - return 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 - /// } - /// - /// - 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 - /// - /// db.create(virtualTable: "book", using: FTS5()) { t in - /// t.tokenizer = .ascii() - /// } - /// - /// - parameters: - /// - separators: Unless empty (the default), SQLite will consider - /// these characters as token separators. - /// - /// See https://www.sqlite.org/fts5.html#ascii_tokenizer - public static func ascii(separators: Set = []) -> FTS5TokenizerDescriptor { - if separators.isEmpty { - return FTS5TokenizerDescriptor(components: ["ascii"]) - } else { - return FTS5TokenizerDescriptor(components: ["ascii", "separators", separators.map { String($0) }.joined(separator: "").sqlExpression.quotedSQL()]) - } - } - - /// The "porter" tokenizer - /// - /// db.create(virtualTable: "book", using: FTS5()) { t in - /// t.tokenizer = .porter() - /// } - /// - /// - parameters: - /// - base: An eventual wrapping tokenizer which replaces the - // default unicode61() base tokenizer. - /// - /// See https://www.sqlite.org/fts5.html#porter_tokenizer - public static func porter(wrapping base: FTS5TokenizerDescriptor? = nil) -> FTS5TokenizerDescriptor { - if let base = base { - return FTS5TokenizerDescriptor(components: ["porter"] + base.components) - } else { - return FTS5TokenizerDescriptor(components: ["porter"]) - } - } - - /// An "unicode61" tokenizer - /// - /// db.create(virtualTable: "book", using: FTS5()) { t in - /// t.tokenizer = .unicode61() - /// } - /// - /// - parameters: - /// - removeDiacritics: If true (the default), then SQLite will - /// strip diacritics from latin characters. - /// - 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#unicode61_tokenizer - public static func unicode61(removeDiacritics: Bool = true, separators: Set = [], tokenCharacters: Set = []) -> FTS5TokenizerDescriptor { - var components: [String] = ["unicode61"] - // TODO: Support for remove_diacritics=2 (SQLite 3.27.0) - if !removeDiacritics { - components.append(contentsOf: ["remove_diacritics", "0"]) - } - if !separators.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) - components.append(contentsOf: [ - "separators", - separators - .sorted() - .map { String($0) } - .joined(separator: "") - .sqlExpression - .quotedSQL()]) - } - if !tokenCharacters.isEmpty { - // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) - components.append(contentsOf: [ - "tokenchars", - tokenCharacters - .sorted() - .map { String($0) } - .joined(separator: "") - .sqlExpression - .quotedSQL()]) - } - return FTS5TokenizerDescriptor(components: components) + /// - 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 + /// + /// db.create(virtualTable: "book", using: FTS5()) { t in + /// t.tokenizer = .ascii() + /// } + /// + /// - parameters: + /// - separators: Unless empty (the default), SQLite will consider + /// these characters as token separators. + /// + /// See https://www.sqlite.org/fts5.html#ascii_tokenizer + public static func ascii(separators: Set = []) -> FTS5TokenizerDescriptor { + if separators.isEmpty { + return FTS5TokenizerDescriptor(components: ["ascii"]) + } else { + return FTS5TokenizerDescriptor(components: ["ascii", "separators", separators.map { String($0) }.joined(separator: "").sqlExpression.quotedSQL()]) } } + + /// The "porter" tokenizer + /// + /// db.create(virtualTable: "book", using: FTS5()) { t in + /// t.tokenizer = .porter() + /// } + /// + /// - parameters: + /// - base: An eventual wrapping tokenizer which replaces the + // default unicode61() base tokenizer. + /// + /// See https://www.sqlite.org/fts5.html#porter_tokenizer + public static func porter(wrapping base: FTS5TokenizerDescriptor? = nil) -> FTS5TokenizerDescriptor { + if let base = base { + return FTS5TokenizerDescriptor(components: ["porter"] + base.components) + } else { + return FTS5TokenizerDescriptor(components: ["porter"]) + } + } + + /// An "unicode61" tokenizer + /// + /// db.create(virtualTable: "book", using: FTS5()) { t in + /// t.tokenizer = .unicode61() + /// } + /// + /// - parameters: + /// - removeDiacritics: If true (the default), then SQLite will + /// strip diacritics from latin characters. + /// - 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#unicode61_tokenizer + public static func unicode61(removeDiacritics: Bool = true, separators: Set = [], tokenCharacters: Set = []) -> FTS5TokenizerDescriptor { + var components: [String] = ["unicode61"] + // TODO: Support for remove_diacritics=2 (SQLite 3.27.0) + if !removeDiacritics { + components.append(contentsOf: ["remove_diacritics", "0"]) + } + if !separators.isEmpty { + // TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) + components.append(contentsOf: [ + "separators", + separators + .sorted() + .map { String($0) } + .joined(separator: "") + .sqlExpression + .quotedSQL()]) + } + if !tokenCharacters.isEmpty { + // TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:) + components.append(contentsOf: [ + "tokenchars", + tokenCharacters + .sorted() + .map { String($0) } + .joined(separator: "") + .sqlExpression + .quotedSQL()]) + } + return FTS5TokenizerDescriptor(components: components) + } +} #endif diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index 65b683f54..f8712ccc4 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -1,141 +1,141 @@ #if SQLITE_ENABLE_FTS5 - /// Flags that tell SQLite how to register a token. - /// - /// See https://www.sqlite.org/fts5.html#custom_tokenizers - public struct FTS5TokenFlags : OptionSet { - public let rawValue: Int32 - - public init(rawValue: Int32) { - self.rawValue = rawValue - } - - /// FTS5_TOKEN_COLOCATED - public static let colocated = FTS5TokenFlags(rawValue: FTS5_TOKEN_COLOCATED) +/// Flags that tell SQLite how to register a token. +/// +/// See https://www.sqlite.org/fts5.html#custom_tokenizers +public struct FTS5TokenFlags : OptionSet { + public let rawValue: Int32 + + public init(rawValue: Int32) { + self.rawValue = rawValue } - /// A function that lets FTS5WrapperTokenizer notify tokens. - /// - /// See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:) - public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> () + /// FTS5_TOKEN_COLOCATED + public static let colocated = FTS5TokenFlags(rawValue: FTS5_TOKEN_COLOCATED) +} + +/// A function that lets FTS5WrapperTokenizer notify tokens. +/// +/// See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:) +public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> () + +/// The protocol for custom FTS5 tokenizers that wrap another tokenizer. +/// +/// Types that adopt FTS5WrapperTokenizer don't have to implement the +/// low-level FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:). +/// +/// Instead, they process regular Swift strings. +/// +/// Here is the implementation for a trivial tokenizer that wraps the +/// built-in ascii tokenizer without any custom processing: +/// +/// 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) +/// } +/// } +public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { + /// The wrapped tokenizer + var wrappedTokenizer: FTS5Tokenizer { get } - /// The protocol for custom FTS5 tokenizers that wrap another tokenizer. + /// Given a token produced by the wrapped tokenizer, notifies customized + /// tokens to the `tokenCallback` function. /// - /// Types that adopt FTS5WrapperTokenizer don't have to implement the - /// low-level FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:). + /// For example: /// - /// Instead, they process regular Swift strings. - /// - /// Here is the implementation for a trivial tokenizer that wraps the - /// built-in ascii tokenizer without any custom processing: - /// - /// 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) - /// } + /// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws { + /// // pass through: + /// try tokenCallback(token, flags) /// } - public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer { - /// The wrapped tokenizer - var wrappedTokenizer: FTS5Tokenizer { get } - - /// Given a token produced by the wrapped tokenizer, notifies customized - /// tokens to the `tokenCallback` function. - /// - /// For example: - /// - /// 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: - /// - /// 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 - /// 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, for 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?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { - // `tokenCallback` is @convention(c). This requires a little setup - // in order to transfer context. - var customContext = FTS5WrapperContext( - tokenizer: self, - context: context, - tokenization: tokenization, - tokenCallback: tokenCallback) - return withUnsafeMutablePointer(to: &customContext) { customContextPointer in - // Invoke wrappedTokenizer - 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 { - return 0 // SQLITE_OK - } - - // Extract context - 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: tokenFlags), - for: 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(resultCode: code, message: "token callback failed") - } + /// + /// When implementing the accept method, there are a two rules + /// to observe: + /// + /// 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 + /// 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, for 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?, tokenization: FTS5Tokenization, pText: UnsafePointer?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 { + // `tokenCallback` is @convention(c). This requires a little setup + // in order to transfer context. + var customContext = FTS5WrapperContext( + tokenizer: self, + context: context, + tokenization: tokenization, + tokenCallback: tokenCallback) + return withUnsafeMutablePointer(to: &customContext) { customContextPointer in + // Invoke wrappedTokenizer + 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 { + return 0 // SQLITE_OK + } + + // Extract context + 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: tokenFlags), + for: tokenization, + tokenCallback: { (token, flags) in + // Turn token into bytes + return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in + guard let addr = buffer.baseAddress else { + return } - }) - - return SQLITE_OK - } catch let error as DatabaseError { - return error.extendedResultCode.rawValue - } catch { - return SQLITE_ERROR - } + 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(resultCode: code, message: "token callback failed") + } + } + }) + + return SQLITE_OK + } catch let error as DatabaseError { + return error.extendedResultCode.rawValue + } catch { + return SQLITE_ERROR } } } } +} #endif