package main import "github.com/mxk/go-sqlite/sqlite3" import "errors" type Option struct { id int64 text string pollId int64 numVotes int64 } func getOptionFromText(db*sqlite3.Conn, text string) (Option, error) { args := sqlite3.NamedArgs{"$a": text} sql := "SELECT * FROM options WHERE text = $a" s, err := db.Query(sql, args) row := make(sqlite3.RowMap) 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)} 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 '" + 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 + "'") }