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

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

type User struct {
    id int64
    name string
    isAdmin bool
}

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

    user := getUserForName(db, name)

    //Check if a user with this name already exists
    if (user.id == 0) {
        args := sqlite3.NamedArgs{"$a": name, "$b": isAdmin}
        sql := "INSERT INTO users (name, admin) VALUES ($a, $b)"

        err := db.Exec(sql, args)

        return User{id:db.LastInsertId(), name:name, isAdmin:isAdmin}, err
    } else {
        return user, nil
    }

}

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 int64
        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 int64
        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}

}