This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
JISQueueing/db/visitor.go

78 lines
2.5 KiB
Go

package db
import (
"JISQueueing/common"
"database/sql"
"errors"
)
//ErrVisitorNotFound indicates that the email does not belong to an existing visitor (new account).
var ErrVisitorNotFound = errors.New("visitor email does not exist")
//GetAllVisitors returns a list of all visitors in our record.
func GetAllVisitors() []common.Visitor {
rows, _ := db.Query("SELECT * FROM clients")
defer rows.Close()
return convertIntoVisitors(rows)
}
//GetVisitor retrieves the visitor with the specified ID in the form of `common.Visitor`.
func GetVisitor(email string) (common.Visitor, error) {
rows, _ := db.Query("SELECT * FROM clients WHERE email=? COLLATE NOCASE", email)
defer rows.Close()
visitors := convertIntoVisitors(rows)
if len(visitors) == 0 {
return common.Visitor{}, ErrVisitorNotFound
}
return visitors[0], nil
}
//NewVisitor saves the provided visitor and returns whether the email is new (first time) or already used (old, and update name).
func NewVisitor(visitor common.Visitor) (bool, common.Visitor) {
exists, editVisitor := EditVisitor(visitor)
if exists {
return false, editVisitor
}
result, _ := db.Exec("INSERT INTO clients (email, name, first_ticket) VALUES (?, ?, ?)", visitor.Email, visitor.Name, -1)
rowsAffected, _ := result.RowsAffected()
return rowsAffected > 0, visitor
}
//EditVisitor updates the provided visitor with the new name associated with the email.
func EditVisitor(visitor common.Visitor) (bool, common.Visitor) {
result, _ := db.Exec("UPDATE clients SET name=? WHERE email=? COLLATE NOCASE", visitor.Name, visitor.Email)
rowsAffected, _ := result.RowsAffected()
updated, _ := GetVisitor(visitor.Email)
return rowsAffected > 0, updated
}
//SetFirstTicket updates the first ticket column for the provided visitor
func SetFirstTicket(visitor common.Visitor) bool {
result, _ := db.Exec("UPDATE clients SET first_ticket=? WHERE email=? COLLATE NOCASE", visitor.FirstTicket, visitor.Email)
rowsAffected, _ := result.RowsAffected()
return rowsAffected > 0
}
//convertIntoVisitors converts the result set from a sql query of a rows of visitors into a []common.Visitor.
func convertIntoVisitors(rows *sql.Rows) []common.Visitor {
visitors := make([]common.Visitor, 0)
for rows.Next() {
var email string
var name string
var firstTicket int
rows.Scan(&email, &name, &firstTicket)
visitor := common.Visitor{
Email: email,
Name: name,
FirstTicket: firstTicket,
}
visitors = append(visitors, visitor)
}
return visitors
}