package store import ( "context" "database/sql" "errors" "time" ) // Audit appends one audit record. func (s *Store) Audit(ctx context.Context, e AuditEntry) error { _, err := s.db.ExecContext(ctx, `INSERT INTO audit_logs(user_id, username, ip, ua, module, action, target, params, result, cost_ms, created_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)`, e.UserID, e.Username, e.IP, e.UA, e.Module, e.Action, e.Target, e.Params, e.Result, e.CostMS, time.Now().Unix()) return err } // RecentAudit returns the newest audit records. func (s *Store) RecentAudit(ctx context.Context, limit int) ([]map[string]any, error) { if limit <= 0 || limit > 500 { limit = 100 } rows, err := s.db.QueryContext(ctx, `SELECT id, username, ip, module, action, target, result, cost_ms, created_at FROM audit_logs ORDER BY id DESC LIMIT ?`, limit) if err != nil { return nil, err } defer rows.Close() out := make([]map[string]any, 0, limit) for rows.Next() { var id, cost, at int64 var user, ip, module, action, target, result string if err := rows.Scan(&id, &user, &ip, &module, &action, &target, &result, &cost, &at); err != nil { return nil, err } out = append(out, map[string]any{ "id": id, "username": user, "ip": ip, "module": module, "action": action, "target": target, "result": result, "cost_ms": cost, "created_at": at, }) } return out, rows.Err() } // Setting reads one key, returning def when unset. func (s *Store) Setting(ctx context.Context, key, def string) (string, error) { var v string err := s.db.QueryRowContext(ctx, `SELECT value FROM settings WHERE key = ?`, key).Scan(&v) if errors.Is(err, sql.ErrNoRows) { return def, nil } return v, err } // SetSetting writes one key. func (s *Store) SetSetting(ctx context.Context, key, value string) error { _, err := s.db.ExecContext(ctx, `INSERT INTO settings(key, value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`, key, value) return err }