package core import ( "database/sql" "fmt" "slices" "strings" ) func (p *Poll) Create(db *sql.DB) error { row := db.QueryRow( "INSERT INTO polls(plan_id, options) VALUES(?,?) RETURNING id", p.PlanId, p.Options, ) if err := row.Scan(&p.Id); err != nil { return fmt.Errorf("Unable to create new poll for plan %d: %w", p.PlanId, err) } return nil } func PollGet(db *sql.DB, user User, id uint) (*Poll, error) { var poll Poll row := db.QueryRow("SELECT id,plan_id,options FROM polls WHERE id=?", id) if err := row.Scan(&poll.Id, &poll.PlanId, &poll.Options); err != nil { return nil, err } return &poll, nil } func PollsList(db *sql.DB, plan_id int) ([]Poll, error) { var polls []Poll rows, err := db.Query("SELECT id,plan_id,options FROM polls WHERE plan_id=?", plan_id) if err != nil { return polls, fmt.Errorf("Unable to query polls for plan %d: %w", plan_id, err) } defer rows.Close() for rows.Next() { var poll Poll if err := rows.Scan(&poll.Id, &poll.PlanId, &poll.Options); err != nil { return nil, fmt.Errorf("Unable to scan polls for plan %d: %w", plan_id, err) } polls = append(polls, poll) } return polls, nil } func (p *Poll) SetVote(db *sql.DB, member Member, option string) error { options := strings.Split(p.Options, ",") if !slices.Contains(options, option) { return fmt.Errorf("%s is not a valid option (%s): %w", option, options, ErrInvalidOption) } _, err := db.Exec("INSERT INTO votes(poll_id,member_id,value) VALUES (?,?,?)", p.Id, member.Id, option) return err }