feat: add files notes and search

This commit is contained in:
2026-07-18 16:03:06 +08:00
parent 530fc43cca
commit b7fb1969e6
6 changed files with 206 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
package search
import (
"strings"
"gorm.io/gorm"
"senlinai-agent/backend/internal/domain"
)
type Service struct {
db *gorm.DB
}
type Result struct {
Type string `json:"type"`
ID uint `json:"id"`
ProjectID uint `json:"project_id"`
Title string `json:"title"`
Snippet string `json:"snippet"`
}
func NewService(database *gorm.DB) *Service {
return &Service{db: database}
}
func (s *Service) Search(userID uint, query string) ([]Result, error) {
query = strings.TrimSpace(query)
if query == "" {
return []Result{}, nil
}
if s.db.Dialector.Name() == "postgres" {
return s.searchPostgres(userID, query)
}
var notes []domain.Note
if err := s.db.Joins("JOIN projects ON projects.id = notes.project_id").
Where("projects.owner_id = ? AND (notes.title LIKE ? OR notes.markdown LIKE ?)", userID, "%"+query+"%", "%"+query+"%").
Find(&notes).Error; err != nil {
return nil, err
}
results := make([]Result, 0, len(notes))
for _, note := range notes {
results = append(results, Result{Type: "note", ID: note.ID, ProjectID: note.ProjectID, Title: note.Title, Snippet: note.Markdown})
}
return results, nil
}
func (s *Service) searchPostgres(userID uint, query string) ([]Result, error) {
var results []Result
err := s.db.Raw(`
SELECT 'note' AS type, notes.id, notes.project_id, notes.title, notes.markdown AS snippet
FROM notes
JOIN projects ON projects.id = notes.project_id
WHERE projects.owner_id = ?
AND to_tsvector('simple', coalesce(notes.title, '') || ' ' || coalesce(notes.markdown, ''))
@@ plainto_tsquery('simple', ?)
ORDER BY notes.updated_at DESC
LIMIT 50
`, userID, query).Scan(&results).Error
return results, err
}

View File

@@ -0,0 +1,26 @@
package search
import (
"fmt"
"testing"
"github.com/glebarez/sqlite"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
"senlinai-agent/backend/internal/domain"
)
func TestSearchFindsNoteBody(t *testing.T) {
database, err := gorm.Open(sqlite.Open(fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, domain.AutoMigrate(database))
require.NoError(t, database.Create(&domain.Project{ID: 1, OwnerID: 7, Name: "支付项目"}).Error)
require.NoError(t, database.Create(&domain.Note{ProjectID: 1, CreatedBy: 7, Title: "接口方案", Markdown: "二维码支付回调设计"}).Error)
service := NewService(database)
results, err := service.Search(7, "回调")
require.NoError(t, err)
require.Len(t, results, 1)
require.Equal(t, "note", results[0].Type)
}