72 lines
1.6 KiB
Go
72 lines
1.6 KiB
Go
package main
|
||
|
||
import (
|
||
"database/sql"
|
||
"fmt"
|
||
"io/ioutil"
|
||
"log"
|
||
"strings"
|
||
|
||
"github.com/niangaodev/art-code/config"
|
||
)
|
||
|
||
func main() {
|
||
// 初始化数据库连接
|
||
config.InitDB()
|
||
db := config.DB
|
||
defer config.CloseDB()
|
||
|
||
// 读取SQL文件
|
||
sqlFile := "scripts/create_inquiries_tables.sql"
|
||
content, err := ioutil.ReadFile(sqlFile)
|
||
if err != nil {
|
||
log.Fatalf("Error reading SQL file: %v", err)
|
||
}
|
||
|
||
// 分割SQL语句
|
||
statements := strings.Split(string(content), ";")
|
||
|
||
// 执行每一条SQL语句
|
||
for _, stmt := range statements {
|
||
stmt = strings.TrimSpace(stmt)
|
||
if stmt == "" {
|
||
continue
|
||
}
|
||
|
||
_, err := db.Exec(stmt)
|
||
if err != nil {
|
||
// 忽略"表已存在"的错误(虽然我们用了IF NOT EXISTS,但为了保险)
|
||
if !strings.Contains(err.Error(), "already exists") {
|
||
log.Printf("Error executing statement: %s\nError: %v", stmt, err)
|
||
}
|
||
} else {
|
||
// 只打印前50个字符
|
||
displayStmt := stmt
|
||
if len(displayStmt) > 50 {
|
||
displayStmt = displayStmt[:50] + "..."
|
||
}
|
||
fmt.Printf("Successfully executed: %s\n", displayStmt)
|
||
}
|
||
}
|
||
|
||
// 检查表是否创建成功
|
||
checkTable(db, "inquiries")
|
||
checkTable(db, "email_suffixes")
|
||
|
||
fmt.Println("Inquiries tables migration completed successfully!")
|
||
}
|
||
|
||
func checkTable(db *sql.DB, tableName string) {
|
||
var name string
|
||
err := db.QueryRow("SHOW TABLES LIKE ?", tableName).Scan(&name)
|
||
if err != nil {
|
||
if err == sql.ErrNoRows {
|
||
fmt.Printf("Table %s does NOT exist!\n", tableName)
|
||
} else {
|
||
fmt.Printf("Error checking table %s: %v\n", tableName, err)
|
||
}
|
||
} else {
|
||
fmt.Printf("Table %s exists.\n", tableName)
|
||
}
|
||
}
|