summaryrefslogtreecommitdiff
path: root/blavote.go
diff options
context:
space:
mode:
authorJoe Robinson <joe@mumsnet.com>2014-07-21 11:51:34 +0100
committerJoe Robinson <joe@mumsnet.com>2014-07-21 11:51:34 +0100
commit5b1d414ba23937e7fe1eba74547a7acf33e9c5a6 (patch)
treef8fd9b1c9860201a10408c82855ac4a4f8cde1ce /blavote.go
parentc4c2aee4aa4ce2b726f14cb8f91f20801d2e6784 (diff)
Added some error checking
Diffstat (limited to 'blavote.go')
-rw-r--r--blavote.go59
1 files changed, 43 insertions, 16 deletions
diff --git a/blavote.go b/blavote.go
index 9158e1c..857c904 100644
--- a/blavote.go
+++ b/blavote.go
@@ -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