Notes/file.go

83 lines
1.3 KiB
Go
Raw Normal View History

2023-06-21 23:52:21 +02:00
package main
import (
// External
"github.com/jmoiron/sqlx"
// Standard
"fmt"
"time"
)
type File struct {
ID int
UserID int `db:"user_id"`
2023-06-22 08:28:51 +02:00
NodeID int `db:"node_id"`
2023-06-21 23:52:21 +02:00
Filename string
Size int64
MIME string
MD5 string
Uploaded time.Time
}
2023-06-22 06:52:27 +02:00
func (session Session) AddFile(file *File) (err error) { // {{{
2023-06-21 23:52:21 +02:00
file.UserID = session.UserID
var rows *sqlx.Rows
rows, err = db.Queryx(`
2023-06-22 06:52:27 +02:00
INSERT INTO file(user_id, node_id, filename, size, mime, md5)
VALUES($1, $2, $3, $4, $5, $6)
2023-06-21 23:52:21 +02:00
RETURNING id
`,
file.UserID,
2023-06-22 06:52:27 +02:00
file.NodeID,
2023-06-21 23:52:21 +02:00
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
2023-06-22 06:52:27 +02:00
} // }}}
2023-06-22 16:48:31 +02:00
func (session Session) Files(nodeID, fileID int) (files []File, err error) { // {{{
2023-06-22 06:52:27 +02:00
var rows *sqlx.Rows
rows, err = db.Queryx(
2023-06-22 16:48:31 +02:00
`SELECT *
FROM file
WHERE
user_id = $1 AND
node_id = $2 AND
CASE $3::int
WHEN 0 THEN true
ELSE id = $3
END`,
2023-06-22 06:52:27 +02:00
session.UserID,
nodeID,
2023-06-22 16:48:31 +02:00
fileID,
2023-06-22 06:52:27 +02:00
)
if err != nil {
return
}
defer rows.Close()
2023-06-22 08:28:51 +02:00
files = []File{}
2023-06-22 06:52:27 +02:00
for rows.Next() {
file := File{}
if err = rows.StructScan(&file); err != nil {
return
}
files = append(files, file)
}
return
} // }}}
2023-06-21 23:52:21 +02:00
// vim: foldmethod=marker