TaskData.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. package Task
  2. import (
  3. "ColdVerify_local/conf"
  4. "ColdVerify_local/lib"
  5. "ColdVerify_local/logs"
  6. "encoding/json"
  7. "fmt"
  8. "github.com/astaxie/beego/cache"
  9. _ "github.com/astaxie/beego/cache/redis"
  10. "github.com/beego/beego/v2/adapter/orm"
  11. orm2 "github.com/beego/beego/v2/client/orm"
  12. "github.com/go-sql-driver/mysql"
  13. _ "github.com/go-sql-driver/mysql"
  14. "strconv"
  15. "strings"
  16. "time"
  17. )
  18. const (
  19. Temperature = "Temperature"
  20. Humidity = "Humidity"
  21. )
  22. // 模板
  23. type TaskData struct {
  24. Id int `orm:"column(ID);size(11);auto;pk"`
  25. T_id string `orm:"size(256);null"` // 标题
  26. T_t float32 `orm:"size(10);null"` // 温度
  27. T_rh float32 `orm:"size(10);null"` // 湿度
  28. T_time time.Time `orm:"type(timestamp);null;"` // 采集时间
  29. CreateTime time.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now_add 第一次保存时才设置时间 UpdateTime time.Time `orm:"column(update_time);type(timestamp);null;auto_now"` //auto_now 每次 model 保存时都会对时间自动更新
  30. }
  31. func (t *TaskData) TableName() string {
  32. return "task_data" // 数据库名称 // ************** 替换 FormulaList **************
  33. }
  34. var redisCache_TaskData cache.Cache
  35. func init() {
  36. //orm2.Debug = true
  37. config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
  38. "redis_"+"TaskData", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
  39. logs.Println(config)
  40. var err error
  41. redisCache_TaskData, err = cache.NewCache("redis", config)
  42. if err != nil || redisCache_TaskData == nil {
  43. errMsg := "failed to init redis"
  44. logs.Println(errMsg, err)
  45. }
  46. }
  47. type TaskDataJPG struct {
  48. State int `json:"state"` //1:生成中 2:已完成 3:失败
  49. Msg string `json:"msg"`
  50. Url string `json:"url"` //url
  51. }
  52. // ---------------- Redis -------------------
  53. // Redis_Set(m.T_sn,m) // Redis 更新缓存
  54. func Redis_TaskDataJPG_Set(key string, r TaskDataJPG) (err error) {
  55. //json序列化
  56. str, err := json.Marshal(r)
  57. if err != nil {
  58. logs.Error(lib.FuncName(), err)
  59. return
  60. }
  61. err = redisCache_TaskData.Put(key, str, 5*time.Minute)
  62. if err != nil {
  63. logs.Println("set key:", key, ",value:", str, err)
  64. }
  65. return
  66. }
  67. // if r,is :=Redis_Get(T_sn);is{
  68. // return r,nil
  69. // }
  70. func Redis_TaskDataJPG_Get(key string) (r TaskDataJPG, is bool) {
  71. if redisCache_TaskData.IsExist(key) {
  72. logs.Println("找到key:", key)
  73. v := redisCache_TaskData.Get(key)
  74. json.Unmarshal(v.([]byte), &r)
  75. return r, true
  76. }
  77. logs.Println("没有 找到key:", key)
  78. return TaskDataJPG{}, false
  79. }
  80. func Redis_TaskDataJPG_Del(key string) (err error) {
  81. err = redisCache_TaskData.Delete(key)
  82. return
  83. }
  84. // 创建数据库 Device.CREATE_TaskData("")
  85. func CREATE_TaskData(alias_name, T_task_id string) bool {
  86. o := orm2.NewOrmUsingDB(alias_name)
  87. sql := "DROP TABLE IF EXISTS `z_task_data_" + T_task_id + "`"
  88. o.Raw(sql).Exec()
  89. sql = "CREATE TABLE IF NOT EXISTS `z_task_data_" + T_task_id + "` ( " +
  90. " `ID` int(11) NOT NULL AUTO_INCREMENT," +
  91. " `t_sn` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL," +
  92. " `t_id` varchar(256) DEFAULT NULL," +
  93. " `t_t` float(6, 1) NULL DEFAULT NULL," +
  94. " `t_rh` float(6, 1) NULL DEFAULT NULL," +
  95. " `t_time` datetime(0) NULL DEFAULT NULL," +
  96. " PRIMARY KEY (`ID`) USING BTREE," +
  97. " KEY `t_sn` (`t_sn`)," +
  98. " KEY `t_id` (`t_id`)," +
  99. " KEY `t_time` (`t_time`)" +
  100. ") ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;"
  101. _, err := o.Raw(sql).Exec()
  102. if err != nil {
  103. return false
  104. }
  105. //sqlIndex := "ALTER TABLE `z_task_data_" + T_task_id + "` add unique index(`t_sn`,`t_id`,`t_time`);"
  106. //logs.Debug(sqlIndex)
  107. //o.Raw(sqlIndex).Exec()
  108. return true
  109. }
  110. // ---------------- 特殊方法 -------------------
  111. // 清空
  112. func Truncate_TaskData(alias_name, T_task_id string) bool {
  113. o := orm2.NewOrmUsingDB(alias_name)
  114. sql := "truncate table z_task_data_" + T_task_id
  115. logs.Println(sql)
  116. _, err := o.Raw(sql).Exec()
  117. if err != nil {
  118. // 数据库表不存在,则创建数据库
  119. if err.(*mysql.MySQLError).Number == 1146 {
  120. CREATE_TaskData(alias_name, T_task_id)
  121. return true
  122. }
  123. logs.Error(lib.FuncName(), err)
  124. return false
  125. }
  126. return true
  127. }
  128. type TaskData_ struct {
  129. ID int `orm:"column(ID);size(100);null"` // ID
  130. T_sn string `orm:"column(t_sn);size(256);null"` // sn
  131. T_id string `orm:"column(t_id);size(256);null"` // 标题
  132. T_t float32 `orm:"column(t_t);size(10);null"` // 温度
  133. T_rh float32 `orm:"column(t_rh);size(10);null"` // 湿度
  134. T_time string `orm:"column(t_times);null;"` // 采集时间
  135. T_Certificate_sn string `orm:"size(256);null"` // 证书编号
  136. }
  137. type TaskDataClass_ struct {
  138. T_sn string `orm:"column(t_sn);size(256);null"` // 标题
  139. T_id string `orm:"column(t_id);size(256);null"` // 名称
  140. }
  141. func Read_TaskData_ById_List(T_task_id string, SN string, T_id string, Time_start_ string, Time_end_ string, page int, page_z int) ([]TaskData_, int64) {
  142. o := orm.NewOrm()
  143. var maps []TaskData_
  144. var maps_z []orm2.ParamsList
  145. pagez := page_z
  146. var offset int
  147. if page <= 1 {
  148. offset = 0
  149. } else {
  150. page -= 1
  151. offset = page * pagez
  152. }
  153. sql_condition := ""
  154. if len(Time_start_) > 1 {
  155. sql_condition += " AND t_time >= '" + Time_start_ + "'"
  156. }
  157. if len(Time_end_) > 1 {
  158. sql_condition += " AND t_time <= '" + Time_end_ + "'"
  159. }
  160. if len(T_id) > 0 {
  161. sql_condition += " AND t_id = '" + T_id + "'"
  162. }
  163. if len(SN) > 0 {
  164. sql_condition += " AND t_sn = '" + SN + "'"
  165. }
  166. if len(sql_condition) > 0 {
  167. sql_condition = " WHERE " + strings.TrimLeft(sql_condition, " AND ")
  168. }
  169. sql := "SELECT COUNT(ID) FROM z_task_data_" + T_task_id + sql_condition
  170. fmt.Println(sql)
  171. _, err := o.Raw(sql).ValuesList(&maps_z)
  172. if err != nil {
  173. return maps, 0
  174. }
  175. if len(maps_z) == 0 {
  176. return maps, 0
  177. }
  178. //fmt.Println("maps_z;",maps_z[0][0])
  179. sql = "SELECT ID,t_sn,t_id,t_t,t_rh,DATE_FORMAT(t_time,'%Y-%m-%d %H:%i:%s') AS t_times,t_time FROM z_task_data_" + T_task_id + sql_condition + " ORDER BY t_time DESC"
  180. if page_z != 9999 {
  181. sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(pagez)
  182. }
  183. fmt.Println(sql)
  184. _, err = o.Raw(sql).QueryRows(&maps)
  185. if err != nil {
  186. logs.Error(lib.FuncName(), err)
  187. }
  188. //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
  189. key, _ := strconv.Atoi(maps_z[0][0].(string))
  190. return maps, int64(key)
  191. }
  192. func Read_TaskData_ById_List_AES(T_task_id string, SN string, T_id string, Time_start_ string, Time_end_ string, page int, page_z int) ([]TaskData_, int64) {
  193. o := orm.NewOrm()
  194. var maps []TaskData_
  195. var maps_z []orm2.ParamsList
  196. pagez := page_z
  197. var offset int
  198. if page <= 1 {
  199. offset = 0
  200. } else {
  201. page -= 1
  202. offset = page * pagez
  203. }
  204. sql_condition := ""
  205. if len(Time_start_) > 1 {
  206. sql_condition += " AND t_time >= '" + Time_start_ + "'"
  207. }
  208. if len(Time_end_) > 1 {
  209. sql_condition += " AND t_time <= '" + Time_end_ + "'"
  210. }
  211. if len(T_id) > 0 {
  212. sql_condition += " AND t_id = '" + T_id + "'"
  213. }
  214. if len(SN) > 0 {
  215. sql_condition += " AND t_sn = '" + SN + "'"
  216. }
  217. if len(sql_condition) > 0 {
  218. sql_condition = " WHERE " + strings.TrimLeft(sql_condition, " AND ")
  219. }
  220. sql := "SELECT COUNT(ID) FROM z_task_data_" + T_task_id + sql_condition
  221. fmt.Println(sql)
  222. _, err := o.Raw(sql).ValuesList(&maps_z)
  223. if err != nil {
  224. return maps, 0
  225. }
  226. if len(maps_z) == 0 {
  227. return maps, 0
  228. }
  229. //fmt.Println("maps_z;",maps_z[0][0])
  230. sql = "SELECT ID,t_sn,t_id,t_t,t_rh,DATE_FORMAT(t_time,'%Y-%m-%d %H:%i:%s') AS t_times,t_time FROM z_task_data_" + T_task_id + sql_condition + " ORDER BY t_time"
  231. if page_z != 9999 {
  232. sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(pagez)
  233. }
  234. fmt.Println(sql)
  235. _, err = o.Raw(sql).QueryRows(&maps)
  236. if err != nil {
  237. logs.Error(lib.FuncName(), err)
  238. }
  239. //value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", cnt), 64)
  240. key, _ := strconv.Atoi(maps_z[0][0].(string))
  241. return maps, int64(key)
  242. }
  243. func Read_TaskData_ById_List_(T_task_id string, SN string) []TaskData_ {
  244. o := orm.NewOrm()
  245. var maps []TaskData_
  246. sql_condition := ""
  247. sql_condition += " t_sn ='" + SN + "'"
  248. //fmt.Println("maps_z;",maps_z[0][0])
  249. sql := "SELECT ID,t_sn,t_id,t_t,t_rh,DATE_FORMAT(t_time,'%Y-%m-%d %H:%i') AS t_times,t_time FROM z_task_data_" + T_task_id + " WHERE " + sql_condition + " ORDER BY t_time "
  250. fmt.Println(sql)
  251. _, err := o.Raw(sql).QueryRows(&maps)
  252. if err != nil {
  253. logs.Error(lib.FuncName(), err)
  254. return maps
  255. }
  256. return maps
  257. }
  258. func Read_TaskData_ById_ClassList(T_task_id string) []TaskDataClass_ {
  259. o := orm.NewOrm()
  260. var maps []TaskDataClass_
  261. //fmt.Println("maps_z;",maps_z[0][0])
  262. //sql := "SELECT DISTINCT t_sn,t_id FROM z_task_data_" + T_task_id + " ORDER BY t_id "
  263. //sql := "SELECT DISTINCT t_sn FROM z_task_data_" + T_task_id + " ORDER BY t_id "
  264. sql := "SELECT t_sn,t_id FROM z_task_data_" + T_task_id + " GROUP BY t_sn,t_id ORDER BY t_id+0 "
  265. fmt.Println(sql)
  266. _, err := o.Raw(sql).QueryRows(&maps)
  267. if err != nil {
  268. // 数据库表不存在,则创建数据库
  269. if err.(*mysql.MySQLError).Number == 1146 {
  270. CREATE_TaskData(conf.Local_AliasName, T_task_id)
  271. }
  272. logs.Error(lib.FuncName(), err)
  273. return maps
  274. }
  275. return maps
  276. }
  277. func Read_TaskData_sn(T_task_id string) []TaskDataClass_ {
  278. o := orm.NewOrm()
  279. var maps []TaskDataClass_
  280. sql := "SELECT DISTINCT t_sn FROM z_task_data_" + T_task_id + " ORDER BY t_sn "
  281. fmt.Println(sql)
  282. _, err := o.Raw(sql).QueryRows(&maps)
  283. if err != nil {
  284. logs.Error(lib.FuncName(), err)
  285. return maps
  286. }
  287. return maps
  288. }
  289. func Update_TaskData_ByT_sn(T_task_id, T_sn, T_id string) error {
  290. o := orm.NewOrm()
  291. // 修改id
  292. sql := "UPDATE z_task_data_" + T_task_id + " SET `t_id` = '" + T_id + "' WHERE `t_sn` = '" + T_sn + "'"
  293. logs.Println(sql)
  294. _, err := o.Raw(sql).Exec()
  295. if err != nil {
  296. logs.Error(lib.FuncName(), err)
  297. return err
  298. }
  299. return nil
  300. }
  301. func Delete_TaskData_ByT_sn(T_task_id, T_sn string) error {
  302. o := orm.NewOrm()
  303. // 修改id
  304. sql := "DELETE FROM z_task_data_" + T_task_id + " WHERE `t_sn` = '" + T_sn + "'"
  305. logs.Println(sql)
  306. _, err := o.Raw(sql).Exec()
  307. if err != nil {
  308. logs.Error(lib.FuncName(), err)
  309. return err
  310. }
  311. return nil
  312. }
  313. // 添加
  314. func Add_TaskData(T_task_id string, T_sn string, T_id string, T_t string, T_rh string, T_time string) bool {
  315. o := orm2.NewOrm()
  316. tx, err := o.Begin()
  317. if err != nil {
  318. logs.Error("start the transaction failed")
  319. return false
  320. }
  321. // 开始插入数据
  322. //
  323. //sql := "INSERT INTO z_task_data_" + T_task_id + " (`t_sn`, `t_id`, `t_time`) " +
  324. // "VALUES ('" + T_sn + "', " + T_id + ", '" + T_time + "') " +
  325. // "ON DUPLICATE KEY UPDATE t_t=" + T_t + ", t_rh="+ T_rh +";"
  326. // 去重复数据
  327. sql := "DELETE FROM z_task_data_" + T_task_id + " WHERE " + " t_id = '" + T_id + "' AND " + " t_sn = '" + T_sn + "' " + "AND t_time = '" + T_time + "' "
  328. // 这里有时间优化 用于一次 prepare 多次 exec,以提高批量执行的速度
  329. //fmt.Println(sql)
  330. res, err := tx.Raw(sql).Exec()
  331. if err != nil {
  332. tx.Rollback()
  333. logs.Error(lib.FuncName(), err)
  334. return false
  335. }
  336. res.RowsAffected()
  337. sql = "INSERT INTO z_task_data_" + T_task_id + " (`t_sn`, `t_id`, `t_t`, `t_rh`, `t_time`) " +
  338. "VALUES ('" + T_sn + "', '" + T_id + "', " + T_t + "," + T_rh + ", '" + T_time + "')"
  339. // 更新数据
  340. //sql := "INSERT INTO z_task_data_" + T_task_id + " (`t_sn`, `t_id`, `t_t`, `t_rh`, `t_time`) " +
  341. // "VALUES ('" + T_sn + "', " + T_id + ", " + T_t + "," + T_rh + ", '" + T_time + "')" +
  342. // "on duplicate key update `t_t`=" + T_t + ",`t_rh`=" + T_rh
  343. //fmt.Println(sql)
  344. res, err = tx.Raw(sql).Exec()
  345. if err != nil {
  346. tx.Rollback()
  347. logs.Error(lib.FuncName(), err)
  348. return false
  349. }
  350. tx.Commit()
  351. //fmt.Println("mysql row affected nums: ", num)
  352. return true
  353. }
  354. // 创建唯一索引
  355. func Create_Unique_Index(T_task_id string) error {
  356. // 创建索引
  357. o := orm.NewOrm()
  358. createIndexSql := "ALTER TABLE z_task_data_" + T_task_id + " ADD CONSTRAINT unique_index_t_sn_t_id_t_time UNIQUE (t_sn, t_id, t_time);"
  359. //fmt.Println(sql)
  360. _, err := o.Raw(createIndexSql).Exec()
  361. if err != nil && !strings.Contains(err.Error(), "Duplicate key name 'unique_index_t_sn_t_id_t_time'") {
  362. logs.Error(lib.FuncName(), err)
  363. return err
  364. }
  365. return nil
  366. }
  367. // 删除唯一索引
  368. func Delete_Unique_Index(T_task_id string) error {
  369. // 创建索引
  370. o := orm.NewOrm()
  371. // 删除索引
  372. deleteIndexSql := "ALTER TABLE z_task_data_" + T_task_id + " DROP INDEX unique_index_t_sn_t_id_t_time;"
  373. //fmt.Println(sql)
  374. _, err := o.Raw(deleteIndexSql).Exec()
  375. if err != nil {
  376. logs.Error(lib.FuncName(), err)
  377. return err
  378. }
  379. return nil
  380. }
  381. func Adds_TaskData(T_task_id string, valueStrings []string) error {
  382. o := orm.NewOrm()
  383. // 插入数据
  384. sql := "INSERT INTO z_task_data_" + T_task_id + " (`t_sn`, `t_id`, `t_t`, `t_rh`, `t_time`) VALUES"
  385. sql += strings.Join(valueStrings, ",")
  386. sql += " ON DUPLICATE KEY UPDATE t_t = VALUES(t_t), t_rh = VALUES(t_rh)"
  387. //fmt.Println(sql)
  388. _, err := o.Raw(sql).Exec()
  389. if err != nil {
  390. logs.Error(lib.FuncName(), err)
  391. return err
  392. }
  393. //fmt.Println("mysql row affected nums: ", num)
  394. return nil
  395. }
  396. // 修改
  397. func Up_TaskData(T_task_id string, Id string, T_t string, T_rh string, T_time string) bool {
  398. o := orm.NewOrm()
  399. SET_str := " SET "
  400. if len(T_t) > 0 {
  401. SET_str = SET_str + " t_t = " + T_t + " ,"
  402. }
  403. if len(T_rh) > 0 {
  404. SET_str = SET_str + " t_rh = " + T_rh + " ,"
  405. }
  406. if len(T_time) > 0 {
  407. SET_str = SET_str + " t_time = '" + T_time + "' ,"
  408. }
  409. if len(SET_str) > 7 {
  410. SET_str = SET_str[:(len(SET_str) - 1)]
  411. }
  412. // 开始插入数据 UPDATE `cold_verify`.`Z_TaskData_d8qMyeXLzIxn` SET `t_t` = 20.2 WHERE `ID` = 69
  413. sql := "UPDATE z_task_data_" + T_task_id + " " + SET_str + " WHERE ID = " + Id
  414. // 这里有时间优化 用于一次 prepare 多次 exec,以提高批量执行的速度
  415. //fmt.Println(sql)
  416. res, err := o.Raw(sql).Exec()
  417. if err != nil {
  418. logs.Error(lib.FuncName(), err)
  419. return false
  420. }
  421. res.RowsAffected()
  422. //fmt.Println("mysql row affected nums: ", num)
  423. return true
  424. }
  425. // 删除
  426. func Del_TaskData(T_task_id string, Id string) bool {
  427. o := orm.NewOrm()
  428. // 开始插入数据 UPDATE `cold_verify`.`Z_TaskData_d8qMyeXLzIxn` SET `t_t` = 20.2 WHERE `ID` = 69
  429. sql := "DELETE FROM z_task_data_" + T_task_id + " WHERE ID = " + Id
  430. // 这里有时间优化 用于一次 prepare 多次 exec,以提高批量执行的速度
  431. logs.Println(sql)
  432. res, err := o.Raw(sql).Exec()
  433. if err != nil {
  434. logs.Error(lib.FuncName(), err)
  435. return false
  436. }
  437. res.RowsAffected()
  438. //fmt.Println("mysql row affected nums: ", num)
  439. return true
  440. }
  441. func Read_TaskData_ByT_id(T_task_id string, Id string) (t_sn string, err error) {
  442. o := orm.NewOrm()
  443. // 开始插入数据 UPDATE `cold_verify`.`Z_TaskData_d8qMyeXLzIxn` SET `t_t` = 20.2 WHERE `ID` = 69
  444. sql := "SELECT t_sn FROM z_task_data_" + T_task_id + " WHERE t_id = '" + Id + "'"
  445. // 这里有时间优化 用于一次 prepare 多次 exec,以提高批量执行的速度
  446. logs.Println(sql)
  447. err = o.Raw(sql).QueryRow(&t_sn)
  448. if err != nil {
  449. logs.Error(lib.FuncName(), err)
  450. return t_sn, err
  451. }
  452. //fmt.Println("mysql row affected nums: ", num)
  453. return t_sn, err
  454. }
  455. func Read_TaskData_ByT_sn(T_task_id string, sn string) (t_id string, err error) {
  456. o := orm.NewOrm()
  457. // 开始插入数据 UPDATE `cold_verify`.`Z_TaskData_d8qMyeXLzIxn` SET `t_t` = 20.2 WHERE `ID` = 69
  458. sql := "SELECT t_id FROM z_task_data_" + T_task_id + " WHERE t_sn = '" + sn + "'"
  459. // 这里有时间优化 用于一次 prepare 多次 exec,以提高批量执行的速度
  460. logs.Println(sql)
  461. err = o.Raw(sql).QueryRow(&t_id)
  462. if err != nil {
  463. logs.Error(lib.FuncName(), err)
  464. return t_id, err
  465. }
  466. //fmt.Println("mysql row affected nums: ", num)
  467. return t_id, err
  468. }
  469. // 添加
  470. func Del_TaskData_t_id(T_task_id string, Id string) bool {
  471. o := orm.NewOrm()
  472. // 开始插入数据 UPDATE `cold_verify`.`Z_TaskData_d8qMyeXLzIxn` SET `t_t` = 20.2 WHERE `ID` = 69
  473. sql := "DELETE FROM z_task_data_" + T_task_id + " WHERE t_id = '" + Id + "'"
  474. // 这里有时间优化 用于一次 prepare 多次 exec,以提高批量执行的速度
  475. logs.Println(sql)
  476. res, err := o.Raw(sql).Exec()
  477. if err != nil {
  478. logs.Error(lib.FuncName(), err)
  479. return false
  480. }
  481. res.RowsAffected()
  482. //fmt.Println("mysql row affected nums: ", num)
  483. return true
  484. }
  485. // 检查导出表总数
  486. func Check_TaskData_Num(T_task_id string) bool {
  487. o1 := orm2.NewOrmUsingDB(conf.Local_AliasName)
  488. o2 := orm2.NewOrmUsingDB(conf.Server_AliasName)
  489. var maps_z1, maps_z2 []orm2.ParamsList
  490. sql := "SELECT COUNT(ID) FROM z_task_data_" + T_task_id
  491. fmt.Println(sql)
  492. _, err := o1.Raw(sql).ValuesList(&maps_z1)
  493. if err != nil {
  494. return false
  495. }
  496. _, err = o2.Raw(sql).ValuesList(&maps_z2)
  497. if err != nil {
  498. return false
  499. }
  500. if len(maps_z1) != len(maps_z2) {
  501. return false
  502. }
  503. return true
  504. }
  505. // 检查导出表总数
  506. func Check_TaskData_Num_Verify1(T_task_id string) bool {
  507. o1 := orm2.NewOrmUsingDB(conf.Local_AliasName)
  508. o2 := orm2.NewOrmUsingDB(conf.Verify1_AliasName)
  509. var maps_z1, maps_z2 []orm2.ParamsList
  510. sql := "SELECT COUNT(ID) FROM z_task_data_" + strings.ToLower(T_task_id)
  511. fmt.Println(sql)
  512. _, err := o1.Raw(sql).ValuesList(&maps_z1)
  513. if err != nil {
  514. return false
  515. }
  516. sql2 := "SELECT COUNT(ID) FROM Z_TaskData_" + T_task_id
  517. _, err = o2.Raw(sql2).ValuesList(&maps_z2)
  518. if err != nil {
  519. return false
  520. }
  521. if len(maps_z1) != len(maps_z2) {
  522. return false
  523. }
  524. return true
  525. }
  526. func Read_TaskData_Num(T_task_id string) int {
  527. o1 := orm2.NewOrmUsingDB(conf.Local_AliasName)
  528. var maps_z []orm2.ParamsList
  529. sql := "SELECT COUNT(ID) FROM z_task_data_" + T_task_id
  530. fmt.Println(sql)
  531. _, err := o1.Raw(sql).ValuesList(&maps_z)
  532. if err != nil {
  533. logs.Error(lib.FuncName(), err)
  534. return 0
  535. }
  536. key, _ := strconv.Atoi(maps_z[0][0].(string))
  537. return key
  538. }
  539. func Dump_TaskData(T_task_id, root, password, url_port, database, sql_file string) (string, error) {
  540. // url_port 127.0.0.1:3306
  541. // mysql8.0 以上加 --column-statistics=0
  542. // mysqldump --column-statistics=0 -uroot -proot -h127.0.0.1 -P3306 cold_verify Z_TaskData_ixEfo5zk2Oeb > /Data/Z_TaskData_ixEfo5zk2Oeb.sql
  543. v := Read_Local_Mysql_Version()
  544. host_port := strings.Split(url_port, ":")
  545. table_name := "z_task_data_" + T_task_id
  546. org := "mysqldump "
  547. if v >= 8 {
  548. org += "--column-statistics=0 "
  549. }
  550. //--no-create-info 只导出数据,而不添加 CREATE TABLE 语句。
  551. //--single-transaction 在备份库的时候并不锁定数据表
  552. //--add-locks:在每个表导出之前增加LOCK TABLES并且之后UNLOCK TABLE。(默认为打开状态,使用--skip-add-locks取消选项)
  553. //--compact:压缩模式,产生更少的输出;
  554. org = org + fmt.Sprintf("-u%s -p%s -h%s -P%s --no-create-info --set-gtid-purged=OFF --skip-add-locks --compact --quick %s %s > %s ",
  555. root, password, host_port[0], host_port[1], database, table_name, sql_file)
  556. logs.Println(org)
  557. _, err := lib.Command(org)
  558. if err != nil {
  559. logs.Error(lib.FuncName(), err)
  560. }
  561. return org, err
  562. }
  563. func Dump_TaskData_Verify(T_task_id, root, password, url_port, database, sql_file string) (string, error) {
  564. // url_port 127.0.0.1:3306
  565. // mysql8.0 以上加 --column-statistics=0
  566. // mysqldump --column-statistics=0 -uroot -proot -h127.0.0.1 -P3306 cold_verify Z_TaskData_ixEfo5zk2Oeb > /Data/Z_TaskData_ixEfo5zk2Oeb.sql
  567. v := Read_Local_Mysql_Version()
  568. host_port := strings.Split(url_port, ":")
  569. table_name := "Z_TaskData_" + T_task_id
  570. org := "mysqldump "
  571. if v >= 8 {
  572. org += "--column-statistics=0 "
  573. }
  574. //--no-create-info 只导出数据,而不添加 CREATE TABLE 语句。
  575. //--single-transaction 在备份库的时候并不锁定数据表
  576. //--add-locks:在每个表导出之前增加LOCK TABLES并且之后UNLOCK TABLE。(默认为打开状态,使用--skip-add-locks取消选项)
  577. //--compact:压缩模式,产生更少的输出;
  578. org = org + fmt.Sprintf("-u%s -p%s -h%s -P%s --no-create-info --set-gtid-purged=OFF --skip-add-locks --compact --quick %s %s > %s ",
  579. root, password, host_port[0], host_port[1], database, table_name, sql_file)
  580. logs.Println(org)
  581. _, err := lib.Command(org)
  582. if err != nil {
  583. logs.Error(lib.FuncName(), err)
  584. }
  585. return org, err
  586. }
  587. func Insert_TaskData(root, password, url_port, database, sql_file string) (string, error) {
  588. // url_port 127.0.0.1:3306
  589. // mysql -u root -p root -h127.0.0.1 -P3306 cold_verify_local < /data/Z_TaskData_ixEfo5zk2Oeb.sql
  590. host_port := strings.Split(url_port, ":")
  591. org := fmt.Sprintf("mysql -u%s -p%s -h%s -P%s %s < %s",
  592. root, password, host_port[0], host_port[1], database, sql_file)
  593. logs.Println(org)
  594. _, err := lib.Command(org)
  595. if err != nil {
  596. logs.Error(lib.FuncName(), err)
  597. }
  598. return org, err
  599. }
  600. func Read_Local_Mysql_Version() int {
  601. o := orm2.NewOrmUsingDB(conf.Local_AliasName)
  602. var params []orm2.Params
  603. o.Raw("select version();").Values(&params)
  604. version, _ := strconv.Atoi(params[0]["version()"].(string)[0:1])
  605. return version
  606. }
  607. func Import_TaskData(T_task_id string, offset, pagez int) bool {
  608. var maps []TaskData_
  609. serverOrm := orm2.NewOrmUsingDB(conf.Server_AliasName)
  610. localOrm := orm2.NewOrmUsingDB(conf.Local_AliasName)
  611. tb_name := "z_task_data_" + T_task_id
  612. // 开从先上版查询数据
  613. sql := "select `ID`, `t_sn`, `t_id`, `t_t`, `t_rh`, DATE_FORMAT(t_time,'%Y-%m-%d %H:%i:%s') AS t_times from " + tb_name + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(pagez)
  614. logs.Println(sql)
  615. _, err := serverOrm.Raw(sql).QueryRows(&maps)
  616. if err != nil {
  617. logs.Error(lib.FuncName(), err)
  618. return false
  619. }
  620. values := []string{}
  621. for _, row := range maps {
  622. // 处理数据
  623. values = append(values, fmt.Sprintf("('%s',%d,%v,%v,'%s')", row.T_sn, row.T_id, row.T_t, row.T_rh, row.T_time))
  624. }
  625. // 向本地版插入数据
  626. sql = "INSERT IGNORE INTO " + tb_name + "( `t_sn`, `t_id`, `t_t`, `t_rh`, `t_time`) VALUES " + strings.Join(values, ",")
  627. //logs.Println(sql)
  628. _, err = localOrm.Raw(sql).Exec()
  629. if err != nil {
  630. logs.Error(lib.FuncName(), err)
  631. return false
  632. }
  633. return true
  634. }
  635. // InsertTaskData 添加设备数据
  636. func InsertTaskData(T_task_id string, d TaskData_) {
  637. o := orm.NewOrm()
  638. var maps TaskData_
  639. sql := fmt.Sprintf("SELECT * FROM z_task_data_%s where t_time='%s' and t_id = '%s' and t_sn = '%s'", T_task_id, d.T_time, d.T_id, d.T_sn)
  640. err := o.Raw(sql).QueryRow(&maps)
  641. if err != nil && err.Error() != orm.ErrNoRows.Error() {
  642. logs.Error(lib.FuncName(), err)
  643. }
  644. // 添加
  645. if maps.ID == 0 {
  646. sqlStatement := fmt.Sprintf("insert into z_task_data_%s(t_sn, t_id, t_t, t_rh, t_time) value('%s','%s',%f,%f,'%s')", T_task_id, d.T_sn, d.T_id, d.T_t, d.T_rh, d.T_time)
  647. _, err = o.Raw(sqlStatement).Exec()
  648. if err != nil {
  649. logs.Error(lib.FuncName(), err)
  650. }
  651. return
  652. }
  653. //已经存在该条目,更新
  654. sqlStatement := fmt.Sprintf("update z_task_data_%s set t_t = %f,t_rh = %f where t_time= '%s' and t_id = '%s' and t_sn = '%s'", T_task_id, d.T_t, d.T_rh, d.T_time, d.T_id, d.T_sn)
  655. _, err = o.Raw(sqlStatement).Exec()
  656. if err != nil {
  657. logs.Error(lib.FuncName(), err)
  658. }
  659. }
  660. // DeleteTaskDataByTimeRange 删除时间范围内的数据
  661. func DeleteTaskDataByTimeRange(T_task_id, sn string, id string, start, end string) {
  662. sqlStatement := fmt.Sprintf("delete from z_task_data_%s where t_time between '%s' and '%s' and t_id = '%s' and t_sn = '%s'", T_task_id, start, end, id, sn)
  663. o := orm.NewOrm()
  664. exec, err := o.Raw(sqlStatement).Exec()
  665. if err != nil {
  666. fmt.Println(err.Error())
  667. }
  668. affected, _ := exec.RowsAffected()
  669. fmt.Printf("从%s~%s时间段删除了%d条数据", start, end, affected)
  670. }
  671. // UpdateTaskDataTemperatureAndHumidityRandom 随机更新
  672. func UpdateTaskDataTemperatureAndHumidityRandom(T_task_id, sn, id, startTime, endTime string, ttMax, ttMin, trhMax, trhMin int) {
  673. //sql语句
  674. sqlStatement := fmt.Sprintf("update z_task_data_%s set t_t = t_t + FLOOR(%d + RAND() * (%d - %d + 1)) /100.0, t_rh = t_rh + FLOOR(%d + RAND() * (%d - %d + 1)) /100.0 where t_time BETWEEN '%s' AND '%s' and t_id = '%s' and t_sn = '%s'", T_task_id, ttMin, ttMax, ttMin, trhMin, trhMax, trhMin, startTime, endTime, id, sn)
  675. o := orm.NewOrm()
  676. exec, err := o.Raw(sqlStatement).Exec()
  677. if err != nil {
  678. fmt.Println("执行错误:", sqlStatement)
  679. }
  680. affected, _ := exec.RowsAffected()
  681. fmt.Println("执行更新行数:", affected)
  682. }
  683. // UpdateTaskDataTemperatureAndHumidity 更新设备探头数据温湿度
  684. func UpdateTaskDataTemperatureAndHumidity(T_task_id, sn, id, startTime, endTime string, temperature, humidity float64) {
  685. sqlStatement := fmt.Sprintf("update z_task_data_%s set t_t = t_t + %f , t_rh = t_rh + %f where t_id = '%s' and t_sn = '%s' and t_time BETWEEN '%s' and '%s'", T_task_id, temperature, humidity, id, sn, startTime, endTime)
  686. o := orm.NewOrm()
  687. exec, err := o.Raw(sqlStatement).Exec()
  688. if err != nil {
  689. fmt.Println(err.Error())
  690. }
  691. affected, err := exec.RowsAffected()
  692. if err != nil {
  693. fmt.Println(err.Error())
  694. }
  695. fmt.Printf("影响了%d行\n", affected)
  696. }
  697. // UpdateTaskData 更新设备探头数据
  698. func UpdateTaskData(T_task_id, sn, id string, old, newO TaskData_) {
  699. sqlStatement := fmt.Sprintf("update z_task_data_%s set t_t = %f , t_rh = %f where t_sn = '%s' and t_id = '%s' and t_t = %f and t_rh = %f and t_time= '%s'", T_task_id, newO.T_t, newO.T_rh, sn, id, old.T_t, old.T_rh, old.T_time)
  700. fmt.Println("执行SQL:", sqlStatement)
  701. o := orm.NewOrm()
  702. exec, err := o.Raw(sqlStatement).Exec()
  703. if err != nil {
  704. fmt.Println("执行错误:", sqlStatement, err.Error())
  705. }
  706. affected, _ := exec.RowsAffected()
  707. fmt.Println("执行更新行数:", affected)
  708. }
  709. // 查询温度最小值 最大值
  710. func Read_TaskData_T_Min_Max(T_task_id string, SN string, T_id string, Time_start_ string, Time_end_ string) (minT, maxT float64) {
  711. o := orm.NewOrm()
  712. sql_condition := ""
  713. if len(Time_start_) > 1 {
  714. sql_condition += " AND t_time >= '" + Time_start_ + "'"
  715. }
  716. if len(Time_end_) > 1 {
  717. sql_condition += " AND t_time <= '" + Time_end_ + "'"
  718. }
  719. if len(T_id) > 0 {
  720. sql_condition += " AND t_id = '" + T_id + "'"
  721. }
  722. if len(SN) > 0 {
  723. sql_condition += " AND t_sn = '" + SN + "'"
  724. }
  725. if len(sql_condition) > 0 {
  726. sql_condition = " WHERE " + strings.TrimLeft(sql_condition, " AND ")
  727. }
  728. //fmt.Println("maps_z;",maps_z[0][0])
  729. sql := "SELECT MIN(t_t) AS min_t, MAX(t_t) AS max_t FROM z_task_data_" + T_task_id + sql_condition
  730. fmt.Println(sql)
  731. err := o.Raw(sql).QueryRow(&minT, &maxT)
  732. if err != nil {
  733. logs.Error(lib.FuncName(), err)
  734. }
  735. return
  736. }
  737. // UpdateTaskDataTemperatureAndHumidityByGeometric 更新设备探头数据温湿度 等比缩放
  738. func UpdateTaskDataTemperatureAndHumidityByGeometric(T_task_id, sn, id, startTime, endTime string, temperature, humidity float64) {
  739. sqlStatement := fmt.Sprintf("update z_task_data_%s set t_t = t_t * %f , t_rh = t_rh * %f where t_id = '%s' and t_sn = '%s' and t_time BETWEEN '%s' and '%s'", T_task_id, temperature, humidity, id, sn, startTime, endTime)
  740. o := orm.NewOrm()
  741. exec, err := o.Raw(sqlStatement).Exec()
  742. if err != nil {
  743. fmt.Println(err.Error())
  744. }
  745. affected, err := exec.RowsAffected()
  746. if err != nil {
  747. fmt.Println(err.Error())
  748. }
  749. fmt.Printf("影响了%d行\n", affected)
  750. }
  751. func Read_TaskData_T_Min_Max_Time_Min_Max(T_task_id string, SN []string, T_id []string, Time_start_ string, Time_end_ string) (minT, maxT float64, minTime, maxTime time.Time) {
  752. o := orm.NewOrm()
  753. sql_condition := ""
  754. if len(Time_start_) > 1 {
  755. sql_condition += " AND t_time >= '" + Time_start_ + "'"
  756. }
  757. if len(Time_end_) > 1 {
  758. sql_condition += " AND t_time <= '" + Time_end_ + "'"
  759. }
  760. if len(T_id) > 0 || len(SN) > 0 {
  761. sql_condition += " AND t_id in (" + strings.Join(T_id, ",") + ") OR t_sn in (" + strings.Join(SN, ",") + ")"
  762. }
  763. if len(sql_condition) > 0 {
  764. sql_condition = " WHERE " + strings.TrimLeft(sql_condition, " AND ")
  765. }
  766. //fmt.Println("maps_z;",maps_z[0][0])
  767. sql := "SELECT MIN(t_t) AS min_t, MAX(t_t) AS max_t,MIN(t_time) AS min_time, MAX(t_time) AS max_time FROM z_task_data_" + T_task_id + sql_condition
  768. fmt.Println(sql)
  769. err := o.Raw(sql).QueryRow(&minT, &maxT, &minTime, &maxTime)
  770. if err != nil {
  771. logs.Error(lib.FuncName(), err)
  772. }
  773. return
  774. }
  775. // 获取线上设备数据
  776. func Read_DeviceData_T_Min_Max_Time_Min_Max(T_sn, T_id string, Time_start_ string, Time_end_ string) (minT, maxT float64, minTime, maxTime time.Time) {
  777. o := orm2.NewOrmUsingDB(conf.Server_AliasName)
  778. sql_condition := ""
  779. if len(Time_start_) > 1 {
  780. sql_condition += " AND t_time >= '" + Time_start_ + "'"
  781. }
  782. if len(Time_end_) > 1 {
  783. sql_condition += " AND t_time <= '" + Time_end_ + "'"
  784. }
  785. sql_condition += " AND t_id = '" + T_id + "'"
  786. if len(sql_condition) > 0 {
  787. sql_condition = " WHERE " + strings.TrimLeft(sql_condition, " AND ")
  788. }
  789. //fmt.Println("maps_z;",maps_z[0][0])
  790. sql := "SELECT MIN(t_t) AS min_t, MAX(t_t) AS max_t,MIN(t_time) AS min_time, MAX(t_time) AS max_time FROM z_devicedata_" + T_sn + sql_condition
  791. fmt.Println(sql)
  792. err := o.Raw(sql).QueryRow(&minT, &maxT, &minTime, &maxTime)
  793. if err != nil {
  794. logs.Error(lib.FuncName(), err)
  795. }
  796. return
  797. }
  798. func Read_TaskData_ByIds_List(T_task_id string, SN []string, T_id []string, Time_start_ string, Time_end_ string) []TaskData {
  799. o := orm.NewOrm()
  800. var maps []TaskData
  801. sql_condition := ""
  802. if len(Time_start_) > 1 {
  803. sql_condition += " AND t_time >= '" + Time_start_ + "'"
  804. }
  805. if len(Time_end_) > 1 {
  806. sql_condition += " AND t_time <= '" + Time_end_ + "'"
  807. }
  808. if len(T_id) > 0 || len(SN) > 0 {
  809. sql_condition += " AND (t_id in (" + strings.Join(T_id, ",") + ") OR t_sn in (" + strings.Join(SN, ",") + "))"
  810. }
  811. if len(sql_condition) > 0 {
  812. sql_condition = " WHERE " + strings.TrimLeft(sql_condition, " AND ")
  813. }
  814. //fmt.Println("maps_z;",maps_z[0][0])
  815. sql := "SELECT ID,t_sn,t_id,t_t,t_rh,t_time FROM z_task_data_" + T_task_id + sql_condition + " ORDER BY t_time"
  816. fmt.Println(sql)
  817. _, err := o.Raw(sql).QueryRows(&maps)
  818. if err != nil {
  819. logs.Error(lib.FuncName(), err)
  820. }
  821. return maps
  822. }
  823. // 按照 t_id 分组数据
  824. func GroupDataByTID(data []TaskData) map[string][]TaskData {
  825. groupedData := make(map[string][]TaskData)
  826. for _, d := range data {
  827. groupedData[d.T_id] = append(groupedData[d.T_id], d)
  828. }
  829. return groupedData
  830. }
  831. // 删除的重复数据
  832. func DeleteDeduplicate(T_task_id string) (int64, error) {
  833. localOrm := orm2.NewOrmUsingDB(conf.Local_AliasName)
  834. tb_name := "z_task_data_" + T_task_id
  835. var cnt int64
  836. // 创建临时表
  837. sqlCreate := "CREATE TABLE `tmp_table` AS (SELECT MIN(`ID`) AS `min_id` FROM " + tb_name + " GROUP BY `t_sn`,`t_id`,`t_time`);"
  838. _, err := localOrm.Raw(sqlCreate).Exec()
  839. if err != nil {
  840. logs.Error(lib.FuncName(), err)
  841. return cnt, err
  842. }
  843. sqlDelete := "DELETE FROM " + tb_name + " WHERE `ID` NOT IN (SELECT `min_id` FROM `tmp_table`);"
  844. res, err := localOrm.Raw(sqlDelete).Exec()
  845. if err != nil {
  846. logs.Error(lib.FuncName(), err)
  847. return cnt, err
  848. }
  849. cnt, _ = res.RowsAffected()
  850. sqlDrop := "DROP TABLE `tmp_table`;"
  851. _, err = localOrm.Raw(sqlDrop).Exec()
  852. if err != nil {
  853. logs.Error(lib.FuncName(), err)
  854. return cnt, err
  855. }
  856. return cnt, nil
  857. }
  858. func CheckTableExist(alias_name, T_task_id string) bool {
  859. o := orm2.NewOrmUsingDB(alias_name)
  860. sql := "select count(ID) from z_task_data_" + T_task_id
  861. _, err := o.Raw(sql).Exec()
  862. if err != nil {
  863. // 数据库表不存在,则创建数据库
  864. logs.Error(lib.FuncName(), err)
  865. if err.(*mysql.MySQLError).Number == 1146 {
  866. return false
  867. }
  868. }
  869. return true
  870. }
  871. // 修改auto_increment的初始值
  872. func UpdateAUTO_INCREMENT(alias_name, T_task_id string) error {
  873. o := orm2.NewOrmUsingDB(alias_name)
  874. var max_id int
  875. sql := "select max(ID) from z_task_data_" + T_task_id
  876. err := o.Raw(sql).QueryRow(&max_id)
  877. if err != nil {
  878. logs.Error(lib.FuncName(), err)
  879. return err
  880. }
  881. // ALTER TABLE z_task_data_lg9v2zpfem7b AUTO_INCREMENT = 39905;
  882. sql = "ALTER TABLE z_task_data_" + T_task_id + " AUTO_INCREMENT = " + strconv.Itoa(max_id+1)
  883. _, err = o.Raw(sql).Exec()
  884. if err != nil {
  885. logs.Error(lib.FuncName(), err)
  886. return err
  887. }
  888. return nil
  889. }