forked from tildetown/town
WIP inserting users
parent
c0a8c50dbb
commit
8d531936a1
|
@ -9,16 +9,17 @@ CREATE TABLE IF NOT EXISTS users (
|
|||
FOREIGN KEY (signupid) REFERENCES signups(signupid)
|
||||
);
|
||||
|
||||
-- TODO address /should/ be unique but leaving it duplicable for now since i can think of some cases where there might be >1 account for the same human
|
||||
CREATE TABLE IF NOT EXISTS emails (
|
||||
id INTEGER PRIMARY KEY,
|
||||
address TEXT UNIQUE,
|
||||
address TEXT,
|
||||
userid INTEGER,
|
||||
|
||||
FOREIGN KEY (userid) REFERENCES users(userid)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_notes (
|
||||
noteid INTEGER,
|
||||
noteid INTEGER,
|
||||
userid INTEGER,
|
||||
|
||||
PRIMARY KEY (noteid, userid),
|
|
@ -59,6 +59,7 @@ func (n *AdminNote) Insert(db *sql.DB) error {
|
|||
|
||||
type TownUser struct {
|
||||
ID int64
|
||||
Created time.Time
|
||||
Emails []string
|
||||
Username string
|
||||
Notes []AdminNote
|
||||
|
@ -66,6 +67,61 @@ type TownUser struct {
|
|||
IsAdmin bool
|
||||
}
|
||||
|
||||
func (u *TownUser) Insert(db *sql.DB) (err error) {
|
||||
var tx *sql.Tx
|
||||
var stmt *sql.Stmt
|
||||
var result sql.Result
|
||||
var liid int64
|
||||
|
||||
if tx, err = db.Begin(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
u.Created = time.Now()
|
||||
if stmt, err = tx.Prepare(`
|
||||
INSERT INTO notes (created, username, state, admin)
|
||||
VALUES ( ?, ?, ?, ?)`); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if result, err = stmt.Exec(
|
||||
u.Created.Unix(),
|
||||
u.Username,
|
||||
u.State,
|
||||
u.IsAdmin); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if liid, err = result.LastInsertId(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
u.ID = liid
|
||||
|
||||
if len(u.Emails) > 0 {
|
||||
for _, e := range u.Emails {
|
||||
if stmt, err = tx.Prepare(`
|
||||
INSERT INTO emails (address, userid)
|
||||
VALUES (?, ?)`); err != nil {
|
||||
return err
|
||||
}
|
||||
if result, err = stmt.Exec(e, u.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tx.Commit()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ConnectDB() (*sql.DB, error) {
|
||||
db, err := sql.Open("sqlite3", dsn)
|
||||
if err != nil {
|
||||
|
|
Loading…
Reference in New Issue