DBManager.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  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. //清除了数据库数据 需要清除 customStyleHashLocal 这样新登录绑定后才会读取
  170. AppConfigSettings.shared.customStyleHashLocal = ""
  171. }
  172. func deleteNotExistApp(_ exitApps: [String]) {
  173. var infos: [O2App] = []
  174. let sql = "select * from \(CreateTables.TBALE_NAME_O2_APP) ORDER BY `order` ASC"
  175. self.queue.inDatabase({ (db) in
  176. let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
  177. while (resultSet?.next())! {
  178. let app = O2App()
  179. app.appId = resultSet?.string(forColumn: "appid")
  180. app.title = resultSet?.string(forColumn: "title")
  181. app.storyBoard = resultSet?.string(forColumn: "storyboard")
  182. app.vcName = resultSet?.string(forColumn: "vcname")
  183. app.segueIdentifier = resultSet?.string(forColumn: "segueidentifier")
  184. app.normalIcon = resultSet?.string(forColumn: "normalicon")
  185. app.selectedIcon = resultSet?.string(forColumn: "selectedicon")
  186. app.order = Int((resultSet?.int(forColumn: "order"))!)
  187. app.mainOrder = Int((resultSet?.int(forColumn: "mainorder"))!)
  188. infos.append(app)
  189. }
  190. infos.forEachEnumerated({ (index, app) in
  191. if let appId = app.appId {
  192. if !exitApps.contains(appId) { // 不存在就删除
  193. let delSql = "delete from \(CreateTables.TBALE_NAME_O2_APP) where appid = '\(appId)'"
  194. db?.executeUpdate(delSql, withArgumentsIn: nil)
  195. }
  196. }
  197. })
  198. })
  199. }
  200. func delete(_ info: O2App) {
  201. let delSql = "delete from \(CreateTables.TBALE_NAME_O2_APP) where appid = '\(String(describing: info.appId!))'"
  202. self.queue.inDatabase({ (db) in
  203. db?.executeUpdate(delSql, withArgumentsIn: nil)
  204. })
  205. }
  206. func queryData(_ appId: String) -> O2App? {
  207. var homeApp: O2App?
  208. let sql = "SELECT * FROM \(CreateTables.TBALE_NAME_O2_APP) WHERE appid = '\(appId)'"
  209. self.queue.inDatabase({ (db) in
  210. let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
  211. while(resultSet?.next())! {
  212. homeApp = O2App()
  213. homeApp?.appId = resultSet?.string(forColumn: "appid")
  214. homeApp?.title = resultSet?.string(forColumn: "title")
  215. homeApp?.storyBoard = resultSet?.string(forColumn: "storyboard")
  216. homeApp?.vcName = resultSet?.string(forColumn: "vcname")
  217. homeApp?.segueIdentifier = resultSet?.string(forColumn: "segueidentifier")
  218. homeApp?.normalIcon = resultSet?.string(forColumn: "normalicon")
  219. homeApp?.selectedIcon = resultSet?.string(forColumn: "selectedicon")
  220. homeApp?.order = Int((resultSet?.int(forColumn: "order"))!)
  221. homeApp?.mainOrder = Int((resultSet?.int(forColumn: "mainorder"))!)
  222. }
  223. })
  224. return homeApp
  225. }
  226. func queryData() -> [O2App] {
  227. var infos: [O2App] = []
  228. let sql = "select * from \(CreateTables.TBALE_NAME_O2_APP) ORDER BY `order` ASC"
  229. self.queue.inDatabase({ (db) in
  230. let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
  231. while (resultSet?.next())! {
  232. let app = O2App()
  233. app.appId = resultSet?.string(forColumn: "appid")
  234. app.title = resultSet?.string(forColumn: "title")
  235. app.storyBoard = resultSet?.string(forColumn: "storyboard")
  236. app.vcName = resultSet?.string(forColumn: "vcname")
  237. app.segueIdentifier = resultSet?.string(forColumn: "segueidentifier")
  238. app.normalIcon = resultSet?.string(forColumn: "normalicon")
  239. app.selectedIcon = resultSet?.string(forColumn: "selectedicon")
  240. app.order = Int((resultSet?.int(forColumn: "order"))!)
  241. app.mainOrder = Int((resultSet?.int(forColumn: "mainorder"))!)
  242. infos.append(app)
  243. }
  244. })
  245. return infos
  246. }
  247. func queryNoMainData() -> [O2App] {
  248. var infos: [O2App] = []
  249. let sql = "select * from \(CreateTables.TBALE_NAME_O2_APP) where categorytype = 0 ORDER BY `order`"
  250. self.queue.inDatabase({ (db) in
  251. let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
  252. while (resultSet?.next())! {
  253. let app = O2App()
  254. app.appId = resultSet?.string(forColumn: "appid")
  255. app.title = resultSet?.string(forColumn: "title")
  256. app.storyBoard = resultSet?.string(forColumn: "storyboard")
  257. app.vcName = resultSet?.string(forColumn: "vcname")
  258. app.segueIdentifier = resultSet?.string(forColumn: "segueidentifier")
  259. app.normalIcon = resultSet?.string(forColumn: "normalicon")
  260. app.selectedIcon = resultSet?.string(forColumn: "selectedicon")
  261. app.order = Int((resultSet?.int(forColumn: "order"))!)
  262. app.mainOrder = Int((resultSet?.int(forColumn: "mainorder"))!)
  263. infos.append(app)
  264. }
  265. })
  266. return infos
  267. }
  268. func queryMainData() -> [O2App] {
  269. var infos: [O2App] = []
  270. let sql = "select * from \(CreateTables.TBALE_NAME_O2_APP) where categorytype = 1 ORDER BY `mainorder`"
  271. self.queue.inDatabase({ (db) in
  272. let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
  273. while (resultSet?.next())! {
  274. let app = O2App()
  275. app.appId = resultSet?.string(forColumn: "appid")
  276. app.title = resultSet?.string(forColumn: "title")
  277. app.storyBoard = resultSet?.string(forColumn: "storyboard")
  278. app.vcName = resultSet?.string(forColumn: "vcname")
  279. app.segueIdentifier = resultSet?.string(forColumn: "segueidentifier")
  280. app.normalIcon = resultSet?.string(forColumn: "normalicon")
  281. app.selectedIcon = resultSet?.string(forColumn: "selectedicon")
  282. app.order = Int((resultSet?.int(forColumn: "order"))!)
  283. app.mainOrder = Int((resultSet?.int(forColumn: "mainorder"))!)
  284. infos.append(app)
  285. }
  286. })
  287. return infos
  288. }
  289. // MARK: - Run 相关的操作
  290. //创建跑步用户
  291. func initRunUserInfo(userDN: String) -> Promise<Bool> {
  292. return Promise { fulfill, reject in
  293. let sql = "insert into \(CreateTables.TBALE_NAME_RUN_USER) (userDN, weight, totalDistance, totalRunTimes, totalUseTime, totalCalories, updateTime) values (?, ?, ?, ?, ?, ?, ?)"
  294. self.queue.inDatabase { (db) in
  295. let updateTime = Date().timeIntervalSince1970
  296. if let result = db?.executeUpdate(sql, withArgumentsIn: [userDN, 0.0, 0.0, 0, 0, 0, updateTime]) {
  297. fulfill(result)
  298. } else {
  299. reject(O2DBError.ExecuteError)
  300. }
  301. }
  302. }
  303. }
  304. //更新用户体重信息
  305. func updateRunUserWeight(userDN: String, weight: Double) -> Promise<Bool> {
  306. DDLogDebug("userDN:\(userDN) weight:\(weight)")
  307. return Promise { fulfill, reject in
  308. let updateTime = Date().timeIntervalSince1970
  309. let updateSql = "update \(CreateTables.TBALE_NAME_RUN_USER) set weight = ?, updateTime = ? where userDN = \"\(userDN)\" "
  310. self.queue.inDatabase({ (db) in
  311. if let result = db?.executeUpdate(updateSql, withArgumentsIn: [weight, updateTime]) {
  312. if result {
  313. DDLogDebug("更新个人体重数据成功!")
  314. } else {
  315. DDLogError("更新个人体重数据失败!")
  316. }
  317. fulfill(result)
  318. } else {
  319. DDLogError("更新个人跑步数据异常!")
  320. reject(O2DBError.ExecuteError)
  321. }
  322. })
  323. }
  324. }
  325. //将某一次跑步数据更新到用户的总表中
  326. func updateRunUserWithRunTrackInfo(userDN: String, distance: Double, useTime: Int, calories: Int) -> Promise<Bool> {
  327. return Promise { fulfill, reject in
  328. let sql = "select * from \(CreateTables.TBALE_NAME_RUN_USER) where userDN = \"\(userDN)\" "
  329. let updateSql = "update \(CreateTables.TBALE_NAME_RUN_USER) set totalDistance = ? , totalRunTimes = ?, totalUseTime = ?, totalCalories = ?, updateTime = ? where userDN = \"\(userDN)\" "
  330. self.queue.inDatabase({ (db) in
  331. if let queryResult = db?.executeQuery(sql, withArgumentsIn: []) {
  332. if queryResult.next() {
  333. let totalDistance = queryResult.double(forColumn: "totalDistance")
  334. let totalRunTimes = queryResult.long(forColumn: "totalRunTimes")
  335. let totalUseTime = queryResult.long(forColumn: "totalUseTime")
  336. let totalCalories = queryResult.long(forColumn: "totalCalories")
  337. let updateTime = Date().timeIntervalSince1970
  338. if let result = db?.executeUpdate(updateSql, withArgumentsIn: [totalDistance + distance, totalRunTimes + 1, totalUseTime + useTime, totalCalories + calories, updateTime]) {
  339. if result {
  340. DDLogDebug("更新个人跑步数据成功!")
  341. } else {
  342. DDLogError("更新个人跑步数据失败!")
  343. }
  344. fulfill(result)
  345. } else {
  346. DDLogError("更新个人跑步数据异常!")
  347. reject(O2DBError.ExecuteError)
  348. }
  349. } else {
  350. DDLogError("没有查询到用户对象,id:\(userDN)")
  351. reject(O2DBError.EmptyResultError)
  352. }
  353. queryResult.close()
  354. } else {
  355. DDLogError("查询个人跑步数据异常!")
  356. reject(O2DBError.ExecuteError)
  357. }
  358. })
  359. }
  360. }
  361. //根据dn查询用户对象
  362. func queryRunUserInfoByDN(userDN: String) -> Promise<O2RunUserInfo> {
  363. return Promise { fulfill, reject in
  364. let sql = "select * from \(CreateTables.TBALE_NAME_RUN_USER) where userDN = ? "
  365. self.queue.inDatabase({ (db) in
  366. if let result = db?.executeQuery(sql, withArgumentsIn: [userDN]) {
  367. if result.next() {
  368. let user = O2RunUserInfo()
  369. user.updateTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "updateTime")))
  370. user.weight = result.double(forColumn: "weight")
  371. user.totalCalories = result.long(forColumn: "totalCalories")
  372. user.totalDistance = result.double(forColumn: "totalDistance")
  373. user.totalUseTime = result.long(forColumn: "totalUseTime")
  374. user.totalRunTimes = result.long(forColumn: "totalRunTimes")
  375. user.userDN = result.string(forColumn: "userDN")
  376. fulfill(user)
  377. } else {
  378. DDLogDebug("用户\(userDN) 不存在!")
  379. let insertSql = "insert into \(CreateTables.TBALE_NAME_RUN_USER) (userDN, weight, totalDistance, totalRunTimes, totalUseTime, totalCalories, updateTime) values (?, ?, ?, ?, ?, ?, ?)"
  380. let updateTime = Date().timeIntervalSince1970
  381. if let insertResult = db?.executeUpdate(insertSql, withArgumentsIn: [userDN, 0.0, 0.0, 0, 0, 0, updateTime]) {
  382. if insertResult {
  383. DDLogDebug("创建一个新用户!")
  384. if let newResult = db?.executeQuery(sql, withArgumentsIn: [userDN]) {
  385. if newResult.next() {
  386. let user = O2RunUserInfo()
  387. user.updateTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "updateTime")))
  388. user.weight = result.double(forColumn: "weight")
  389. user.totalCalories = result.long(forColumn: "totalCalories")
  390. user.totalDistance = result.double(forColumn: "totalDistance")
  391. user.totalUseTime = result.long(forColumn: "totalUseTime")
  392. user.totalRunTimes = result.long(forColumn: "totalRunTimes")
  393. user.userDN = result.string(forColumn: "userDN")
  394. fulfill(user)
  395. } else {
  396. reject(O2DBError.EmptyResultError)
  397. }
  398. } else {
  399. reject(O2DBError.ExecuteError)
  400. }
  401. } else {
  402. DDLogDebug("创建新用户失败!")
  403. reject(O2DBError.ExecuteError)
  404. }
  405. } else {
  406. reject(O2DBError.ExecuteError)
  407. }
  408. }
  409. result.close()
  410. } else {
  411. reject(O2DBError.ExecuteError)
  412. }
  413. })
  414. }
  415. }
  416. //插入一次跑步数据
  417. func insertRunTrackInfo(runInfo: O2RunTrackInfo) -> Promise<String> {
  418. return Promise { fulfill, reject in
  419. let sql = "insert into \(CreateTables.TBALE_NAME_RUN_TRACK) (id, userDN, runDate, startTime, endTime, useTime, distance, calories, stepNumber, speed, entityName, createTime) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
  420. let id = UUID().uuidString
  421. let createTime = Date()
  422. let array: [Any] = [
  423. id,
  424. runInfo.userDN ?? "",
  425. runInfo.runDate?.timeIntervalSince1970 ?? 0,
  426. runInfo.startTime?.timeIntervalSince1970 ?? 0,
  427. runInfo.endTime?.timeIntervalSince1970 ?? 0,
  428. runInfo.useTime ?? 0,
  429. runInfo.distance ?? 0.0,
  430. runInfo.calories ?? 0,
  431. runInfo.stepNumber ?? 0,
  432. runInfo.speed ?? 0.0,
  433. runInfo.entityName ?? "",
  434. createTime.timeIntervalSince1970
  435. ]
  436. self.queue.inDatabase({ (db) in
  437. if let result = db?.executeUpdate(sql, withArgumentsIn: array) {
  438. if result {
  439. fulfill(id)
  440. } else {
  441. reject(O2DBError.ExecuteError)
  442. }
  443. } else {
  444. reject(O2DBError.ExecuteError)
  445. }
  446. })
  447. }
  448. }
  449. //插入跑步的时候的位置点集合
  450. func insertRunTrackPoints(points: [O2RunTrackPointInfo]) -> Promise<[O2RunTrackPointInfo]> {
  451. return Promise { fulfill, reject in
  452. let sql = "insert into \(CreateTables.TBALE_NAME_RUN_TRACK_POINT) (id, runId, latitude, longitude, pointTime, createTime) values (?, ?, ?, ?, ?, ?)"
  453. var errorInsert: [O2RunTrackPointInfo] = []
  454. self.queue.inDatabase { (db) in
  455. let createTime = Date()
  456. for point in points {
  457. let id = UUID().uuidString
  458. let pArray: [Any] = [
  459. id,
  460. point.runId ?? "",
  461. point.latitude ?? 0.0,
  462. point.longitude ?? 0.0,
  463. point.pointTime?.timeIntervalSince1970 ?? 0,
  464. createTime.timeIntervalSince1970
  465. ]
  466. if let result = db?.executeUpdate(sql, withArgumentsIn: pArray) {
  467. if !result {
  468. errorInsert.append(point)
  469. }
  470. } else {
  471. errorInsert.append(point)
  472. }
  473. }
  474. fulfill(errorInsert)
  475. }
  476. }
  477. }
  478. //查询当个跑步对象 包含位置信息
  479. func queryRunTrackWithPoints(id: String) -> Promise<O2RunTrackFullData> {
  480. return Promise { fulfill, reject in
  481. let sql = "select * from \(CreateTables.TBALE_NAME_RUN_TRACK) where id = ? "
  482. let pointsSql = "select * from \(CreateTables.TBALE_NAME_RUN_TRACK_POINT) where runId = ? order by pointTime "
  483. self.queue.inDatabase({ (db) in
  484. if let result = db?.executeQuery(sql, withArgumentsIn: [id]) {
  485. if result.next() {
  486. let data = O2RunTrackFullData()
  487. data.id = result.string(forColumn: "id")
  488. data.userDN = result.string(forColumn: "userDN")
  489. data.createTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "createTime")))
  490. data.entityName = result.string(forColumn: "entityName")
  491. data.runDate = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "runDate")))
  492. data.startTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "startTime")))
  493. data.endTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "endTime")))
  494. data.distance = result.double(forColumn: "distance")
  495. data.speed = result.double(forColumn: "speed")
  496. data.calories = result.long(forColumn: "calories")
  497. data.useTime = result.long(forColumn: "useTime")
  498. data.stepNumber = result.long(forColumn: "stepNumber")
  499. if let pointsResult = db?.executeQuery(pointsSql, withArgumentsIn: [id]) {
  500. var points: [O2RunTrackPointInfo] = []
  501. while(pointsResult.next()) {
  502. let point = O2RunTrackPointInfo()
  503. point.id = pointsResult.string(forColumn: "id")
  504. point.runId = id
  505. point.pointTime = Date.init(timeIntervalSince1970: Double(pointsResult.long(forColumn: "pointTime")))
  506. point.createTime = Date.init(timeIntervalSince1970: Double(pointsResult.long(forColumn: "createTime")))
  507. point.latitude = pointsResult.double(forColumn: "latitude")
  508. point.longitude = pointsResult.double(forColumn: "longitude")
  509. points.append(point)
  510. }
  511. data.points = points
  512. pointsResult.close()
  513. } else {
  514. DDLogError("没有查询到位置信息列表")
  515. }
  516. fulfill(data)
  517. result.close()
  518. } else {
  519. DDLogDebug("没有查询到跑步对象。。。。")
  520. reject(O2DBError.EmptyResultError)
  521. }
  522. } else {
  523. reject(O2DBError.ExecuteError)
  524. }
  525. })
  526. }
  527. }
  528. //查询全部的的跑步记录
  529. func queryRunTrackAllList() -> Promise<[O2RunTrackInfo]> {
  530. return Promise { fulfill, reject in
  531. let sql = "select * from \(CreateTables.TBALE_NAME_RUN_TRACK) order by createTime desc "
  532. self.queue.inDatabase({ (db) in
  533. if let result = db?.executeQuery(sql, withArgumentsIn: []) {
  534. var array: [O2RunTrackInfo] = []
  535. while result.next() {
  536. let data = O2RunTrackInfo()
  537. data.id = result.string(forColumn: "id")
  538. data.userDN = result.string(forColumn: "userDN")
  539. data.createTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "createTime")))
  540. data.entityName = result.string(forColumn: "entityName")
  541. data.runDate = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "runDate")))
  542. data.startTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "startTime")))
  543. data.endTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "endTime")))
  544. data.distance = result.double(forColumn: "distance")
  545. data.speed = result.double(forColumn: "speed")
  546. data.calories = result.long(forColumn: "calories")
  547. data.useTime = result.long(forColumn: "useTime")
  548. data.stepNumber = result.long(forColumn: "stepNumber")
  549. array.append(data)
  550. }
  551. fulfill(array)
  552. result.close()
  553. } else {
  554. reject(O2DBError.ExecuteError)
  555. }
  556. })
  557. }
  558. }
  559. //查询时间段内 跑步列表数据
  560. func queryRunTrackListByTime(startTime: Date, endTime: Date) -> Promise<[O2RunTrackInfo]> {
  561. return Promise { fulfill, reject in
  562. let sql = "select * from \(CreateTables.TBALE_NAME_RUN_TRACK) where runDate > ? and runDate < ? order by createTime desc "
  563. self.queue.inDatabase({ (db) in
  564. let start = Int(startTime.timeIntervalSince1970)
  565. let end = Int(endTime.timeIntervalSince1970)
  566. if let result = db?.executeQuery(sql, withArgumentsIn: [start, end]) {
  567. var array: [O2RunTrackInfo] = []
  568. while result.next() {
  569. let data = O2RunTrackInfo()
  570. data.id = result.string(forColumn: "id")
  571. data.userDN = result.string(forColumn: "userDN")
  572. data.createTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "createTime")))
  573. data.entityName = result.string(forColumn: "entityName")
  574. data.runDate = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "runDate")))
  575. data.startTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "startTime")))
  576. data.endTime = Date.init(timeIntervalSince1970: Double(result.long(forColumn: "endTime")))
  577. data.distance = result.double(forColumn: "distance")
  578. data.speed = result.double(forColumn: "speed")
  579. data.calories = result.long(forColumn: "calories")
  580. data.useTime = result.long(forColumn: "useTime")
  581. data.stepNumber = result.long(forColumn: "stepNumber")
  582. array.append(data)
  583. }
  584. fulfill(array)
  585. result.close()
  586. } else {
  587. reject(O2DBError.ExecuteError)
  588. }
  589. })
  590. }
  591. }
  592. }
  593. enum O2DBError: Error {
  594. case ExecuteError
  595. case EmptyResultError
  596. case EmptyRowIdError
  597. case UnkownError
  598. }
  599. extension O2DBError: LocalizedError {
  600. var errorDescription: String? {
  601. get {
  602. switch self {
  603. case .ExecuteError:
  604. return "执行sql语言出错!"
  605. case .EmptyResultError:
  606. return "查询数据结果为空!"
  607. case .EmptyRowIdError:
  608. return "没有获取到自增ID!"
  609. case .UnkownError:
  610. return "未知错误"
  611. }
  612. }
  613. }
  614. }