hatecomputers.club/database/migrate.go

85 lines
1.8 KiB
Go
Raw Normal View History

2024-03-26 18:00:05 -04:00
package database
import (
"log"
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
type Migrator func(*sql.DB) (*sql.DB, error)
func MigrateUsers(dbConn *sql.DB) (*sql.DB, error) {
log.Println("migrating users table")
_, err := dbConn.Exec(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);`)
if err != nil {
return dbConn, err
}
log.Println("creating unique index on users table")
_, err = dbConn.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_users_username ON users (username);`)
if err != nil {
return dbConn, err
}
return dbConn, nil
}
func MigrateApiKeys(dbConn *sql.DB) (*sql.DB, error) {
log.Println("migrating api_keys table")
_, err := dbConn.Exec(`CREATE TABLE IF NOT EXISTS api_keys (
key TEXT PRIMARY KEY,
user_id INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id)
);`)
if err != nil {
return dbConn, err
}
return dbConn, nil
}
func MigrateDNSRecords(dbConn *sql.DB) (*sql.DB, error) {
log.Println("migrating dns_records table")
_, err := dbConn.Exec(`CREATE TABLE IF NOT EXISTS dns_records (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL,
name TEXT NOT NULL,
type TEXT NOT NULL,
content TEXT NOT NULL,
ttl INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id)
);`)
if err != nil {
return dbConn, err
}
return dbConn, nil
}
func Migrate(dbConn *sql.DB) (*sql.DB, error) {
log.Println("migrating database")
migrations := []Migrator{
MigrateUsers,
MigrateApiKeys,
MigrateDNSRecords,
}
for _, migration := range migrations {
dbConn, err := migration(dbConn)
if err != nil {
return dbConn, err
}
}
return dbConn, nil
}