Completed db rewrite
This commit is contained in:
parent
54d7d14ef9
commit
cf4b8e0119
19 changed files with 481 additions and 276 deletions
|
|
@ -1,43 +1,59 @@
|
|||
package core
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func GetPoll(orm *gorm.DB, user User, id uint) (*Poll, error) {
|
||||
var poll Poll = Poll{
|
||||
ID: id,
|
||||
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
|
||||
}
|
||||
|
||||
if result := orm.Take(&poll); result.Error != nil {
|
||||
return nil, result.Error
|
||||
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
|
||||
}
|
||||
|
||||
fmt.Printf("%+v\n", poll.PlanID)
|
||||
|
||||
return &poll, nil
|
||||
}
|
||||
|
||||
func (p *Poll) SetVote(orm *gorm.DB, user User, option string) error {
|
||||
found := false
|
||||
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, ",")
|
||||
|
||||
for _, opt := range options {
|
||||
if opt == option {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return ErrInvalidOption
|
||||
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)
|
||||
|
||||
if res := orm.Create(Vote{PollID: p.ID, UsernameID: user.Username, Value: option}); res.Error != nil {
|
||||
return res.Error
|
||||
}
|
||||
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue