diff options
Diffstat (limited to 'poll.go')
-rw-r--r-- | poll.go | 73 |
1 files changed, 73 insertions, 0 deletions
@@ -0,0 +1,73 @@ +package main + +import "github.com/mxk/go-sqlite/sqlite3" + +type Poll struct { + id int + title string + userId int +} + +func addPoll(db *sqlite3.Conn, title string, options []string, nick string) error { + + user := getUserForName(db, nick) + + if (user.id == 0) { + createUser(db, nick, false) + user = getUserForName(db, nick) + } + + args := sqlite3.NamedArgs{"$a": title, "$b": user.id} + sql := "INSERT INTO polls (title, user_id) VALUES ($a, $b)" + + err := db.Exec(sql, args) + + if (err != nil ) { + return err + } + + pollId := db.LastInsertId() + for _,option := range options { + addOption(db, option, pollId) + if (err != nil ) { + return err + } + } + + return nil + +} + +func addOption(db *sqlite3.Conn, text string, pollId int64) error { + + args := sqlite3.NamedArgs{"$a": text, "$b": pollId} + sql := "INSERT INTO options (text, poll_id) VALUES ($a, $b)" + + err := db.Exec(sql, args) + + if (err != nil ) { + return err + } + + return nil +} + +func getPollFromTitle(db *sqlite3.Conn, title string) Poll { + + args := sqlite3.NamedArgs{"$a": title} + sql := "SELECT * FROM polls WHERE title = $a" + s, err := db.Query(sql, args) + row := make(sqlite3.RowMap) + + for ; err == nil ; err = s.Next() { + var rowid int + s.Scan(&rowid, row) // Assigns 1st column to rowid, the rest to row + + poll := Poll{id:rowid, title:row["title"].(string), userId:row["user_id"].(int)} + return poll + } + + //If we get here there are no matching users + return Poll{id:0, title:"", userId:0} + +}
\ No newline at end of file |