Compare commits

...

2 Commits

Author SHA1 Message Date
vilmibm c4c02533e7 town db scripting 2023-03-06 03:07:35 +00:00
vilmibm 8d531936a1 WIP inserting users 2023-03-06 03:04:27 +00:00
3 changed files with 71 additions and 2 deletions

View File

@ -0,0 +1,12 @@
#!/bin/bash
set -e
dbpath="/town/var/town.db"
srcpath="/town/src/town"
rm -f "$dbpath"
sqlite3 < "${srcpath}/sql/create_town_db.sql" "$dbpath"
chown root:admin "$dbpath"
chmod o-r "$dbpath"
chmod g+w "$dbpath"

View File

@ -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),

View File

@ -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 {