database, config, home page, start of upload endpoint
This commit is contained in:
+58
@@ -0,0 +1,58 @@
|
||||
package main
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
func initDatabase(path string) (*gorm.DB, error) {
|
||||
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{})
|
||||
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.AutoMigrate(&Upload{}); 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
|
||||
}
|
||||
Reference in New Issue
Block a user