diff options
author | Joe Robinson <joe@mumsnet.com> | 2014-07-18 16:58:51 +0100 |
---|---|---|
committer | Joe Robinson <joe@mumsnet.com> | 2014-07-18 16:58:51 +0100 |
commit | df0a8c9ef163016cf6a6530fb6ac6eddd6b691c5 (patch) | |
tree | 83b62ff9740188563a861abbcdfa097ee3623cc7 | |
parent | 0d0048d532e6b738653d3c4cd6bde36dcb1d6728 (diff) |
check if a user exists before creating it
-rw-r--r-- | user.go | 33 |
1 files changed, 26 insertions, 7 deletions
@@ -1,6 +1,5 @@ package main -import "fmt" import "github.com/mxk/go-sqlite/sqlite3" type User struct { @@ -11,13 +10,16 @@ type User struct { func createUser(db *sqlite3.Conn, name string, isAdmin bool) { - args := sqlite3.NamedArgs{"$a": name, "$b": isAdmin} - sql := "INSERT INTO users (name, admin) VALUES ($a, $b)" - - db.Exec(sql, args) + //Check if a user with this name already exists + if (getUserForName(db, name).id == 0) { + args := sqlite3.NamedArgs{"$a": name, "$b": isAdmin} + sql := "INSERT INTO users (name, admin) VALUES ($a, $b)" + db.Exec(sql, args) + } } + func getUserForId(db *sqlite3.Conn, id int) User { args := sqlite3.NamedArgs{"$a": id} @@ -28,8 +30,6 @@ func getUserForId(db *sqlite3.Conn, id int) User { for ; err == nil ; err = s.Next() { var rowid int s.Scan(&rowid, row) // Assigns 1st column to rowid, the rest to row - fmt.Println(rowid, row) // Prints "1 map[a:1 b:demo c:<nil>]" - fmt.Println(row["name"]) user := User{id:rowid, name:row["name"].(string), isAdmin:row["admin"].(bool)} return user @@ -38,5 +38,24 @@ func getUserForId(db *sqlite3.Conn, id int) User { //If we get here there are no matching users return User{id:0, name:"", isAdmin:false} +} + +func getUserForName(db *sqlite3.Conn, name string) User { + + args := sqlite3.NamedArgs{"$a": name} + sql := "SELECT * FROM users WHERE name = $a" + s, err := db.Query(sql, args) + row := make(sqlite3.RowMap) + + for ; err == nil ; err = s.Next() { + var rowid int + s.Scan(&rowid, row) + + user := User{id:rowid, name:row["name"].(string), isAdmin:row["admin"].(bool)} + return user + } + + //If we get here there are no matching users + return User{id:0, name:"", isAdmin:false} }
\ No newline at end of file |