Guest User

Untitled

a guest
Apr 20th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. //
  2. // DBManager.swift
  3. // Pazar-Backend
  4. //
  5. // Created by Bilgehan IŞIKLI on 19/01/2018.
  6. //
  7.  
  8. import PerfectMySQL
  9. import Foundation
  10. import PerfectThread
  11. #if os(Linux)
  12. import Glibc
  13. #else
  14. import Darwin
  15. #endif
  16.  
  17. class DBManager {
  18.  
  19. struct MySQLPoolItem {
  20. let mysql = MySQL()
  21. let lock = Threading.Lock()
  22. func connect()->Bool{
  23. return mysql.connect(host: Prefs.dbhost, user: Prefs.dbuser, password: Prefs.dbpass, db: Prefs.schema)
  24. }
  25. }
  26.  
  27. var pool: [MySQLPoolItem] = []
  28.  
  29. static let shared = DBManager()
  30.  
  31. func preparePool() {
  32.  
  33. var connectionCount = Prefs.connectionPoolCount
  34.  
  35. while connectionCount > 0 {
  36.  
  37. let item = MySQLPoolItem()
  38. _ = item.mysql.setOption(.MYSQL_SET_CHARSET_NAME, "utf8")
  39. let connected = item.connect()
  40. guard connected else {
  41. // verify we connected successfully
  42. print(item.mysql.errorMessage())
  43. return
  44. }
  45. print("Database connection \((connectionCount)) success");
  46. pool.append(item)
  47. connectionCount -= 1
  48. }
  49.  
  50. }
  51.  
  52. func getAvailableConnection() -> MySQLPoolItem {
  53.  
  54. var item : MySQLPoolItem? = nil;
  55.  
  56. while item == nil {
  57. item = tryAvailableConnection()
  58. if(item == nil){
  59. sleep(1)
  60. }
  61. }
  62.  
  63. return item!
  64. }
  65.  
  66. private func tryAvailableConnection() -> MySQLPoolItem? {
  67.  
  68. for item in pool {
  69.  
  70. if(item.lock.tryLock()){
  71.  
  72. if(!item.mysql.ping()){
  73. if(item.mysql.connect()){
  74. return item
  75. }
  76. }else{
  77. return item
  78. }
  79.  
  80. }
  81.  
  82. }
  83.  
  84. return nil
  85.  
  86. }
  87.  
  88. func runSync(query: String) -> ((result:Bool,items:MySQL.Results?)) {
  89.  
  90. let poolItem = getAvailableConnection()
  91.  
  92. defer {
  93. poolItem.lock.unlock()
  94. }
  95.  
  96. let querySuccess = poolItem.mysql.query(statement: query)
  97.  
  98. return (querySuccess,poolItem.mysql.storeResults())
  99.  
  100. }
  101.  
  102.  
  103.  
  104.  
  105. }
Add Comment
Please, Sign In to add comment