Notes/file.go
2023-06-22 16:48:31 +02:00

83 lines
1.3 KiB
Go

package main
import (
// External
"github.com/jmoiron/sqlx"
// Standard
"fmt"
"time"
)
type File struct {
ID int
UserID int `db:"user_id"`
NodeID int `db:"node_id"`
Filename string
Size int64
MIME string
MD5 string
Uploaded time.Time
}
func (session Session) AddFile(file *File) (err error) { // {{{
file.UserID = session.UserID
var rows *sqlx.Rows
rows, err = db.Queryx(`
INSERT INTO file(user_id, node_id, filename, size, mime, md5)
VALUES($1, $2, $3, $4, $5, $6)
RETURNING id
`,
file.UserID,
file.NodeID,
file.Filename,
file.Size,
file.MIME,
file.MD5,
)
if err != nil {
return
}
defer rows.Close()
rows.Next()
err = rows.Scan(&file.ID)
fmt.Printf("%#v\n", file)
return
} // }}}
func (session Session) Files(nodeID, fileID int) (files []File, err error) { // {{{
var rows *sqlx.Rows
rows, err = db.Queryx(
`SELECT *
FROM file
WHERE
user_id = $1 AND
node_id = $2 AND
CASE $3::int
WHEN 0 THEN true
ELSE id = $3
END`,
session.UserID,
nodeID,
fileID,
)
if err != nil {
return
}
defer rows.Close()
files = []File{}
for rows.Next() {
file := File{}
if err = rows.StructScan(&file); err != nil {
return
}
files = append(files, file)
}
return
} // }}}
// vim: foldmethod=marker