51 lines
816 B
Go
51 lines
816 B
Go
|
package models
|
||
|
|
||
|
import (
|
||
|
"database/sql"
|
||
|
"errors"
|
||
|
)
|
||
|
|
||
|
type User struct {
|
||
|
Username string
|
||
|
}
|
||
|
|
||
|
type UserModel struct {
|
||
|
DB *sql.DB
|
||
|
}
|
||
|
|
||
|
// Insert
|
||
|
func (m *UserModel) Insert(username string, password string) (int, error) {
|
||
|
stmt := `INSERT INTO users (username, password, created)
|
||
|
VALUES(?, ?, UTC_TIMESTAMP())`
|
||
|
|
||
|
result, err := m.DB.Exec(stmt, username, password)
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
id, err := result.LastInsertId()
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
return int(id), nil
|
||
|
}
|
||
|
|
||
|
// Get
|
||
|
func (m *UserModel) Get(id int) (User, error) {
|
||
|
stmt := "SELECT id, username FROM users WHERE id = ?"
|
||
|
|
||
|
var u User
|
||
|
|
||
|
err := m.DB.QueryRow(stmt, id).Scan(&u.Username)
|
||
|
if err != nil {
|
||
|
if errors.Is(err, sql.ErrNoRows) {
|
||
|
return User{}, ErrNoRecord
|
||
|
} else {
|
||
|
return User{}, err
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return u, nil
|
||
|
}
|