package database import ( "log" "database/sql" _ "github.com/mattn/go-sqlite3" ) type Migrator func(*sql.DB) (*sql.DB, error) func AddFriends(dbConn *sql.DB) (*sql.DB, error) { _, err := dbConn.Exec(`CREATE TABLE IF NOT EXISTS frens ( id TEXT PRIMARY KEY, name TEXT );`) if err != nil { return dbConn, err } log.Println("creating unique index on frens table") _, err = dbConn.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_frens_name ON frens (name);`) if err != nil { return dbConn, err } return dbConn, nil } func AddMessages(dbConn *sql.DB) (*sql.DB, error) { _, err := dbConn.Exec(`CREATE TABLE IF NOT EXISTS messages ( id TEXT PRIMARY KEY, fren_id TEXT, message TEXT, time TIMESTAMP, fren_sent BOOLEAN NOT NULL CHECK (fren_sent IN (0, 1)), FOREIGN KEY (fren_id) REFERENCES frens (id) ON DELETE CASCADE );`) if err != nil { return dbConn, err } log.Println("creating time and fren_id index on message table") _, err = dbConn.Exec(`CREATE INDEX IF NOT EXISTS idx_message_timestamp ON messages (time);`) _, err = dbConn.Exec(`CREATE INDEX IF NOT EXISTS idx_message_fren ON messages (fren_id);`) if err != nil { return dbConn, err } return dbConn, nil } func Migrate(dbConn *sql.DB) (*sql.DB, error) { log.Println("migrating database") migrations := []Migrator{ AddFriends, AddMessages, } for _, migration := range migrations { dbConn, err := migration(dbConn) if err != nil { return dbConn, err } } return dbConn, nil }