package main import "github.com/mxk/go-sqlite/sqlite3" import "fmt" type Poll struct { id int64 title string userId int64 } func addPoll(db *sqlite3.Conn, title string, options []string, nick string) (int64, 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 0, err } pollId := db.LastInsertId() for _,option := range options { addOption(db, option, pollId) if (err != nil ) { return 0, err } } return pollId, 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 int64 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"].(int64)} return poll } //If we get here there are no matching users return Poll{id:0, title:"", userId:0} } func getPollFromId(db *sqlite3.Conn, id int) Poll { args := sqlite3.NamedArgs{"$a": id} sql := "SELECT * FROM polls WHERE id = $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 poll := Poll{id:rowid, title:row["title"].(string), userId:row["user_id"].(int64)} return poll } //If we get here there are no matching users return Poll{id:0, title:"", userId:0} } func deletePoll(db *sqlite3.Conn, id int, nick string) error { user := getUserForName(db, nick) poll := getPollFromId(db, id) if (user.isAdmin || poll.userId == user.id) { if (poll.id == 0) { return nil } else { sql := "DELETE FROM polls WHERE id = $a" args := sqlite3.NamedArgs{"$a": id} db.Exec(sql, args) return nil } } else { fmt.Println("denied") return nil } }