-
Notifications
You must be signed in to change notification settings - Fork 6
Full Text Search Demonstration #76
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
// | ||
// SearchResultRow.swift | ||
// PowerSyncExample | ||
// | ||
// Created by Joshua Brink on 2025/09/03. | ||
// | ||
|
||
import SwiftUI | ||
|
||
struct SearchResultRow: View { | ||
let item: SearchResultItem | ||
|
||
var body: some View { | ||
HStack { | ||
|
||
Image(systemName: item.type == .list ? "list.bullet" : "checkmark.circle") | ||
.foregroundColor(.secondary) | ||
|
||
if let list = item.listContent { | ||
Text(list.name) | ||
} else if let todo = item.todo { | ||
Text(todo.description) | ||
.strikethrough(todo.isComplete, color: .secondary) | ||
.foregroundColor(todo.isComplete ? .secondary : .primary) | ||
} else { | ||
Text("Unknown item") | ||
} | ||
|
||
Spacer() | ||
|
||
Image(systemName: "chevron.right") | ||
.font(.caption.weight(.bold)) | ||
.foregroundColor(.secondary.opacity(0.5)) | ||
} | ||
.contentShape(Rectangle()) | ||
} | ||
} | ||
|
||
#Preview { | ||
List { | ||
SearchResultRow(item: SearchResultItem( | ||
id: UUID().uuidString, | ||
type: .list, | ||
content: ListContent(id: UUID().uuidString, name: "Groceries", createdAt: "now", ownerId: "user1") | ||
)) | ||
SearchResultRow(item: SearchResultItem( | ||
id: UUID().uuidString, | ||
type: .todo, | ||
content: Todo(id: UUID().uuidString, listId: "list1", description: "Buy milk", isComplete: false) | ||
)) | ||
SearchResultRow(item: SearchResultItem( | ||
id: UUID().uuidString, | ||
type: .todo, | ||
content: Todo(id: UUID().uuidString, listId: "list1", description: "Walk the dog", isComplete: true) | ||
)) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,6 +4,7 @@ enum Route: Hashable { | |
case home | ||
case signIn | ||
case signUp | ||
case search | ||
} | ||
|
||
@Observable | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,184 @@ | ||
// | ||
// FullTextSearch.swift | ||
// PowerSyncExample | ||
// | ||
// Created by Joshua Brink on 2025/09/03. | ||
// | ||
joshua-journey-apps marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
import Foundation | ||
import PowerSync | ||
|
||
enum ExtractType { | ||
case columnOnly | ||
case columnInOperation | ||
} | ||
|
||
/// Generates SQL JSON extract expressions for FTS triggers. | ||
/// | ||
/// - Parameters: | ||
/// - type: The type of extraction needed (`columnOnly` or `columnInOperation`). | ||
/// - sourceColumn: The JSON source column (e.g., `'data'`, `'NEW.data'`). | ||
/// - columns: The list of column names to extract. | ||
/// - Returns: A comma-separated string of SQL expressions. | ||
func generateJsonExtracts(type: ExtractType, sourceColumn: String, columns: [String]) -> String { | ||
func createExtract(jsonSource: String, columnName: String) -> String { | ||
return "json_extract(\(jsonSource), '$.\"\(columnName)\"')" | ||
} | ||
|
||
func generateSingleColumnSql(columnName: String) -> String { | ||
switch type { | ||
case .columnOnly: | ||
return createExtract(jsonSource: sourceColumn, columnName: columnName) | ||
case .columnInOperation: | ||
return "\"\(columnName)\" = \(createExtract(jsonSource: sourceColumn, columnName: columnName))" | ||
} | ||
} | ||
|
||
return columns.map(generateSingleColumnSql).joined(separator: ", ") | ||
} | ||
|
||
/// Generates the SQL statements required to set up an FTS5 virtual table | ||
/// and corresponding triggers for a given PowerSync table. | ||
/// | ||
/// | ||
/// - Parameters: | ||
/// - tableName: The public name of the table to index (e.g., "lists", "todos"). | ||
/// - columns: The list of column names within the table to include in the FTS index. | ||
/// - schema: The PowerSync `Schema` object to find the internal table name. | ||
/// - tokenizationMethod: The FTS5 tokenization method (e.g., "porter unicode61", "unicode61"). | ||
/// - Returns: An array of SQL statements to be executed, or `nil` if the table is not found in the schema. | ||
func getFtsSetupSqlStatements( | ||
tableName: String, | ||
columns: [String], | ||
schema: Schema, | ||
tokenizationMethod: String = "unicode61" | ||
) -> [String]? { | ||
|
||
guard let table = schema.tables.first(where: { $0.name == tableName }) else { | ||
print("Table '\(tableName)' not found in schema. Skipping FTS setup for this table.") | ||
return nil | ||
} | ||
let internalName = table.localOnly ? "ps_data_local__\(table.name)" : "ps_data__\(table.name)" | ||
|
||
let ftsTableName = "fts_\(tableName)" | ||
|
||
let stringColumnsForCreate = columns.map { "\"\($0)\"" }.joined(separator: ", ") | ||
|
||
let stringColumnsForInsertList = columns.map { "\"\($0)\"" }.joined(separator: ", ") | ||
|
||
var sqlStatements: [String] = [] | ||
|
||
// 1. Create the FTS5 Virtual Table | ||
sqlStatements.append(""" | ||
CREATE VIRTUAL TABLE IF NOT EXISTS \(ftsTableName) | ||
USING fts5(id UNINDEXED, \(stringColumnsForCreate), tokenize='\(tokenizationMethod)'); | ||
""") | ||
|
||
// 2. Copy existing data from the main table to the FTS table | ||
sqlStatements.append(""" | ||
INSERT INTO \(ftsTableName)(rowid, id, \(stringColumnsForInsertList)) | ||
SELECT rowid, id, \(generateJsonExtracts(type: .columnOnly, sourceColumn: "data", columns: columns)) | ||
FROM \(internalName); | ||
""") | ||
|
||
// 3. Create INSERT Trigger | ||
sqlStatements.append(""" | ||
CREATE TRIGGER IF NOT EXISTS fts_insert_trigger_\(tableName) AFTER INSERT ON \(internalName) | ||
BEGIN | ||
INSERT INTO \(ftsTableName)(rowid, id, \(stringColumnsForInsertList)) | ||
VALUES ( | ||
NEW.rowid, | ||
NEW.id, | ||
\(generateJsonExtracts(type: .columnOnly, sourceColumn: "NEW.data", columns: columns)) | ||
); | ||
END; | ||
""") | ||
|
||
// 4. Create UPDATE Trigger | ||
sqlStatements.append(""" | ||
CREATE TRIGGER IF NOT EXISTS fts_update_trigger_\(tableName) AFTER UPDATE ON \(internalName) | ||
BEGIN | ||
UPDATE \(ftsTableName) | ||
SET \(generateJsonExtracts(type: .columnInOperation, sourceColumn: "NEW.data", columns: columns)) | ||
WHERE rowid = NEW.rowid; | ||
END; | ||
""") | ||
|
||
// 5. Create DELETE Trigger | ||
sqlStatements.append(""" | ||
CREATE TRIGGER IF NOT EXISTS fts_delete_trigger_\(tableName) AFTER DELETE ON \(internalName) | ||
BEGIN | ||
DELETE FROM \(ftsTableName) WHERE rowid = OLD.rowid; | ||
END; | ||
""") | ||
|
||
return sqlStatements | ||
} | ||
|
||
|
||
/// Configures Full-Text Search (FTS) tables and triggers for specified tables | ||
/// within the PowerSync database. Call this function during database initialization. | ||
/// | ||
/// Executes all generated SQL within a single transaction. | ||
/// | ||
/// - Parameters: | ||
/// - db: The initialized `PowerSyncDatabaseProtocol` instance. | ||
/// - schema: The `Schema` instance matching the database. | ||
/// - Throws: An error if the database transaction fails. | ||
func configureFts(db: PowerSyncDatabaseProtocol, schema: Schema) async throws { | ||
let ftsCheckTable = "fts_\(LISTS_TABLE)" | ||
let checkSql = "SELECT name FROM sqlite_master WHERE type='table' AND name = ?" | ||
|
||
do { | ||
let existingTable: String? = try await db.getOptional(sql: checkSql, parameters: [ftsCheckTable]) { cursor in | ||
try cursor.getString(name: "name") | ||
} | ||
|
||
if existingTable != nil { | ||
print("[FTS] FTS table '\(ftsCheckTable)' already exists. Skipping setup.") | ||
return | ||
} | ||
} catch { | ||
print("[FTS] Failed to check for existing FTS tables: \(error.localizedDescription). Proceeding with setup attempt.") | ||
} | ||
print("[FTS] Starting FTS configuration...") | ||
var allSqlStatements: [String] = [] | ||
|
||
if let listStatements = getFtsSetupSqlStatements( | ||
tableName: LISTS_TABLE, | ||
columns: ["name"], | ||
schema: schema, | ||
tokenizationMethod: "porter unicode61" | ||
) { | ||
print("[FTS] Generated \(listStatements.count) SQL statements for '\(LISTS_TABLE)' table.") | ||
allSqlStatements.append(contentsOf: listStatements) | ||
} | ||
|
||
if let todoStatements = getFtsSetupSqlStatements( | ||
tableName: TODOS_TABLE, | ||
columns: ["description"], | ||
schema: schema | ||
) { | ||
print("[FTS] Generated \(todoStatements.count) SQL statements for '\(TODOS_TABLE)' table.") | ||
allSqlStatements.append(contentsOf: todoStatements) | ||
} | ||
|
||
// --- Execute all generated SQL statements --- | ||
|
||
if !allSqlStatements.isEmpty { | ||
do { | ||
print("[FTS] Executing \(allSqlStatements.count) SQL statements in a transaction...") | ||
_ = try await db.writeTransaction { transaction in | ||
for sql in allSqlStatements { | ||
print("[FTS] Executing SQL:\n\(sql)") | ||
_ = try transaction.execute(sql: sql, parameters: []) | ||
} | ||
} | ||
print("[FTS] Configuration completed successfully.") | ||
} catch { | ||
print("[FTS] Error during FTS setup SQL execution: \(error.localizedDescription)") | ||
throw error | ||
} | ||
} else { | ||
print("[FTS] No FTS SQL statements were generated. Check table names and schema definition.") | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// | ||
// SearchResultItem.swift | ||
// PowerSyncExample | ||
// | ||
// Created by Joshua Brink on 2025/09/03. | ||
// | ||
|
||
joshua-journey-apps marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
import Foundation | ||
|
||
enum SearchResultType { | ||
case list | ||
case todo | ||
} | ||
|
||
struct SearchResultItem: Identifiable, Hashable { | ||
let id: String | ||
let type: SearchResultType | ||
let content: AnyHashable | ||
simolus3 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
var listContent: ListContent? { | ||
content as? ListContent | ||
} | ||
|
||
var todo: Todo? { | ||
content as? Todo | ||
} | ||
|
||
func hash(into hasher: inout Hasher) { | ||
hasher.combine(id) | ||
hasher.combine(type) | ||
} | ||
|
||
static func == (lhs: SearchResultItem, rhs: SearchResultItem) -> Bool { | ||
lhs.id == rhs.id && lhs.type == rhs.type | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.