Add DB objects
This commit is contained in:
parent
abd5e2025e
commit
6ec37b83ce
7 changed files with 450 additions and 2 deletions
85
admin/file.go
Normal file
85
admin/file.go
Normal file
|
@ -0,0 +1,85 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
)
|
||||
|
||||
type EFile struct {
|
||||
id int64
|
||||
Path string
|
||||
id_exercice int64
|
||||
Name string
|
||||
Checksum []byte
|
||||
}
|
||||
|
||||
func (e Exercice) GetFiles() ([]EFile, error) {
|
||||
if rows, err := DBQuery("SELECT id_file, path, name, sha1 FROM exercice_files WHERE id_exercice = ?", e.id); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
defer rows.Close()
|
||||
|
||||
var files = make([]EFile, 0)
|
||||
for rows.Next() {
|
||||
var f EFile
|
||||
f.id_exercice = e.id
|
||||
if err := rows.Scan(&f.id, &f.Path, &f.Name, &f.Checksum); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
files = append(files, f)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return files, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (e Exercice) ImportFile(filePath string) (EFile, error) {
|
||||
if fd, err := os.Open(filePath); err != nil {
|
||||
return EFile{}, err
|
||||
} else {
|
||||
defer fd.Close()
|
||||
|
||||
hash := sha1.New()
|
||||
if _, err := io.Copy(hash, fd); err != nil {
|
||||
return EFile{}, err
|
||||
}
|
||||
|
||||
var result []byte
|
||||
return e.AddFile(filePath, path.Base(filePath), hash.Sum(result))
|
||||
}
|
||||
}
|
||||
|
||||
func (e Exercice) AddFile(path string, name string, checksum []byte) (EFile, error) {
|
||||
if res, err := DBExec("INSERT INTO exercice_files (id_exercice, path, name, sha1) VALUES (?, ?, ?, ?)", e.id, path, name, checksum); err != nil {
|
||||
return EFile{}, err
|
||||
} else if fid, err := res.LastInsertId(); err != nil {
|
||||
return EFile{}, err
|
||||
} else {
|
||||
return EFile{fid, path, e.id, name, checksum}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (f EFile) Update() (int64, error) {
|
||||
if res, err := DBExec("UPDATE exercice_files SET id_exercice = ?, path = ?, name = ?, sha1 = ? WHERE id_file = ?", f.id_exercice, f.Path, f.Name, f.Checksum, f.id); err != nil {
|
||||
return 0, err
|
||||
} else if nb, err := res.RowsAffected(); err != nil {
|
||||
return 0, err
|
||||
} else {
|
||||
return nb, err
|
||||
}
|
||||
}
|
||||
|
||||
func (f EFile) Delete() (int64, error) {
|
||||
if res, err := DBExec("DELETE FROM exercice_files WHERE id_file = ?", f.id); err != nil {
|
||||
return 0, err
|
||||
} else if nb, err := res.RowsAffected(); err != nil {
|
||||
return 0, err
|
||||
} else {
|
||||
return nb, err
|
||||
}
|
||||
}
|
Reference in a new issue