-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathSQLiteConnectionPoolSerial.swift
86 lines (77 loc) · 2.57 KB
/
SQLiteConnectionPoolSerial.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// SQLiteConnectionPoolSerial.swift
// SQLiteConnectionPool
//
// Created by Andrea Prearo on 1/20/19.
// Copyright © 2019 Andrea Prearo. All rights reserved.
//
import Foundation
public class SQLiteConnectionPoolSerial {
public static let shared = SQLiteConnectionPoolSerial()
private var connectedDatabases = Set<SQLiteConnection>()
private var queue = DispatchQueue(label: "com.aprearo.connectionPool.serialuQueue")
public func connectToDatabase(filename: String) -> Result<SQLiteConnection?, Error> {
if let database = self.connectedDatabase(filename: filename) {
return .success(database)
}
var value: SQLiteConnection?
var error: Error?
queue.sync {
do {
let newDatabase = try SQLiteConnection(filename: filename)
self.connectedDatabases.insert(newDatabase)
value = newDatabase
} catch let localError {
error = localError
}
}
if let error = error {
return .failure(error)
}
return .success(value)
}
public func disconnectFromDatabase(filename: String) -> Error? {
var error: Error?
queue.sync {
for database in self.connectedDatabases {
if database.filename == filename {
guard let connection = self.connectedDatabases.remove(database) else { return }
do {
try connection.close()
} catch let localError {
error = localError
}
}
}
}
return error
}
public func connectedDatabase(filename: String) -> SQLiteConnection? {
return queue.sync {
let connectedDatabases = self.connectedDatabases
for database in connectedDatabases {
if database.filename == filename {
return database
}
}
return nil
}
}
public func disconnectFromAllDatabases() -> Error? {
var error: Error?
queue.sync {
self.connectedDatabases.forEach { connection in
do {
try connection.close()
} catch let localError {
error = localError
}
}
self.connectedDatabases.removeAll()
}
return error
}
public var connectedDatabasesCount: Int {
return queue.sync { connectedDatabases.count }
}
}