Skip to content

Commit

Permalink
Escape SQLite FTS search terms
Browse files Browse the repository at this point in the history
  • Loading branch information
FluxCapacitor2 committed Aug 7, 2024
1 parent f7bee7c commit 9676345
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions app/database/db_sqlite.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package database
import (
"database/sql"
"fmt"
"regexp"
"strings"

"github.com/google/uuid"
Expand Down Expand Up @@ -181,9 +182,16 @@ type RawResult struct {
Content string
}

// TODO: escape the search term. If it contains a . or unclosed quote, it triggers a syntax error and the query fails.
//
// (see https://sqlite.org/fts5.html#full_text_query_syntax)
var re = regexp.MustCompile(`\W`)

func escape(searchTerm string) string {
// Split the search term into individual words (this step also removes double quotes from the input)
words := re.Split(searchTerm, -1)
// Surround each word with double quotes and add a * to match partial words at the end of the query
quoted := fmt.Sprintf("\"%s\"*", strings.Join(words, "\" \""))
return quoted
}

func (db *SQLiteDatabase) Search(sources []string, search string, page uint32, pageSize uint32) ([]Result, *uint32, error) {

tx, err := db.conn.Begin()
Expand Down Expand Up @@ -216,7 +224,7 @@ func (db *SQLiteDatabase) Search(sources []string, search string, page uint32, p
// Add the required status and search term as parameters
args = append(args,
Finished, // (as opposed to the Error or Unindexable states)
search,
escape(search),
pageSize,
(page-1)*pageSize,
)
Expand Down

0 comments on commit 9676345

Please sign in to comment.