DBManager.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. //
  2. // DBManager.swift
  3. // O2OA
  4. //
  5. // Created by FancyLou on 2019/9/16.
  6. // Copyright © 2019 O2OA. All rights reserved.
  7. //
  8. import FMDB
  9. import CocoaLumberjack
  10. import Promises
  11. class DBManager {
  12. static let DB_NAME = "O2_FMDB.db"
  13. static let shared: DBManager = {
  14. return DBManager()
  15. }()
  16. var queue: FMDatabaseQueue
  17. private init() {
  18. var docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
  19. docPath?.append("/\(DBManager.DB_NAME)")
  20. self.queue = FMDatabaseQueue(path: docPath)
  21. let tableCreate = CreateTables(dbQueue: self.queue)
  22. tableCreate.createTables()
  23. }
  24. // MARK: - o2 CloudFile 的操作
  25. func queryCloudFile(fileId: String) -> Promise<O2CloudFileInfo> {
  26. return Promise { fulfill, reject in
  27. let sql = "SELECT * FROM \(CreateTables.TBALE_NAME_O2_CLOUD_FILE) WHERE fileid = '\(fileId)'"
  28. self.queue.inDatabase({ (db) in
  29. if let resultSet = db?.executeQuery(sql, withArgumentsIn: nil) {
  30. if resultSet.next() {
  31. let fileInfo = O2CloudFileInfo()
  32. fileInfo.fileId = resultSet.string(forColumn: "fileid")
  33. fileInfo.fileName = resultSet.string(forColumn: "filename")
  34. fileInfo.filePath = resultSet.string(forColumn: "filepath")
  35. fileInfo.fileExt = resultSet.string(forColumn: "fileext")
  36. fulfill(fileInfo)
  37. } else {
  38. reject(O2DBError.EmptyResultError)
  39. }
  40. resultSet.close()
  41. } else {
  42. reject(O2DBError.ExecuteError)
  43. }
  44. })
  45. }
  46. }
  47. func insertCloudFile(info: O2CloudFileInfo) -> Promise<Bool> {
  48. return Promise { fulfill, reject in
  49. let sql = "insert into \(CreateTables.TBALE_NAME_O2_CLOUD_FILE) (fileid, filename, filepath, fileext) values (?, ?, ?, ?)"
  50. self.queue.inDatabase { (db) in
  51. if let result = db?.executeUpdate(sql, withArgumentsIn: [info.fileId!, info.fileName!, info.filePath!, info.fileExt ?? ""]) {
  52. fulfill(result)
  53. } else {
  54. reject(O2DBError.ExecuteError)
  55. }
  56. }
  57. }
  58. }
  59. // MARK: - o2 通讯录收藏相关的操作
  60. func insertContactData(_ person:PersonV2,_ ownerid:String) {
  61. let sSql = "select count(*) from \(CreateTables.TABLE_NAME_O2_CONTACT_FAV) where `id` = \(String(describing: person.id!)) and `ownerid` = '\(ownerid)'"
  62. let sql = "insert into \(CreateTables.TABLE_NAME_O2_CONTACT_FAV) (`id`,`distinguishedName`,`employee`,`genderType`,`lastLoginAddress`,`lastLoginClient`,`lastLoginTime`,`mail`,`mobile`,`name`,`changePasswordTime`,`superior`,`signature`,`pinyin`,`pinyinInitial`,`qq`,`unique`,`updateTime`,`weixin`,`officePhone`,`boardDate`,`birthday`,`orderNumber`,`ownerid`) values ('\(String(describing: person.id!))','\(String(describing: person.distinguishedName!))','\(String(describing: person.employee ?? ""))','\(String(describing: person.genderType ?? ""))','\(String(describing: person.lastLoginAddress ?? ""))','\(String(describing: person.lastLoginClient ?? ""))','\(String(describing: person.lastLoginTime ?? ""))','\(String(describing: person.mail ?? ""))','\(String(describing: person.mobile ?? ""))','\(String(describing: person.name ?? ""))','\(String(describing: person.changePasswordTime ?? ""))','\(String(describing: person.superior ?? ""))','\(String(describing: person.signature ?? ""))','\(String(describing: person.pinyin ?? ""))','\(String(describing: person.pinyinInitial ?? ""))','\(String(describing: person.qq ?? ""))','\(String(describing: person.unique ?? ""))','\(String(describing: person.updateTime ?? ""))','\(String(describing: person.weixin ?? ""))','\(String(describing: person.officePhone ?? ""))','\(String(describing: person.boardDate ?? ""))','\(String(describing: person.birthday ?? ""))',\(String(describing: person.orderNumber ?? 0)),'\(ownerid)')"
  63. self.queue.inDatabase({ (db) in
  64. let resultSet = db?.executeQuery(sSql, withArgumentsIn: nil)
  65. if let _ = (resultSet?.next()) {
  66. DDLogError("已存在,无法收藏。。。")
  67. }else{
  68. db?.executeUpdate(sql, withArgumentsIn: nil)
  69. }
  70. })
  71. }
  72. func isCollect(_ person:PersonV2,_ ownerid:String) -> Bool{
  73. var returnValue = false
  74. let sql = "SELECT COUNT(*) as collectNum FROM \(CreateTables.TABLE_NAME_O2_CONTACT_FAV) WHERE `id` = '\(String(describing: person.id!))' AND `ownerid` = '\(ownerid)' "
  75. self.queue.inDatabase({ (db) in
  76. let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
  77. if let _ = (resultSet?.next()) {
  78. if Int(resultSet?.int(forColumn: "collectNum") ?? 0) > 0 {
  79. returnValue = true
  80. }else {
  81. returnValue = false
  82. }
  83. }else{
  84. returnValue = false
  85. }
  86. })
  87. return returnValue
  88. }
  89. func deleteContactData(_ person:PersonV2,_ ownerid:String){
  90. let sql = "delete from \(CreateTables.TABLE_NAME_O2_CONTACT_FAV) where `id` = '\(String(describing: person.id!))' and `ownerid` = '\(ownerid)'"
  91. self.queue.inDatabase({ (db) in
  92. db?.executeUpdate(sql, withArgumentsIn: nil)
  93. })
  94. }
  95. func queryContactData(_ ownerid:String) -> [PersonV2] {
  96. DDLogDebug("queryContactData .....")
  97. var persons:[PersonV2] = []
  98. let sql = "SELECT * FROM \(CreateTables.TABLE_NAME_O2_CONTACT_FAV) WHERE `ownerid` = '\(ownerid)'"
  99. self.queue.inDatabase({ (db) in
  100. let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
  101. while (resultSet?.next())! {
  102. let p = PersonV2()
  103. p.id = resultSet?.string(forColumn: "id")
  104. p.name = resultSet?.string(forColumn: "name")
  105. p.changePasswordTime = resultSet?.string(forColumn: "changePasswordTime")
  106. p.distinguishedName = resultSet?.string(forColumn: "distinguishedName")
  107. p.employee = resultSet?.string(forColumn: "employee")
  108. p.genderType = resultSet?.string(forColumn: "genderType")
  109. p.lastLoginAddress = resultSet?.string(forColumn: "lastLoginAddress")
  110. p.lastLoginClient = resultSet?.string(forColumn: "lastLoginClient")
  111. p.lastLoginTime = resultSet?.string(forColumn: "lastLoginTime")
  112. p.mail = resultSet?.string(forColumn: "mail")
  113. p.mobile = resultSet?.string(forColumn: "mobile")
  114. p.orderNumber = Int(resultSet?.int(forColumn: "orderNumber") ?? 0)
  115. p.superior = resultSet?.string(forColumn: "superior")
  116. p.signature = resultSet?.string(forColumn: "pinyin")
  117. p.pinyin = resultSet?.string(forColumn: "id")
  118. p.pinyinInitial = resultSet?.string(forColumn: "pinyinInitial")
  119. p.qq = resultSet?.string(forColumn: "qq")
  120. p.unique = resultSet?.string(forColumn: "unique")
  121. p.updateTime = resultSet?.string(forColumn: "updateTime")
  122. p.officePhone = resultSet?.string(forColumn: "officePhone")
  123. p.boardDate = resultSet?.string(forColumn: "boardDate")
  124. p.birthday = resultSet?.string(forColumn: "birthday")
  125. p.ownerid = resultSet?.string(forColumn: "ownerid")
  126. persons.append(p)
  127. DDLogDebug("person name \(p.name ?? "")")
  128. }
  129. })
  130. return persons
  131. }
  132. // MARK: - o2app相关的操作
  133. func updateData(_ info: O2App, _ categoryType: Int) {
  134. let sql = "UPDATE \(CreateTables.TBALE_NAME_O2_APP) SET title=?,storyboard=?,vcname=?,segueidentifier=?,normalicon=?,selectedicon=?,`order`=?,mainorder=?,categorytype=? where appid=?"
  135. let argumentsArray = [(info.title ?? ""), (info.storyBoard ?? ""), (info.vcName ?? ""), (info.segueIdentifier ?? ""), (info.normalIcon ?? ""), (info.selectedIcon ?? ""), info.order, info.mainOrder, categoryType, info.appId!] as [Any]
  136. self.queue.inDatabase({ (db) in
  137. db?.executeUpdate(sql, withArgumentsIn: argumentsArray)
  138. })
  139. }
  140. func insertData(_ info: O2App) {
  141. let sSql = "select count(*) as appnumber,`categorytype` from \(CreateTables.TBALE_NAME_O2_APP) where appid = '\(String(describing: info.appId!))'"
  142. let insertSql = "INSERT INTO \(CreateTables.TBALE_NAME_O2_APP)(appid,title,storyboard,vcname,segueidentifier,normalicon,selectedicon,`order`,mainOrder,categorytype) values (?,?,?,?,?,?,?,?,?,?)"
  143. let argumentsArray1 = [info.appId!, (info.title ?? ""), (info.storyBoard ?? ""), (info.vcName ?? ""), (info.segueIdentifier ?? ""), (info.normalIcon ?? ""), (info.selectedIcon ?? ""), info.order, info.mainOrder, 0] as [Any]
  144. var isUpdate = false
  145. var categoryType = 0
  146. self.queue.inDatabase({ (db) in
  147. let resultSet = db?.executeQuery(sSql, withArgumentsIn: nil)
  148. if let _ = (resultSet?.next()) {
  149. if Int(resultSet?.int(forColumn: "appnumber") ?? 0) > 0 {
  150. isUpdate = true
  151. categoryType = Int(resultSet?.int(forColumn: "categorytype") ?? 0)
  152. } else {
  153. isUpdate = false
  154. db?.executeUpdate(insertSql, withArgumentsIn: argumentsArray1)
  155. }
  156. } else {
  157. db?.executeUpdate(insertSql, withArgumentsIn: argumentsArray1)
  158. }
  159. })
  160. if isUpdate == true {
  161. updateData(info, categoryType)
  162. }
  163. }
  164. func removeAll() {
  165. let delSql = "DELETE FROM \(CreateTables.TBALE_NAME_O2_APP) WHERE 1=1 "
  166. self.queue.inDatabase({ (db) in
  167. db?.executeUpdate(delSql, withArgumentsIn: nil)
  168. })
  169. }
  170. func deleteNotExistApp(_ exitApps: [String]) {
  171. var infos: [O2App] = []
  172. let sql = "select * from \(CreateTables.TBALE_NAME_O2_APP) ORDER BY `order` ASC"
  173. self.queue.inDatabase({ (db) in
  174. let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
  175. while (resultSet?.next())! {
  176. let app = O2App()
  177. app.appId = resultSet?.string(forColumn: "appid")
  178. app.title = resultSet?.string(forColumn: "title")
  179. app.storyBoard = resultSet?.string(forColumn: "storyboard")
  180. app.vcName = resultSet?.string(forColumn: "vcname")
  181. app.segueIdentifier = resultSet?.string(forColumn: "segueidentifier")
  182. app.normalIcon = resultSet?.string(forColumn: "normalicon")
  183. app.selectedIcon = resultSet?.string(forColumn: "selectedicon")
  184. app.order = Int((resultSet?.int(forColumn: "order"))!)
  185. app.mainOrder = Int((resultSet?.int(forColumn: "mainorder"))!)
  186. infos.append(app)
  187. }
  188. infos.forEachEnumerated({ (index, app) in
  189. if let appId = app.appId {
  190. if !exitApps.contains(appId) { // 不存在就删除
  191. let delSql = "delete from \(CreateTables.TBALE_NAME_O2_APP) where appid = '\(appId)'"
  192. db?.executeUpdate(delSql, withArgumentsIn: nil)
  193. }
  194. }
  195. })
  196. })
  197. }
  198. func delete(_ info: O2App) {
  199. let delSql = "delete from \(CreateTables.TBALE_NAME_O2_APP) where appid = '\(String(describing: info.appId!))'"
  200. self.queue.inDatabase({ (db) in
  201. db?.executeUpdate(delSql, withArgumentsIn: nil)
  202. })
  203. }
  204. func queryData(_ appId: String) -> O2App? {
  205. var homeApp: O2App?
  206. let sql = "SELECT * FROM \(CreateTables.TBALE_NAME_O2_APP) WHERE appid = '\(appId)'"
  207. self.queue.inDatabase({ (db) in
  208. let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
  209. while(resultSet?.next())! {
  210. homeApp = O2App()
  211. homeApp?.appId = resultSet?.string(forColumn: "appid")
  212. homeApp?.title = resultSet?.string(forColumn: "title")
  213. homeApp?.storyBoard = resultSet?.string(forColumn: "storyboard")
  214. homeApp?.vcName = resultSet?.string(forColumn: "vcname")
  215. homeApp?.segueIdentifier = resultSet?.string(forColumn: "segueidentifier")
  216. homeApp?.normalIcon = resultSet?.string(forColumn: "normalicon")
  217. homeApp?.selectedIcon = resultSet?.string(forColumn: "selectedicon")
  218. homeApp?.order = Int((resultSet?.int(forColumn: "order"))!)
  219. homeApp?.mainOrder = Int((resultSet?.int(forColumn: "mainorder"))!)
  220. }
  221. })
  222. return homeApp
  223. }
  224. func queryData() -> [O2App] {
  225. var infos: [O2App] = []
  226. let sql = "select * from \(CreateTables.TBALE_NAME_O2_APP) ORDER BY `order` ASC"
  227. self.queue.inDatabase({ (db) in
  228. let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
  229. while (resultSet?.next())! {
  230. let app = O2App()
  231. app.appId = resultSet?.string(forColumn: "appid")
  232. app.title = resultSet?.string(forColumn: "title")
  233. app.storyBoard = resultSet?.string(forColumn: "storyboard")
  234. app.vcName = resultSet?.string(forColumn: "vcname")
  235. app.segueIdentifier = resultSet?.string(forColumn: "segueidentifier")
  236. app.normalIcon = resultSet?.string(forColumn: "normalicon")
  237. app.selectedIcon = resultSet?.string(forColumn: "selectedicon")
  238. app.order = Int((resultSet?.int(forColumn: "order"))!)
  239. app.mainOrder = Int((resultSet?.int(forColumn: "mainorder"))!)
  240. infos.append(app)
  241. }
  242. })
  243. return infos
  244. }
  245. func queryNoMainData() -> [O2App] {
  246. var infos: [O2App] = []
  247. let sql = "select * from \(CreateTables.TBALE_NAME_O2_APP) where categorytype = 0 ORDER BY `order`"
  248. self.queue.inDatabase({ (db) in
  249. let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
  250. while (resultSet?.next())! {
  251. let app = O2App()
  252. app.appId = resultSet?.string(forColumn: "appid")
  253. app.title = resultSet?.string(forColumn: "title")
  254. app.storyBoard = resultSet?.string(forColumn: "storyboard")
  255. app.vcName = resultSet?.string(forColumn: "vcname")
  256. app.segueIdentifier = resultSet?.string(forColumn: "segueidentifier")
  257. app.normalIcon = resultSet?.string(forColumn: "normalicon")
  258. app.selectedIcon = resultSet?.string(forColumn: "selectedicon")
  259. app.order = Int((resultSet?.int(forColumn: "order"))!)
  260. app.mainOrder = Int((resultSet?.int(forColumn: "mainorder"))!)
  261. infos.append(app)
  262. }
  263. })
  264. return infos
  265. }
  266. func queryMainData() -> [O2App] {
  267. var infos: [O2App] = []
  268. let sql = "select * from \(CreateTables.TBALE_NAME_O2_APP) where categorytype = 1 ORDER BY `mainorder`"
  269. self.queue.inDatabase({ (db) in
  270. let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
  271. while (resultSet?.next())! {
  272. let app = O2App()
  273. app.appId = resultSet?.string(forColumn: "appid")
  274. app.title = resultSet?.string(forColumn: "title")
  275. app.storyBoard = resultSet?.string(forColumn: "storyboard")
  276. app.vcName = resultSet?.string(forColumn: "vcname")
  277. app.segueIdentifier = resultSet?.string(forColumn: "segueidentifier")
  278. app.normalIcon = resultSet?.string(forColumn: "normalicon")
  279. app.selectedIcon = resultSet?.string(forColumn: "selectedicon")
  280. app.order = Int((resultSet?.int(forColumn: "order"))!)
  281. app.mainOrder = Int((resultSet?.int(forColumn: "mainorder"))!)
  282. infos.append(app)
  283. }
  284. })
  285. return infos
  286. }
  287. // MARK: - Run 相关的操作
  288. //创建跑步用户
  289. func initRunUserInfo(userDN: String) -> Promise<Bool> {
  290. return Promise { fulfill, reject in
  291. let sql = "insert into \(CreateTables.TBALE_NAME_RUN_USER) (userDN, weight, totalDistance, totalRunTimes, totalUseTime, totalCalories, updateTime) values (?, ?, ?, ?, ?, ?, ?)"
  292. self.queue.inDatabase { (db) in
  293. let updateTime = Date().timeIntervalSince1970
  294. if let result = db?.executeUpdate(sql, withArgumentsIn: [userDN, 0.0, 0.0, 0, 0, 0, updateTime]) {
  295. fulfill(result)
  296. } else {
  297. reject(O2DBError.ExecuteError)
  298. }
  299. }
  300. }
  301. }
  302. //更新用户体重信息
  303. func updateRunUserWeight(userDN: String, weight: Double) -> Promise<Bool> {
  304. DDLogDebug("userDN:\(userDN) weight:\(weight)")
  305. return Promise { fulfill, reject in
  306. let updateTime = Date().timeIntervalSince1970
  307. let updateSql = "update \(CreateTables.TBALE_NAME_RUN_USER) set weight = ?, updateTime = ? where userDN = \"\(userDN)\" "
  308. self.queue.inDatabase({ (db) in
  309. if let result = db?.executeUpdate(updateSql, withArgumentsIn: [weight, updateTime]) {
  310. if result {
  311. DDLogDebug("更新个人体重数据成功!")
  312. } else {
  313. DDLogError("更新个人体重数据失败!")
  314. }
  315. fulfill(result)
  316. } else {
  317. DDLogError("更新个人跑步数据异常!")
  318. reject(O2DBError.ExecuteError)
  319. }
  320. })
  321. }
  322. }
  323. //将某一次跑步数据更新到用户的总表中
  324. func updateRunUserWithRunTrackInfo(userDN: String, distance: Double, useTime: Int, calories: Int) -> Promise<Bool> {
  325. return Promise { fulfill, reject in
  326. let sql = "select * from \(CreateTables.TBALE_NAME_RUN_USER) where userDN = \"\(userDN)\" "
  327. let updateSql = "update \(CreateTables.TBALE_NAME_RUN_USER) set totalDistance = ? , totalRunTimes = ?, totalUseTime = ?, totalCalories = ?, updateTime = ? where userDN = \"\(userDN)\" "
  328. self.queue.inDatabase({ (db) in
  329. if let queryResult = db?.executeQuery(sql, withArgumentsIn: []) {
  330. if queryResult.next() {
  331. let totalDistance = queryResult.double(forColumn: "totalDistance")
  332. let totalRunTimes = queryResult.long(forColumn: "totalRunTimes")
  333. let totalUseTime = queryResult.long(forColumn: "totalUseTime")
  334. let totalCalories = queryResult.long(forColumn: "totalCalories")
  335. let updateTime = Date().timeIntervalSince1970
  336. if let result = db?.executeUpdate(updateSql, withArgumentsIn: [totalDistance + distance, totalRunTimes + 1, totalUseTime + useTime, totalCalories + calories, updateTime]) {
  337. if result {
  338. DDLogDebug("更新个人跑步数据成功!")
  339. } else {
  340. DDLogError("更新个人跑步数据失败!")
  341. }
  342. fulfill(result)
  343. } else {
  344. DDLogError("更新个人跑步数据异常!")
  345. reject(O2DBError.ExecuteError)
  346. }
  347. } else {
  348. DDLogError("没有查询到用户对象,id:\(userDN)")
  349. reject(O2DBError.EmptyResultError)
  350. }
  351. queryResult.close()
  352. } else {
  353. DDLogError("查询个人跑步数据异常!")
  354. reject(O2DBError.ExecuteError)
  355. }
  356. })
  357. }
  358. }
  359. //根据dn查询用户对象
  360. func queryRunUserInfoByDN(userDN: String) -> Promise<O2RunUserInfo> {
  361. return Promise { fulfill, reject in
  362. let sql = "select * from \(CreateTables.TBALE_NAME_RUN_USER) where userDN = ? "
  363. self.queue.inDatabase({ (db) in
  364. if let result = db?.executeQuery(sql, withArgumentsIn: [userDN]) {
  365. if result.next() {
  366. let user = O2RunUserInfo()
  367. user.updateTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "updateTime")))
  368. user.weight = result.double(forColumn: "weight")
  369. user.totalCalories = result.long(forColumn: "totalCalories")
  370. user.totalDistance = result.double(forColumn: "totalDistance")
  371. user.totalUseTime = result.long(forColumn: "totalUseTime")
  372. user.totalRunTimes = result.long(forColumn: "totalRunTimes")
  373. user.userDN = result.string(forColumn: "userDN")
  374. fulfill(user)
  375. } else {
  376. DDLogDebug("用户\(userDN) 不存在!")
  377. let insertSql = "insert into \(CreateTables.TBALE_NAME_RUN_USER) (userDN, weight, totalDistance, totalRunTimes, totalUseTime, totalCalories, updateTime) values (?, ?, ?, ?, ?, ?, ?)"
  378. let updateTime = Date().timeIntervalSince1970
  379. if let insertResult = db?.executeUpdate(insertSql, withArgumentsIn: [userDN, 0.0, 0.0, 0, 0, 0, updateTime]) {
  380. if insertResult {
  381. DDLogDebug("创建一个新用户!")
  382. if let newResult = db?.executeQuery(sql, withArgumentsIn: [userDN]) {
  383. if newResult.next() {
  384. let user = O2RunUserInfo()
  385. user.updateTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "updateTime")))
  386. user.weight = result.double(forColumn: "weight")
  387. user.totalCalories = result.long(forColumn: "totalCalories")
  388. user.totalDistance = result.double(forColumn: "totalDistance")
  389. user.totalUseTime = result.long(forColumn: "totalUseTime")
  390. user.totalRunTimes = result.long(forColumn: "totalRunTimes")
  391. user.userDN = result.string(forColumn: "userDN")
  392. fulfill(user)
  393. } else {
  394. reject(O2DBError.EmptyResultError)
  395. }
  396. } else {
  397. reject(O2DBError.ExecuteError)
  398. }
  399. } else {
  400. DDLogDebug("创建新用户失败!")
  401. reject(O2DBError.ExecuteError)
  402. }
  403. } else {
  404. reject(O2DBError.ExecuteError)
  405. }
  406. }
  407. result.close()
  408. } else {
  409. reject(O2DBError.ExecuteError)
  410. }
  411. })
  412. }
  413. }
  414. //插入一次跑步数据
  415. func insertRunTrackInfo(runInfo: O2RunTrackInfo) -> Promise<String> {
  416. return Promise { fulfill, reject in
  417. let sql = "insert into \(CreateTables.TBALE_NAME_RUN_TRACK) (id, userDN, runDate, startTime, endTime, useTime, distance, calories, stepNumber, speed, entityName, createTime) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  418. let id = UUID().uuidString
  419. let createTime = Date()
  420. let array: [Any] = [
  421. id,
  422. runInfo.userDN ?? "",
  423. runInfo.runDate?.timeIntervalSince1970 ?? 0,
  424. runInfo.startTime?.timeIntervalSince1970 ?? 0,
  425. runInfo.endTime?.timeIntervalSince1970 ?? 0,
  426. runInfo.useTime ?? 0,
  427. runInfo.distance ?? 0.0,
  428. runInfo.calories ?? 0,
  429. runInfo.stepNumber ?? 0,
  430. runInfo.speed ?? 0.0,
  431. runInfo.entityName ?? "",
  432. createTime.timeIntervalSince1970
  433. ]
  434. self.queue.inDatabase({ (db) in
  435. if let result = db?.executeUpdate(sql, withArgumentsIn: array) {
  436. if result {
  437. fulfill(id)
  438. } else {
  439. reject(O2DBError.ExecuteError)
  440. }
  441. } else {
  442. reject(O2DBError.ExecuteError)
  443. }
  444. })
  445. }
  446. }
  447. //插入跑步的时候的位置点集合
  448. func insertRunTrackPoints(points: [O2RunTrackPointInfo]) -> Promise<[O2RunTrackPointInfo]> {
  449. return Promise { fulfill, reject in
  450. let sql = "insert into \(CreateTables.TBALE_NAME_RUN_TRACK_POINT) (id, runId, latitude, longitude, pointTime, createTime) values (?, ?, ?, ?, ?, ?)"
  451. var errorInsert: [O2RunTrackPointInfo] = []
  452. self.queue.inDatabase { (db) in
  453. let createTime = Date()
  454. for point in points {
  455. let id = UUID().uuidString
  456. let pArray: [Any] = [
  457. id,
  458. point.runId ?? "",
  459. point.latitude ?? 0.0,
  460. point.longitude ?? 0.0,
  461. point.pointTime?.timeIntervalSince1970 ?? 0,
  462. createTime.timeIntervalSince1970
  463. ]
  464. if let result = db?.executeUpdate(sql, withArgumentsIn: pArray) {
  465. if !result {
  466. errorInsert.append(point)
  467. }
  468. } else {
  469. errorInsert.append(point)
  470. }
  471. }
  472. fulfill(errorInsert)
  473. }
  474. }
  475. }
  476. //查询当个跑步对象 包含位置信息
  477. func queryRunTrackWithPoints(id: String) -> Promise<O2RunTrackFullData> {
  478. return Promise { fulfill, reject in
  479. let sql = "select * from \(CreateTables.TBALE_NAME_RUN_TRACK) where id = ? "
  480. let pointsSql = "select * from \(CreateTables.TBALE_NAME_RUN_TRACK_POINT) where runId = ? order by pointTime "
  481. self.queue.inDatabase({ (db) in
  482. if let result = db?.executeQuery(sql, withArgumentsIn: [id]) {
  483. if result.next() {
  484. let data = O2RunTrackFullData()
  485. data.id = result.string(forColumn: "id")
  486. data.userDN = result.string(forColumn: "userDN")
  487. data.createTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "createTime")))
  488. data.entityName = result.string(forColumn: "entityName")
  489. data.runDate = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "runDate")))
  490. data.startTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "startTime")))
  491. data.endTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "endTime")))
  492. data.distance = result.double(forColumn: "distance")
  493. data.speed = result.double(forColumn: "speed")
  494. data.calories = result.long(forColumn: "calories")
  495. data.useTime = result.long(forColumn: "useTime")
  496. data.stepNumber = result.long(forColumn: "stepNumber")
  497. if let pointsResult = db?.executeQuery(pointsSql, withArgumentsIn: [id]) {
  498. var points: [O2RunTrackPointInfo] = []
  499. while(pointsResult.next()) {
  500. let point = O2RunTrackPointInfo()
  501. point.id = pointsResult.string(forColumn: "id")
  502. point.runId = id
  503. point.pointTime = Date.init(timeIntervalSince1970: Double(pointsResult.long(forColumn: "pointTime")))
  504. point.createTime = Date.init(timeIntervalSince1970: Double(pointsResult.long(forColumn: "createTime")))
  505. point.latitude = pointsResult.double(forColumn: "latitude")
  506. point.longitude = pointsResult.double(forColumn: "longitude")
  507. points.append(point)
  508. }
  509. data.points = points
  510. pointsResult.close()
  511. } else {
  512. DDLogError("没有查询到位置信息列表")
  513. }
  514. fulfill(data)
  515. result.close()
  516. } else {
  517. DDLogDebug("没有查询到跑步对象。。。。")
  518. reject(O2DBError.EmptyResultError)
  519. }
  520. } else {
  521. reject(O2DBError.ExecuteError)
  522. }
  523. })
  524. }
  525. }
  526. //查询全部的的跑步记录
  527. func queryRunTrackAllList() -> Promise<[O2RunTrackInfo]> {
  528. return Promise { fulfill, reject in
  529. let sql = "select * from \(CreateTables.TBALE_NAME_RUN_TRACK) order by createTime desc "
  530. self.queue.inDatabase({ (db) in
  531. if let result = db?.executeQuery(sql, withArgumentsIn: []) {
  532. var array: [O2RunTrackInfo] = []
  533. while result.next() {
  534. let data = O2RunTrackInfo()
  535. data.id = result.string(forColumn: "id")
  536. data.userDN = result.string(forColumn: "userDN")
  537. data.createTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "createTime")))
  538. data.entityName = result.string(forColumn: "entityName")
  539. data.runDate = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "runDate")))
  540. data.startTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "startTime")))
  541. data.endTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "endTime")))
  542. data.distance = result.double(forColumn: "distance")
  543. data.speed = result.double(forColumn: "speed")
  544. data.calories = result.long(forColumn: "calories")
  545. data.useTime = result.long(forColumn: "useTime")
  546. data.stepNumber = result.long(forColumn: "stepNumber")
  547. array.append(data)
  548. }
  549. fulfill(array)
  550. result.close()
  551. } else {
  552. reject(O2DBError.ExecuteError)
  553. }
  554. })
  555. }
  556. }
  557. //查询时间段内 跑步列表数据
  558. func queryRunTrackListByTime(startTime: Date, endTime: Date) -> Promise<[O2RunTrackInfo]> {
  559. return Promise { fulfill, reject in
  560. let sql = "select * from \(CreateTables.TBALE_NAME_RUN_TRACK) where runDate > ? and runDate < ? order by createTime desc "
  561. self.queue.inDatabase({ (db) in
  562. let start = Int(startTime.timeIntervalSince1970)
  563. let end = Int(endTime.timeIntervalSince1970)
  564. if let result = db?.executeQuery(sql, withArgumentsIn: [start, end]) {
  565. var array: [O2RunTrackInfo] = []
  566. while result.next() {
  567. let data = O2RunTrackInfo()
  568. data.id = result.string(forColumn: "id")
  569. data.userDN = result.string(forColumn: "userDN")
  570. data.createTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "createTime")))
  571. data.entityName = result.string(forColumn: "entityName")
  572. data.runDate = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "runDate")))
  573. data.startTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "startTime")))
  574. data.endTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "endTime")))
  575. data.distance = result.double(forColumn: "distance")
  576. data.speed = result.double(forColumn: "speed")
  577. data.calories = result.long(forColumn: "calories")
  578. data.useTime = result.long(forColumn: "useTime")
  579. data.stepNumber = result.long(forColumn: "stepNumber")
  580. array.append(data)
  581. }
  582. fulfill(array)
  583. result.close()
  584. } else {
  585. reject(O2DBError.ExecuteError)
  586. }
  587. })
  588. }
  589. }
  590. }
  591. enum O2DBError: Error {
  592. case ExecuteError
  593. case EmptyResultError
  594. case EmptyRowIdError
  595. case UnkownError
  596. }
  597. extension O2DBError: LocalizedError {
  598. var errorDescription: String? {
  599. get {
  600. switch self {
  601. case .ExecuteError:
  602. return "执行sql语言出错!"
  603. case .EmptyResultError:
  604. return "查询数据结果为空!"
  605. case .EmptyRowIdError:
  606. return "没有获取到自增ID!"
  607. case .UnkownError:
  608. return "未知错误"
  609. }
  610. }
  611. }
  612. }