package db import ( "cc/util/log" "github.com/jmoiron/sqlx" ) var ( DB *sqlx.DB // DBPath string = "file:weather.pp?_foreign_keys=1&&_journal_mode=WAL&&mode=rwc" DBPath string = "file:weather.pp?_foreign_keys=1" ) func init() { var err error DB, err = NewSQLiteDB(DBPath) if err != nil { log.L.Fatalf("数据库连接失败: %v", err) } if !IsDBInitialized(DB) { log.L.Info("数据库未初始化,正在初始化...") createTables() initData() } } // 创建表 func createTables() { // 创建天气类型表 weatherTypeTable := ` CREATE TABLE IF NOT EXISTS weather_types ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, description TEXT NOT NULL );` // 创建天气表 weatherTable := ` CREATE TABLE IF NOT EXISTS weathers ( project_id INTEGER PRIMARY KEY, update_at TEXT NOT NULL, weather_type_name TEXT NOT NULL, value TEXT NOT NULL, FOREIGN KEY(project_id) REFERENCES projects(id) );` // 创建位置表 localtionTable := ` CREATE TABLE IF NOT EXISTS localtions ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, code TEXT NOT NULL );` // 创建项目表 projectTable := ` CREATE TABLE IF NOT EXISTS projects ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, code TEXT NOT NULL, user TEXT NOT NULL, description TEXT NOT NULL, localtion_id INTEGER NOT NULL, weather_type_id INTEGER NOT NULL, update_frequency INTEGER NOT NULL, dev BOOLEAN NOT NULL, FOREIGN KEY(localtion_id) REFERENCES localtions(id), FOREIGN KEY(weather_type_id) REFERENCES weather_types(id) );` // 创建表 tables := []string{weatherTypeTable, weatherTable, localtionTable, projectTable} for _, table := range tables { _, err := DB.Exec(table) if err != nil { log.L.Fatalf("创建表失败: %v", err) } } } // 初始化数据 func initData() { // 初始化天气类型 weatherTypes := map[int][]string{ 1: {"now", "实时天气"}, 3: {"3d", "3天预报"}, 7: {"7d", "7天预报"}, 10: {"10d", "10天预报"}, 15: {"15d", "15天预报"}, 30: {"30d", "30天预报"}, 24: {"24h", "24小时预报"}, 72: {"72h", "72小时预报"}, 168: {"168h", "168小时预报"}, } for id, v := range weatherTypes { _, err := DB.Exec("INSERT INTO weather_types (id, name, description) VALUES (?,?,?)", id, v[0], v[1]) if err != nil { log.L.Errorf("初始化天气类型失败: %v", err) } } // 初始化位置 localtions := map[string]string{ "西安": "101010100", "上海": "101020100", } for name, code := range localtions { _, err := DB.Exec("INSERT INTO localtions (name, code) VALUES (?,?)", name, code) if err != nil { log.L.Errorf("初始化位置失败: %v", err) } } }