-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsqlitefs.go
More file actions
231 lines (195 loc) · 5.95 KB
/
sqlitefs.go
File metadata and controls
231 lines (195 loc) · 5.95 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package sqlitefs
import (
"database/sql"
"errors"
"io/fs"
"sync"
)
type writeRequest struct {
path string
data []byte
index int
mimeType string
respCh chan error
}
type SQLiteFS struct {
db *sql.DB
writeCh chan writeRequest
writerWg sync.WaitGroup
}
var _ fs.FS = (*SQLiteFS)(nil)
// NewSQLiteFS создает новый экземпляр SQLiteFS с заданной базой данных.
// Проверяет наличие необходимых таблиц и создает их при отсутствии.
func NewSQLiteFS(db *sql.DB) (*SQLiteFS, error) {
fs := &SQLiteFS{
db: db,
writeCh: make(chan writeRequest),
}
err := fs.createTablesIfNeeded()
if err != nil {
return nil, err
}
fs.writerWg.Add(1)
go fs.writerLoop()
return fs, nil
}
// NewWriter creates a new writer for the specified path.
func (fs *SQLiteFS) NewWriter(path string) *SQLiteWriter {
return NewSQLiteWriter(fs, path)
}
// Open opens the named file.
func (fs *SQLiteFS) Open(name string) (fs.File, error) {
// Clean the path - remove leading slash if present
if name == "" || name == "." {
name = "/"
}
// Remove leading slash for database lookup
dbPath := name
if len(dbPath) > 0 && dbPath[0] == '/' {
dbPath = dbPath[1:]
}
// Check if the file exists directly
var exists bool
err := fs.db.QueryRow("SELECT EXISTS(SELECT 1 FROM file_metadata WHERE path = ?)", dbPath).Scan(&exists)
if err != nil {
return nil, err
}
if exists {
return NewSQLiteFile(fs.db, dbPath)
}
// If not found directly, check if it's a directory by looking for files with this prefix
// This handles the case where the directory itself isn't explicitly stored
if dbPath == "" {
// Root directory - check if any files exist
err = fs.db.QueryRow("SELECT EXISTS(SELECT 1 FROM file_metadata LIMIT 1)").Scan(&exists)
if err != nil {
return nil, err
}
if exists || dbPath == "" { // Root always exists even if empty
return NewSQLiteFile(fs.db, "")
}
} else {
dirPath := dbPath
if len(dirPath) > 0 && dirPath[len(dirPath)-1] != '/' {
dirPath += "/"
}
err = fs.db.QueryRow("SELECT EXISTS(SELECT 1 FROM file_metadata WHERE path LIKE ? LIMIT 1)", dirPath+"%").Scan(&exists)
if err != nil {
return nil, err
}
if exists {
// It's a directory, create a directory file
return NewSQLiteFile(fs.db, dirPath)
}
}
return nil, fs.Error("file does not exist", name)
}
// Error returns a formatted error that includes the path
func (fs *SQLiteFS) Error(msg, path string) error {
return &PathError{Op: "open", Path: path, Err: errors.New(msg)}
}
// PathError records an error and the operation and file path that caused it.
type PathError struct {
Op string
Path string
Err error
}
func (e *PathError) Error() string {
return e.Op + " " + e.Path + ": " + e.Err.Error()
}
// createTablesIfNeeded создает таблицы file_metadata и file_fragments, если они еще не созданы.
func (fs *SQLiteFS) createTablesIfNeeded() error {
_, err := fs.db.Exec(`
CREATE TABLE IF NOT EXISTS file_metadata (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path TEXT UNIQUE NOT NULL,
type TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS file_fragments (
file_id INTEGER NOT NULL,
fragment_index INTEGER NOT NULL,
fragment BLOB NOT NULL,
PRIMARY KEY (file_id, fragment_index),
FOREIGN KEY (file_id) REFERENCES file_metadata(id)
);
CREATE INDEX IF NOT EXISTS idx_file_metadata_path ON file_metadata(path);
CREATE INDEX IF NOT EXISTS idx_file_fragments_length ON file_fragments(file_id, length(fragment));
`)
return err
}
func (fs *SQLiteFS) writerLoop() {
defer fs.writerWg.Done()
for req := range fs.writeCh {
var err error
if req.mimeType != "" {
err = fs.createFileRecord(req.path, req.mimeType)
} else {
err = fs.writeFragment(req.path, req.data, req.index)
}
req.respCh <- err
}
}
func (fs *SQLiteFS) createFileRecord(path, mimeType string) error {
_, err := fs.db.Exec("INSERT OR REPLACE INTO file_metadata (path, type) VALUES (?, ?)", path, mimeType)
return err
}
func (fs *SQLiteFS) writeFragment(path string, data []byte, index int) error {
tx, err := fs.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
var fileID int64
err = tx.QueryRow("SELECT id FROM file_metadata WHERE path = ?", path).Scan(&fileID)
if err != nil {
return err
}
_, err = tx.Exec("INSERT OR REPLACE INTO file_fragments (file_id, fragment_index, fragment) VALUES (?, ?, ?)",
fileID, index, data)
if err != nil {
return err
}
return tx.Commit()
}
func (fs *SQLiteFS) Close() error {
close(fs.writeCh)
fs.writerWg.Wait()
return fs.db.Close()
}
// Remove deletes a file or empty directory from the filesystem.
// It follows os.Remove() semantics - directories must be empty.
func (fs *SQLiteFS) Remove(path string) error {
// Normalize path (remove leading slash)
if len(path) > 0 && path[0] == '/' {
path = path[1:]
}
// Remove trailing slash for directory paths
if len(path) > 0 && path[len(path)-1] == '/' {
path = path[:len(path)-1]
}
// Check if this is a directory (has children)
var hasChildren bool
dirPrefix := path + "/"
err := fs.db.QueryRow("SELECT EXISTS(SELECT 1 FROM file_metadata WHERE path LIKE ? AND path != ?)", dirPrefix+"%", path).Scan(&hasChildren)
if err != nil {
return err
}
if hasChildren {
return &PathError{Op: "remove", Path: path, Err: errors.New("directory not empty")}
}
// Delete fragments first (due to foreign key constraint)
_, err = fs.db.Exec(`DELETE FROM file_fragments WHERE file_id IN (SELECT id FROM file_metadata WHERE path = ?)`, path)
if err != nil {
return err
}
// Delete metadata
result, err := fs.db.Exec(`DELETE FROM file_metadata WHERE path = ?`, path)
if err != nil {
return err
}
rows, _ := result.RowsAffected()
if rows == 0 {
return &PathError{Op: "remove", Path: path, Err: errors.New("file not found")}
}
return nil
}