package main import ( log "github.com/sirupsen/logrus" "database/sql" _ "github.com/go-sql-driver/mysql" "github.com/denzs/wsjtx-dashboards/shared/wsjtx" ) func handleMysql(result wsjtx.Result) { db, dbDown := dbConn() if dbDown { log.Fatal("cant reach database..") } defer db.Close() stmt, err := db.Prepare("INSERT INTO wsjtx_all_txt(ts, station, callsign, band, mode, report, dxcc, geohash, continent, cqzone, ituzone, rx) VALUES(FROM_UNIXTIME(?),?,?,?,?,?,?,?,?,?,?,?)") defer stmt.Close() _, err = stmt.Exec(result.Timestamp.Unix(), station, result.Call, result.Band, result.Mode, result.Signal, result.Ent.Entity, result.GeoHash, result.Ent.Continent, result.Ent.CQZone, result.Ent.ITUZone, result.Rx) if err != nil { log.WithFields(log.Fields{"err":err.Error()}).Warn("error while executing prepared statement..") } } func init_db() { var cnt int log.Debug("init_db()") db, _ := dbConn() row := db.QueryRow("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_NAME LIKE '%" + mysql_table + "%';") switch err := row.Scan(&cnt); err { case sql.ErrNoRows: log.Error("something went wrong while scanning for existing table structure..") panic(err.Error()) case nil: default: panic(err) } if cnt < 1 { qry := "CREATE TABLE IF NOT EXISTS " + mysql_table + " (" + "ts timestamp NOT NULL," + "station VARCHAR(16) NOT NULL," + "callsign VARCHAR(16) NOT NULL," + "band VARCHAR(10) NOT NULL," + "continent VARCHAR(32) NOT NULL," + "mode VARCHAR(16) NOT NULL," + "dxcc VARCHAR(128) NOT NULL," + "geohash VARCHAR(16) NOT NULL," + "report TINYINT NOT NULL," + "cqzone INT NOT NULL," + "ituzone INT NOT NULL," + "rx TINYINT NOT NULL," + "PRIMARY KEY UC_" + mysql_table + "(ts, station, callsign)," + "INDEX idx_dxcc (dxcc));" log.WithFields(log.Fields{"query":qry}).Debug("creating database..") _, err := db.Exec(qry) if err != nil { log.Error("something went wrong while creating table structure..") panic(err) } } else { log.Info("found existing table..") } } func dbConn() (db *sql.DB, err bool){ //db, er := sql.Open("mysql", mysql_user + ":" + mysql_pass + "@tcp(" + mysql_host + ")/" + mysql_db + "?parseTime=true&time_zone=%27UTC%27") db, er := sql.Open("mysql", mysql_user + ":" + mysql_pass + "@tcp(" + mysql_host + ")/" + mysql_db) if er != nil { log.Error("db not reachable: %s",err) return nil, true } pingerr := db.Ping() if pingerr != nil { log.Error("db not pingable..") return nil, true } return db, false }