@@ -6,21 +6,34 @@ final class PostgreSQLTableNameCache {
6
6
var storage : [ Int32 : String ]
7
7
8
8
/// Static shared cache, stored by connections.
9
- private static var shared : [ ObjectIdentifier : PostgreSQLTableNameCache ] = [ : ]
9
+ private static var _shared : ThreadSpecificVariable < PostgreSQLTableNameCaches > = . init( )
10
+
11
+ /// Getter for `_shared` that will initialize if it has not already been initialized.
12
+ private static var shared : PostgreSQLTableNameCaches {
13
+ get {
14
+ if let existing = _shared. currentValue {
15
+ return existing
16
+ } else {
17
+ let new = PostgreSQLTableNameCaches ( )
18
+ _shared. currentValue = new
19
+ return new
20
+ }
21
+ }
22
+ }
10
23
11
24
/// Creates a new cache.
12
- private init ( cache: [ Int32 : String ] ) {
25
+ private init ( _ cache: [ Int32 : String ] ) {
13
26
self . storage = cache
14
27
}
15
28
16
29
/// Invalidates the cache for the supplied connection.
17
30
static func invalidate( for connection: PostgreSQLConnection ) {
18
- shared [ ObjectIdentifier ( connection) ] = nil
31
+ shared. storage [ ObjectIdentifier ( connection) ] = nil
19
32
}
20
33
21
34
/// Generates a cache for the supplied connection.
22
35
static func get( for connection: PostgreSQLConnection ) -> Future < PostgreSQLTableNameCache > {
23
- if let existing = shared [ ObjectIdentifier ( connection) ] {
36
+ if let existing = shared. storage [ ObjectIdentifier ( connection) ] {
24
37
return Future . map ( on: connection) { existing }
25
38
} else {
26
39
return connection. simpleQuery ( " select oid, relname from pg_class " ) . map ( to: PostgreSQLTableNameCache . self) { rows in
@@ -32,10 +45,21 @@ final class PostgreSQLTableNameCache {
32
45
cache [ oid] = name
33
46
}
34
47
35
- let new = PostgreSQLTableNameCache ( cache: cache )
36
- shared [ ObjectIdentifier ( connection) ] = new
48
+ let new = PostgreSQLTableNameCache ( cache)
49
+ shared. storage [ ObjectIdentifier ( connection) ] = new
37
50
return new
38
51
}
39
52
}
40
53
}
41
54
}
55
+
56
+ /// Stores connection caches per thread.
57
+ final class PostgreSQLTableNameCaches {
58
+ /// Psql connection is used as object id.
59
+ var storage : [ ObjectIdentifier : PostgreSQLTableNameCache ]
60
+
61
+ /// Creates a new cache.
62
+ internal init ( ) {
63
+ self . storage = [ : ]
64
+ }
65
+ }
0 commit comments