package store import ( "fmt" "strings" "time" "code.c-base.org/baccenfutter/govote/voting" "code.c-base.org/baccenfutter/govote/voting/quorum" "code.c-base.org/baccenfutter/govote/voting/threshold" "code.c-base.org/baccenfutter/govote/voting/vote" ) // NewVoting writes a new voting into the store. func NewVoting( id string, r string, d time.Time, q quorum.Quorum, t threshold.Threshold, e []string, a bool, ) error { electors := strings.Join(e, " ") if _, err := votingInsert.Exec(id, r, d.String(), q.String(), t.String(), electors, a); err != nil { return err } return nil } // GetVoting takes an id and reads and returns the voting with that ID from the store. func GetVoting(id string) (*voting.Voting, error) { result := votingSelect.QueryRow(id) if result == nil { return nil, fmt.Errorf("not found: %s", id) } var ( err error r string d time.Time q quorum.Quorum t threshold.Threshold e []string a bool dbDeadline string dbQuorum string dbThreshold string dbElectors string ) if err := result.Scan(&r, &dbDeadline, &dbQuorum, &dbThreshold, &dbElectors, &a); err != nil { return nil, err } if d, err = time.Parse("2006-01-02 15:04:05 -0700 MST", dbDeadline); err != nil { return nil, err } if q, err = quorum.FromString(dbQuorum); err != nil { return nil, err } if t, err = threshold.FromString(dbThreshold); err != nil { return nil, err } for _, _e := range strings.Split(dbElectors, " ") { if _e != "" { e = append(e, _e) } } votes, err := getVotes(id) if err != nil { return nil, err } v := voting.NewVotingWithVotes(id, r, d, q, t, e, a, votes) return v, nil } // PlaceVote writes an individual vote to the store. func PlaceVote(id, votingID, elector string, choice vote.Choice) error { if _, err := voteInsert.Exec(id, votingID, elector, choice.String()); err != nil { return err } return nil } func getVotes(id string) ([]vote.Vote, error) { result, err := voteSelect.Query(id) if err != nil { return nil, err } var ( i string e string c vote.Choice ts time.Time dbChoice string dbTimestamp string votes = []vote.Vote{} ) for result.Next() { if err = result.Scan(&i, &e, &dbChoice, &dbTimestamp); err != nil { return nil, err } if c, err = vote.ChoiceFromString(dbChoice); err != nil { return nil, err } if ts, err = time.Parse("2006-01-02 15:04:05", dbTimestamp); err != nil { return nil, err } v := vote.NewVoteWithTimestamp(i, e, c, ts) votes = append(votes, v) } return votes, nil }