forked from flynn/flynn
/
postgres.go
101 lines (86 loc) · 2.06 KB
/
postgres.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
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
package backend
import (
"io"
"os"
"github.com/flynn/flynn/pkg/postgres"
"github.com/jackc/pgx"
)
var Postgres Backend = pg{}
type pg struct{}
func (pg) Name() string { return "postgres" }
func (p pg) Put(tx *postgres.DBTx, info FileInfo, r io.Reader, append bool) error {
if !append {
if err := tx.QueryRow("UPDATE files SET file_oid = lo_create(0) WHERE file_id = $1 RETURNING file_oid", info.ID).Scan(&info.Oid); err != nil {
return err
}
}
lo, err := tx.LargeObjects()
if err != nil {
return err
}
obj, err := lo.Open(*info.Oid, pgx.LargeObjectModeWrite)
if err != nil {
return err
}
if append {
obj.Seek(info.Size, os.SEEK_SET)
}
if _, err := io.Copy(obj, r); err != nil {
return err
}
return nil
}
func (p pg) Copy(tx *postgres.DBTx, dst, src FileInfo) error {
srcFile, err := p.Open(tx, src, false)
if err != nil {
return err
}
defer srcFile.Close()
return p.Put(tx, dst, srcFile, false)
}
func (p pg) Delete(tx *postgres.DBTx, info FileInfo) error {
if err := tx.Exec("SELECT lo_unlink($1)", info.Oid); err != nil {
return err
}
return tx.Exec("UPDATE files SET file_oid = NULL WHERE file_id = $1", info.ID)
}
func (p pg) Open(tx *postgres.DBTx, info FileInfo, txControl bool) (FileStream, error) {
if info.Oid == nil {
return nil, ErrNotFound
}
lo, err := tx.LargeObjects()
if err != nil {
return nil, err
}
obj, err := lo.Open(*info.Oid, pgx.LargeObjectModeRead)
if err != nil {
return nil, err
}
f := &pgFile{LargeObject: obj, size: info.Size}
if txControl {
f.tx = tx
}
return f, nil
}
type pgFile struct {
*pgx.LargeObject
size int64
sizeRead bool
tx *postgres.DBTx
}
func (f *pgFile) Close() error {
if f.tx != nil {
f.tx.Rollback()
}
return nil
}
func (f *pgFile) Seek(offset int64, whence int) (int64, error) {
// HACK: work around ServeContent length detection, remove when fixed
if offset == 0 && whence == os.SEEK_END {
f.sizeRead = true
return f.size, nil
} else if f.sizeRead && offset == 0 && whence == os.SEEK_SET {
return 0, nil
}
return f.LargeObject.Seek(offset, whence)
}