2019-05-02 12:11:27 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"log"
|
|
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
func initDB() {
|
|
|
|
log.Println("Setting up database...")
|
|
|
|
|
|
|
|
tx, err := db.Begin()
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
defer tx.Rollback()
|
|
|
|
|
|
|
|
_, err = tx.Exec("set foreign_key_checks = 0")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var name string
|
|
|
|
rows, err := db.Query("show tables")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
for rows.Next() {
|
|
|
|
err = rows.Scan(&name)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
_, err = tx.Exec("drop table " + name)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
err = rows.Err()
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
rows.Close()
|
|
|
|
|
|
|
|
_, err = tx.Exec("set foreign_key_checks = 1")
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = tx.Commit()
|
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Println("Database cleaned up")
|
|
|
|
_, err = db.Exec( `CREATE TABLE user (
|
|
|
|
id BIGINT UNSIGNED NOT NULL,
|
|
|
|
user_id VARCHAR(32) NOT NULL,
|
|
|
|
name VARCHAR(80) NOT NULL,
|
|
|
|
guild_id SMALLINT(5),
|
2019-05-02 12:23:32 +02:00
|
|
|
PRIMARY KEY (id)
|
2019-05-02 12:22:00 +02:00
|
|
|
) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`)
|
2019-05-02 12:11:27 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = db.Exec( `CREATE TABLE msg (
|
|
|
|
id BIGINT UNSIGNED NOT NULL,
|
|
|
|
user_id BIGINT UNSIGNED NOT NULL,
|
|
|
|
direction ENUM('incoming', 'outgoing'),
|
|
|
|
text VARCHAR(4096) NOT NULL,
|
|
|
|
FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE CASCADE
|
2019-05-02 12:22:00 +02:00
|
|
|
) ENGINE = InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;`)
|
2019-05-02 12:11:27 +02:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Println("Database set up")
|
|
|
|
}
|
|
|
|
|