This commit is contained in:
xkm
2025-11-12 19:55:29 +08:00
commit deec440038
7 changed files with 319 additions and 0 deletions

30
db.go Normal file
View File

@@ -0,0 +1,30 @@
package main
import (
"context"
"database/sql"
"log"
"os"
)
func openDB() (*sql.DB, error) {
dsn := os.Getenv("MYSQL_DSN")
if dsn == "" {
log.Fatal("MYSQL_DSN is empty!")
}
return sql.Open("mysql", dsn)
}
func migrate(ctx context.Context, db *sql.DB) error {
ddl := `
CREATE TABLE IF NOT EXISTS students (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
age INT NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;`
_, err := db.ExecContext(ctx, ddl)
return err
}