Skip to content

Commit

Permalink
fix: improves handling on concurrent accesses to codableMap (#64)
Browse files Browse the repository at this point in the history
* fix: improves handling on concurrent accesses to codableMap

* added Dispatch import for <Swift4.1

* fixed string interpolation issue, whitespacing
  • Loading branch information
KyeMaloy97 authored Aug 1, 2018
1 parent e81b671 commit 2723fe5
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions Sources/SwiftKueryORM/TableInfo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,23 +18,35 @@ import KituraContracts
import SwiftKuery
import Foundation
import TypeDecoder
#if os(Linux)
import Dispatch
#endif

/// Class caching the tables for the models of the application

public class TableInfo {
private var codableMap = [String: (info: TypeInfo, table: Table)]()
private var codableMapLock = DispatchSemaphore(value: 1)

/// Get the table for a model
func getTable<T: Decodable>(_ idColumn: (name: String, type: SQLDataType.Type), _ tableName: String, for type: T.Type) throws -> Table {
return try getInfo(idColumn, tableName, type).table
}

func getInfo<T: Decodable>(_ idColumn: (name: String, type: SQLDataType.Type), _ tableName: String, _ type: T.Type) throws -> (info: TypeInfo, table: Table) {
if codableMap["\(type)"] == nil {
let typeInfo = try TypeDecoder.decode(type)
codableMap["\(type)"] = (info: typeInfo, table: try constructTable(idColumn, tableName, typeInfo))
let typeString = "\(type)"
if let result = codableMap[typeString] {
return result
}
return codableMap["\(type)"]!

codableMapLock.wait()
defer { codableMapLock.signal() }

let typeInfo = try TypeDecoder.decode(type)
let result = (info: typeInfo, table: try constructTable(idColumn, tableName, typeInfo))
codableMap[typeString] = result

return result
}

/// Construct the table for a Model
Expand Down

0 comments on commit 2723fe5

Please sign in to comment.