2020-01-31 21:35:06 +01:00
|
|
|
package persistence
|
|
|
|
|
|
|
|
import (
|
2020-04-09 05:29:28 +02:00
|
|
|
"sort"
|
2020-01-31 21:35:06 +01:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
. "github.com/Masterminds/squirrel"
|
|
|
|
"github.com/kennygrant/sanitize"
|
|
|
|
)
|
|
|
|
|
2020-03-20 02:43:30 +01:00
|
|
|
func (r sqlRepository) getFullText(text ...string) string {
|
2020-02-10 01:52:06 +01:00
|
|
|
sanitizedText := strings.Builder{}
|
|
|
|
for _, txt := range text {
|
|
|
|
sanitizedText.WriteString(strings.TrimSpace(sanitize.Accents(strings.ToLower(txt))) + " ")
|
|
|
|
}
|
2020-04-09 05:29:28 +02:00
|
|
|
words := make(map[string]struct{})
|
|
|
|
for _, w := range strings.Fields(sanitizedText.String()) {
|
|
|
|
words[w] = struct{}{}
|
|
|
|
}
|
|
|
|
var fullText []string
|
|
|
|
for w := range words {
|
|
|
|
fullText = append(fullText, w)
|
|
|
|
}
|
|
|
|
sort.Strings(fullText)
|
|
|
|
return strings.Join(fullText, " ")
|
2020-01-31 21:35:06 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r sqlRepository) doSearch(q string, offset, size int, results interface{}, orderBys ...string) error {
|
|
|
|
q = strings.TrimSpace(sanitize.Accents(strings.ToLower(strings.TrimSuffix(q, "*"))))
|
2020-02-09 18:20:34 +01:00
|
|
|
if len(q) < 2 {
|
2020-01-31 21:35:06 +01:00
|
|
|
return nil
|
|
|
|
}
|
2020-02-25 04:06:12 +01:00
|
|
|
sq := r.newSelectWithAnnotation(r.tableName + ".id").Columns("*")
|
2020-01-31 21:35:06 +01:00
|
|
|
sq = sq.Limit(uint64(size)).Offset(uint64(offset))
|
|
|
|
if len(orderBys) > 0 {
|
|
|
|
sq = sq.OrderBy(orderBys...)
|
|
|
|
}
|
|
|
|
parts := strings.Split(q, " ")
|
|
|
|
for _, part := range parts {
|
|
|
|
sq = sq.Where(Or{
|
|
|
|
Like{"full_text": part + "%"},
|
|
|
|
Like{"full_text": "%" + part + "%"},
|
|
|
|
})
|
|
|
|
}
|
2020-02-01 20:48:22 +01:00
|
|
|
err := r.queryAll(sq, results)
|
2020-01-31 21:35:06 +01:00
|
|
|
return err
|
|
|
|
}
|