diff options
Diffstat (limited to 'option.go')
-rw-r--r-- | option.go | 57 |
1 files changed, 55 insertions, 2 deletions
@@ -4,9 +4,10 @@ import "github.com/mxk/go-sqlite/sqlite3" import "errors" type Option struct { - id int + id int64 text string pollId int64 + numVotes int64 } func getOptionFromText(db*sqlite3.Conn, text string) (Option, error) { @@ -17,7 +18,7 @@ func getOptionFromText(db*sqlite3.Conn, text string) (Option, error) { row := make(sqlite3.RowMap) for ; err == nil ; err = s.Next() { - var rowid int + var rowid int64 s.Scan(&rowid, row) // Assigns 1st column to rowid, the rest to row option := Option{id:rowid, text:row["text"].(string), pollId:row["poll_id"].(int64)} @@ -27,4 +28,56 @@ func getOptionFromText(db*sqlite3.Conn, text string) (Option, error) { //If we get here there are no matching options return Option{id:0, text:"", pollId:0}, errors.New("No option found matching '" + text + "'") +} + +func getVotesForOption(db*sqlite3.Conn, option Option) (Option, error) { + args := sqlite3.NamedArgs{"$a": option.id, "$b": option.pollId} + sql := "SELECT count(*) FROM votes WHERE option_id = $a AND poll_id = $b" + s, err := db.Query(sql, args) + + for ; err == nil ; err = s.Next() { + var votes int64 + s.Scan(&votes) // Assigns 1st column to rowid, the rest to row + + option = Option{id:option.id, text:option.text, pollId:option.pollId, numVotes:votes} + return option, nil + } + + //If we get here there are no matching options + return Option{id:0, text:"", pollId:0}, errors.New("No option found matching '" + option.text + "'") +} + +func getOptionsForPoll(db*sqlite3.Conn, poll Poll) ([]Option, error) { + args := sqlite3.NamedArgs{"$a": poll.id} + sql := "SELECT count(*) FROM options WHERE poll_id = $a" + s, err := db.Query(sql, args) + + var numOptions int64 + + //Get the number of votes first so we can make the right size array + for ; err == nil ; err = s.Next() { + s.Scan(&numOptions) // Assigns 1st column to rowid, the rest to row + } + + var options = make([]Option, numOptions) + + sql = "SELECT * FROM options WHERE poll_id = $a" + s, err = db.Query(sql, args) + row := make(sqlite3.RowMap) + id := 0 + + for ; err == nil ; err = s.Next() { + var rowid int64 + s.Scan(&rowid, row) // Assigns 1st column to rowid, the rest to row + + option := Option{id:rowid, text:row["text"].(string), pollId:row["poll_id"].(int64)} + options[id] = option + id++ + } + + return options, err + + + //If we get here there are no matching options + // return Option{id:0, text:"", pollId:0}, errors.New("No option found matching '" + option.text + "'") }
\ No newline at end of file |