Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // DBManager.swift
- // Pazar-Backend
- //
- // Created by Bilgehan IŞIKLI on 19/01/2018.
- //
- import PerfectMySQL
- import Foundation
- import PerfectThread
- #if os(Linux)
- import Glibc
- #else
- import Darwin
- #endif
- class DBManager {
- struct MySQLPoolItem {
- let mysql = MySQL()
- let lock = Threading.Lock()
- func connect()->Bool{
- return mysql.connect(host: Prefs.dbhost, user: Prefs.dbuser, password: Prefs.dbpass, db: Prefs.schema)
- }
- }
- var pool: [MySQLPoolItem] = []
- static let shared = DBManager()
- func preparePool() {
- var connectionCount = Prefs.connectionPoolCount
- while connectionCount > 0 {
- let item = MySQLPoolItem()
- _ = item.mysql.setOption(.MYSQL_SET_CHARSET_NAME, "utf8")
- let connected = item.connect()
- guard connected else {
- // verify we connected successfully
- print(item.mysql.errorMessage())
- return
- }
- print("Database connection \((connectionCount)) success");
- pool.append(item)
- connectionCount -= 1
- }
- }
- func getAvailableConnection() -> MySQLPoolItem {
- var item : MySQLPoolItem? = nil;
- while item == nil {
- item = tryAvailableConnection()
- if(item == nil){
- sleep(1)
- }
- }
- return item!
- }
- private func tryAvailableConnection() -> MySQLPoolItem? {
- for item in pool {
- if(item.lock.tryLock()){
- if(!item.mysql.ping()){
- if(item.mysql.connect()){
- return item
- }
- }else{
- return item
- }
- }
- }
- return nil
- }
- func runSync(query: String) -> ((result:Bool,items:MySQL.Results?)) {
- let poolItem = getAvailableConnection()
- defer {
- poolItem.lock.unlock()
- }
- let querySuccess = poolItem.mysql.query(statement: query)
- return (querySuccess,poolItem.mysql.storeResults())
- }
- }
Add Comment
Please, Sign In to add comment