69 lines
2.5 KiB
Go
69 lines
2.5 KiB
Go
package sqlite
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"git.zaynet.fr/DoGaMa/DoGaMa-serv/internal/importexport"
|
|
)
|
|
|
|
func (r *Repository) BeginImport(ctx context.Context, value importexport.Import, actorID string) error {
|
|
_, err := r.db.ExecContext(ctx, `INSERT INTO imports(id, requested_by, status, format, relative_stage_path, created_at, expires_at) VALUES (?, ?, 'staging', ?, ?, ?, ?)`, value.ID, actorID, value.Format, value.RelativeStagePath, r.now().UTC().Format(time.RFC3339Nano), value.ExpiresAt)
|
|
if err != nil {
|
|
return fmt.Errorf("begin import: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *Repository) CompleteImport(ctx context.Context, value importexport.Import) error {
|
|
result, err := r.db.ExecContext(ctx, `UPDATE imports SET status='validated', detected_type=?, confidence=?, file_count=?, expanded_size_bytes=?, completed_at=? WHERE id=? AND status='staging'`, value.DetectedType, value.Confidence, value.FileCount, value.ExpandedSizeBytes, r.now().UTC().Format(time.RFC3339Nano), value.ID)
|
|
if err != nil {
|
|
return fmt.Errorf("complete import: %w", err)
|
|
}
|
|
changed, _ := result.RowsAffected()
|
|
if changed != 1 {
|
|
return importexport.ErrInvalidInput
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *Repository) FailImport(ctx context.Context, id, code string) error {
|
|
_, err := r.db.ExecContext(ctx, `UPDATE imports SET status='failed', error_code=?, completed_at=? WHERE id=? AND status='staging'`, code, r.now().UTC().Format(time.RFC3339Nano), id)
|
|
if err != nil {
|
|
return fmt.Errorf("fail import: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *Repository) ExpireImports(ctx context.Context, now string) ([]string, error) {
|
|
tx, err := r.db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("begin import expiry: %w", err)
|
|
}
|
|
defer func() { _ = tx.Rollback() }()
|
|
rows, err := tx.QueryContext(ctx, `SELECT relative_stage_path FROM imports WHERE status IN ('staging', 'validated') AND expires_at<=?`, now)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list expired imports: %w", err)
|
|
}
|
|
var paths []string
|
|
for rows.Next() {
|
|
var value string
|
|
if err := rows.Scan(&value); err != nil {
|
|
rows.Close()
|
|
return nil, err
|
|
}
|
|
paths = append(paths, value)
|
|
}
|
|
if err := rows.Close(); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err := tx.ExecContext(ctx, `UPDATE imports SET status='expired', completed_at=? WHERE status IN ('staging', 'validated') AND expires_at<=?`, now, now); err != nil {
|
|
return nil, fmt.Errorf("expire imports: %w", err)
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
return nil, fmt.Errorf("commit import expiry: %w", err)
|
|
}
|
|
return paths, nil
|
|
}
|