diff --git a/Sources/SwiftKueryORM/TableInfo.swift b/Sources/SwiftKueryORM/TableInfo.swift index 1e5d6ab..3906e85 100644 --- a/Sources/SwiftKueryORM/TableInfo.swift +++ b/Sources/SwiftKueryORM/TableInfo.swift @@ -18,11 +18,15 @@ 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(_ idColumn: (name: String, type: SQLDataType.Type), _ tableName: String, for type: T.Type) throws -> Table { @@ -30,11 +34,19 @@ public class TableInfo { } func getInfo(_ 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