took me a bit to figure out how to do this properly, but i believe it's improved my understanding of how go works
83 lines
2.6 KiB
Go
83 lines
2.6 KiB
Go
package database
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/glebarez/sqlite"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type ContentType uint8
|
|
|
|
const (
|
|
ContentFile ContentType = iota
|
|
ContentPaste
|
|
)
|
|
|
|
type Upload struct {
|
|
ID string `gorm:"column:id;primaryKey" json:"id"`
|
|
Type ContentType `gorm:"column:type;not null;default:0;type:integer" json:"type"`
|
|
Filename string `gorm:"column:filename;not null" json:"-"`
|
|
MIMEType string `gorm:"column:mime_type;not null" json:"mime_type"`
|
|
Size int64 `gorm:"column:size;not null" json:"size"`
|
|
SHA256 []byte `gorm:"column:sha256;type:blob;notnull;index" json:"-"`
|
|
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime" json:"created_at"`
|
|
ExpiresAt *int64 `gorm:"column:expires_at;index" json:"expires_at"` // null means no expiration
|
|
LastAccessedAt int64 `gorm:"column:last_accessed_at;not null;autoCreateTime;index" json:"last_accessed_at"`
|
|
DeleteToken string `gorm:"column:delete_token;not null" json:"-"`
|
|
}
|
|
|
|
type Report struct {
|
|
ID string `gorm:"column:id;primaryKey"`
|
|
UploadID string `gorm:"column:upload_id;not null;index"`
|
|
Reason string `gorm:"column:reason;not null"`
|
|
Upload Upload `gorm:"foreignKey:UploadID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
|
|
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime"`
|
|
}
|
|
|
|
func InitDatabase(path string) (*gorm.DB, error) {
|
|
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{TranslateError: true})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open database: %w", err)
|
|
}
|
|
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("get database handle: %w", err)
|
|
}
|
|
|
|
sqlDB.SetMaxOpenConns(1)
|
|
sqlDB.SetMaxIdleConns(1)
|
|
if err := db.Exec("PRAGMA journal_mode = WAL").Error; err != nil {
|
|
walModeErr := fmt.Errorf("enable database WAL: %w", err)
|
|
return nil, errors.Join(walModeErr, sqlDB.Close())
|
|
}
|
|
if err := db.Exec("PRAGMA foreign_keys = ON").Error; err != nil {
|
|
return nil, fmt.Errorf("enable foreign keys: %w", err)
|
|
}
|
|
|
|
if err := db.AutoMigrate(&Upload{}, &Report{}); err != nil {
|
|
migrationErr := fmt.Errorf("migrate database: %w", err)
|
|
return nil, errors.Join(migrationErr, sqlDB.Close())
|
|
}
|
|
|
|
return db, nil
|
|
}
|
|
|
|
func InsertUpload(db *gorm.DB, upload *Upload) error {
|
|
return db.Create(upload).Error
|
|
}
|
|
|
|
func InsertReport(db *gorm.DB, report *Report) error {
|
|
return db.Omit("Upload").Create(report).Error
|
|
}
|
|
|
|
func GetUploadById(db *gorm.DB, id string) (*Upload, error) {
|
|
var upload Upload
|
|
if err := db.First(&upload, "id = ?", id).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &upload, nil
|
|
}
|