summaryrefslogtreecommitdiff
path: root/user.go
blob: d1ed2616c2faf3359ae73747c1c2040187a2329f (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
package main

import "github.com/mxk/go-sqlite/sqlite3"

type User struct {
    id int
    name string
    isAdmin bool
}

func createUser(db *sqlite3.Conn, name string, isAdmin bool) {

    //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}
    sql := "SELECT * FROM users WHERE id = $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

        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}

}

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}

}