Skip to content

Commit 2d70a59

Browse files
authored
Merge pull request #7 from jilio/feat/simpler-writer
feat: Simpler writer and proper close
2 parents 47c3580 + 45c0bae commit 2d70a59

File tree

3 files changed

+21
-2
lines changed

3 files changed

+21
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ SQLiteFS is a Go package that implements the `fs.FS` interface using SQLite as a
1414

1515
To use SQLiteFS in your Go project, run the following command:
1616

17-
```
17+
```sh
1818
go get github.com/jilio/sqlitefs
1919
```
2020

@@ -51,7 +51,7 @@ func main() {
5151
defer sqliteFS.Close()
5252

5353
// Write a file
54-
writer := sqlitefs.NewSQLiteWriter(sqliteFS, "example.txt")
54+
writer := sqliteFS.NewWriter("example.txt")
5555
_, err = writer.Write([]byte("Hello, SQLiteFS!"))
5656
if err != nil {
5757
log.Fatal(err)

sqlitefs.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ func NewSQLiteFS(db *sql.DB) (*SQLiteFS, error) {
4242
return fs, nil
4343
}
4444

45+
// NewWriter creates a new writer for the specified path.
46+
func (fs *SQLiteFS) NewWriter(path string) *SQLiteWriter {
47+
return NewSQLiteWriter(fs, path)
48+
}
49+
4550
// Open открывает файл по указанному пути.
4651
func (fs *SQLiteFS) Open(name string) (fs.File, error) {
4752
// Проверка существования файла в базе данных

writer.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package sqlitefs
22

33
import (
4+
"errors"
45
"mime"
56
"path/filepath"
67
)
@@ -14,8 +15,11 @@ type SQLiteWriter struct {
1415
fragmentSize int
1516
fragmentIndex int
1617
fileCreated bool
18+
closed bool
1719
}
1820

21+
// NewSQLiteWriter creates a new SQLiteWriter for the specified path.
22+
// Deprecated: Use SQLiteFS.NewWriter instead.
1923
func NewSQLiteWriter(fs *SQLiteFS, path string) *SQLiteWriter {
2024
return &SQLiteWriter{
2125
fs: fs,
@@ -26,6 +30,10 @@ func NewSQLiteWriter(fs *SQLiteFS, path string) *SQLiteWriter {
2630
}
2731

2832
func (w *SQLiteWriter) Write(p []byte) (n int, err error) {
33+
if w.closed {
34+
return 0, errors.New("sqlitefs: write to closed writer")
35+
}
36+
2937
n = len(p)
3038
w.buffer = append(w.buffer, p...)
3139

@@ -84,11 +92,17 @@ func (w *SQLiteWriter) createFileRecord() error {
8492
}
8593

8694
func (w *SQLiteWriter) Close() error {
95+
if w.closed {
96+
return nil
97+
}
98+
8799
for len(w.buffer) > 0 || !w.fileCreated {
88100
err := w.writeFragment()
89101
if err != nil {
90102
return err
91103
}
92104
}
105+
106+
w.closed = true
93107
return nil
94108
}

0 commit comments

Comments
 (0)