summaryrefslogtreecommitdiff
path: root/option.go
blob: dd3055df08cf01f9dd9ff8720738015bdb2afc72 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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, id int) (Option, error) {

    args := sqlite3.NamedArgs{"$a": text, "$b": id}
    sql := "SELECT * FROM options WHERE text = $a and poll_id = $b"
    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 + "'")
}