diff options
Diffstat (limited to 'blavote.go')
-rw-r--r-- | blavote.go | 59 |
1 files changed, 43 insertions, 16 deletions
@@ -8,12 +8,13 @@ import "os" import "io/ioutil" import "strings" import "strconv" +import "errors" var version string func main() { - version = "0.31" + version = "0.4" //Command line arguments var opts struct { @@ -75,7 +76,7 @@ func main() { fmt.Println(err) } } else if (opts.Remove > 0) { - deletePoll(db, opts.Remove, opts.Username) + err = deletePoll(db, opts.Remove, opts.Username) if (err == nil) { fmt.Print("Poll removed with ID ") @@ -85,11 +86,11 @@ func main() { } } else { - fmt.Println(opts.Args.Rest) vote(db, opts.Username, opts.Args.Rest) - } + } + } func connectDb(name string) (*sqlite3.Conn, error) { @@ -125,21 +126,47 @@ func initTables(db *sqlite3.Conn) { } -func vote(db *sqlite3.Conn, nick string, options []string) { +func vote(db *sqlite3.Conn, nick string, options []string) error { - if pollId, err := strconv.Atoi(options[0]); err == nil { - option := getOptionFromText(db, options[1]) - user := getUserForName(db, nick) - args := sqlite3.NamedArgs{"$a": user.id, "$b": pollId, "$c": option.id} - sql := "INSERT INTO votes (user_id, poll_id, option_id) VALUES ($a, $b, $c)" + pollId, err := strconv.Atoi(options[0]) - err := db.Exec(sql, args) + if (err != nil) { + return errors.New("Poll ID must be a number") + } - if (err != nil ) { - fmt.Print("Failed to vote: ") - fmt.Print(err) - } else { - fmt.Println("Vote added") + poll, err := getPollFromId(db, pollId) + + if (err != nil) { + return err + } + + option, err := getOptionFromText(db, options[1]) + + if (err != nil) { + return err + } + + user := getUserForName(db, nick) + + //Record the user in the DB if they aren't already + if (user.id == 0) { + user, err = createUser(db, nick, false) + + if (err != nil) { + return err } } + + args := sqlite3.NamedArgs{"$a": user.id, "$b": poll.id, "$c": option.id} + sql := "INSERT INTO votes (user_id, poll_id, option_id) VALUES ($a, $b, $c)" + + err = db.Exec(sql, args) + + if (err != nil ) { + fmt.Print("Failed to vote: ") + return err + } else { + fmt.Println("Vote added") + return nil + } }
\ No newline at end of file |