go: Separate invitation database code into a separate file

pull/6/head
Luther Wen Xu 2019-10-10 17:32:38 +07:00
parent 6b3761d98e
commit 7fed3d8dd3
Signed by: chanbakjsd
GPG Key ID: B7D77E3E9D102B70
2 changed files with 46 additions and 42 deletions

@ -12,7 +12,6 @@ var db *sql.DB
var errNotFound = errors.New("db: the requested entry was not found")
var errAlreadyExists = errors.New("db: attempting to write to an entry that already exists")
var errInviteUsed = errors.New("db: the requested invite has already been used")
func init() {
var err error
@ -25,44 +24,3 @@ func init() {
panic(err)
}
}
func getInviteOwner(inviteCode string) (string, error) {
rows, err := db.Query("SELECT owner, used FROM invite WHERE code=?", inviteCode)
if err != nil {
return "", err
}
if rows.Next() {
var owner string
var used bool
err := rows.Scan(&owner, &used)
if err != nil {
return "", err
}
if used {
return "", errInviteUsed
}
return owner, nil
}
return "", errNotFound
}
func setInviteOwner(inviteCode, owner string) error {
_, err := getInviteOwner(inviteCode)
if err == nil {
return errAlreadyExists
}
if err != errNotFound {
return err
}
_, err = db.Exec("INSERT INTO invite(code, owner, used) VALUES(?,?,?)", inviteCode, owner, false)
return err
}
func useInvite(inviteCode string) error {
owner, err := getInviteOwner(inviteCode)
if err != nil {
return err
}
_, err = db.Exec("REPLACE INTO invite(code, owner, used) VALUES(?,?,?)", inviteCode, owner, true)
return err
}

@ -0,0 +1,46 @@
package main
import "errors"
var errInviteUsed = errors.New("db: the requested invite has already been used")
func getInviteOwner(inviteCode string) (string, error) {
rows, err := db.Query("SELECT owner, used FROM invite WHERE code=?", inviteCode)
if err != nil {
return "", err
}
if rows.Next() {
var owner string
var used bool
err := rows.Scan(&owner, &used)
if err != nil {
return "", err
}
if used {
return "", errInviteUsed
}
return owner, nil
}
return "", errNotFound
}
func setInviteOwner(inviteCode, owner string) error {
_, err := getInviteOwner(inviteCode)
if err == nil {
return errAlreadyExists
}
if err != errNotFound {
return err
}
_, err = db.Exec("INSERT INTO invite(code, owner, used) VALUES(?,?,?)", inviteCode, owner, false)
return err
}
func useInvite(inviteCode string) error {
owner, err := getInviteOwner(inviteCode)
if err != nil {
return err
}
_, err = db.Exec("REPLACE INTO invite(code, owner, used) VALUES(?,?,?)", inviteCode, owner, true)
return err
}