-
Notifications
You must be signed in to change notification settings - Fork 12
/
document.go
45 lines (38 loc) · 1.26 KB
/
document.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package datastore
import (
"context"
"fmt"
"github.com/gptscript-ai/knowledge/pkg/index"
"log/slog"
)
func (s *Datastore) DeleteDocument(ctx context.Context, documentID, datasetID string) error {
// Find in Database
var document index.Document
tx := s.Index.WithContext(ctx).First(&document, "id = ? AND dataset = ?", documentID, datasetID)
if tx.Error != nil {
return ErrDBDocumentNotFound
}
// Remove from VectorStore
if err := s.Vectorstore.RemoveDocument(ctx, documentID, datasetID); err != nil {
return fmt.Errorf("failed to remove document from VectorStore: %w", err)
}
// Remove from Database
tx = s.Index.WithContext(ctx).Delete(&document)
if tx.Error != nil {
return fmt.Errorf("failed to delete document from DB: %w", tx.Error)
}
// Check if owning file should be removed
var count int64
tx = s.Index.WithContext(ctx).Model(&index.Document{}).Where("file_id = ?", document.FileID).Count(&count)
if tx.Error != nil {
return tx.Error
}
if count == 0 {
slog.Info("Removing file, because all associated documents are gone", "file", document.FileID)
tx = s.Index.WithContext(ctx).Delete(&index.File{}, "id = ?", document.FileID)
if tx.Error != nil {
return fmt.Errorf("failed to delete owning file from DB: %w", tx.Error)
}
}
return nil
}