-
-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathConnectedView.swift
More file actions
365 lines (337 loc) · 13.3 KB
/
ConnectedView.swift
File metadata and controls
365 lines (337 loc) · 13.3 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
//
// ConnectedView.swift
// TableProMobile
//
import os
import SwiftUI
import TableProDatabase
import TableProModels
struct ConnectedView: View {
@Environment(AppState.self) private var appState
@Environment(\.scenePhase) private var scenePhase
let connection: DatabaseConnection
private static let logger = Logger(subsystem: "com.TablePro", category: "ConnectedView")
@State private var session: ConnectionSession?
@State private var tables: [TableInfo] = []
@State private var isConnecting = true
@State private var appError: AppError?
@State private var failureAlertMessage: String?
@State private var showFailureAlert = false
@State private var selectedTab = ConnectedTab.tables
@State private var queryHistory: [QueryHistoryItem] = []
private let historyStorage = QueryHistoryStorage()
@State private var databases: [String] = []
@State private var activeDatabase: String = ""
@State private var schemas: [String] = []
@State private var activeSchema: String = "public"
@State private var isSwitching = false
enum ConnectedTab: String, CaseIterable {
case tables = "Tables"
case query = "Query"
}
private var displayName: String {
connection.name.isEmpty ? connection.host : connection.name
}
private var supportsDatabaseSwitching: Bool {
connection.type == .mysql || connection.type == .mariadb ||
connection.type == .postgresql || connection.type == .redshift
}
private var supportsSchemas: Bool {
connection.type == .postgresql || connection.type == .redshift
}
var body: some View {
Group {
if isConnecting {
ProgressView {
Text(String(format: String(localized: "Connecting to %@..."), displayName))
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else if let appError {
ErrorView(error: appError) {
await connect()
}
} else {
connectedContent
.allowsHitTesting(!isSwitching)
.overlay {
if isSwitching {
ZStack {
Rectangle()
.fill(.ultraThinMaterial)
.ignoresSafeArea()
ProgressView()
.controlSize(.large)
}
.transition(.opacity)
}
}
.animation(.default, value: isSwitching)
}
}
.alert("Error", isPresented: $showFailureAlert) {
Button("OK", role: .cancel) {}
} message: {
Text(failureAlertMessage ?? "")
}
.navigationTitle(displayName)
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .principal) {
Picker("Tab", selection: $selectedTab) {
Text("Tables").tag(ConnectedTab.tables)
Text("Query").tag(ConnectedTab.query)
}
.pickerStyle(.segmented)
.frame(width: 200)
}
if supportsDatabaseSwitching && databases.count > 1 {
ToolbarItem(placement: .topBarLeading) {
Menu {
ForEach(databases, id: \.self) { db in
Button {
Task { await switchDatabase(to: db) }
} label: {
if db == activeDatabase {
Label(db, systemImage: "checkmark")
} else {
Text(db)
}
}
}
} label: {
HStack(spacing: 4) {
Text(activeDatabase)
.font(.subheadline)
if isSwitching {
ProgressView()
.controlSize(.mini)
} else {
Image(systemName: "chevron.down")
.font(.caption2)
.foregroundStyle(.secondary)
}
}
}
.disabled(isSwitching)
}
}
if supportsSchemas && schemas.count > 1 {
ToolbarItem(placement: .topBarTrailing) {
Menu {
ForEach(schemas, id: \.self) { schema in
Button {
Task { await switchSchema(to: schema) }
} label: {
if schema == activeSchema {
Label(schema, systemImage: "checkmark")
} else {
Text(schema)
}
}
}
} label: {
Label(activeSchema, systemImage: "square.3.layers.3d")
.font(.subheadline)
}
.disabled(isSwitching)
}
}
}
.task {
await connect()
queryHistory = historyStorage.load(for: connection.id)
}
.onChange(of: scenePhase) { _, phase in
if phase == .active, session != nil {
Task { await reconnectIfNeeded() }
}
}
}
private var connectedContent: some View {
VStack(spacing: 0) {
switch selectedTab {
case .tables:
TableListView(
connection: connection,
tables: tables,
session: session,
onRefresh: { await refreshTables() }
)
case .query:
QueryEditorView(
session: session,
tables: tables,
queryHistory: $queryHistory,
connectionId: connection.id,
historyStorage: historyStorage
)
}
}
}
private func connect() async {
guard session == nil else {
isConnecting = false
return
}
isConnecting = true
appError = nil
// Reuse existing session if still alive in ConnectionManager
if let existing = appState.connectionManager.session(for: connection.id) {
self.session = existing
do {
self.tables = try await existing.driver.fetchTables(schema: nil)
await loadDatabases()
await loadSchemas()
} catch {
// Session stale — disconnect and reconnect
await appState.connectionManager.disconnect(connection.id)
await connectFresh()
return
}
isConnecting = false
return
}
await connectFresh()
}
private func connectFresh() async {
await appState.sshProvider.setPendingConnectionId(connection.id)
do {
let session = try await appState.connectionManager.connect(connection)
self.session = session
self.tables = try await session.driver.fetchTables(schema: nil)
isConnecting = false
await loadDatabases()
await loadSchemas()
} catch {
let context = ErrorContext(
operation: "connect",
databaseType: connection.type,
host: connection.host,
sshEnabled: connection.sshEnabled
)
appError = ErrorClassifier.classify(error, context: context)
isConnecting = false
}
}
private func reconnectIfNeeded() async {
guard let session, !isSwitching else { return }
do {
_ = try await session.driver.ping()
} catch {
// Connection lost — reconnect
do {
await appState.sshProvider.setPendingConnectionId(connection.id)
let newSession = try await appState.connectionManager.connect(connection)
self.session = newSession
} catch {
let context = ErrorContext(
operation: "reconnect",
databaseType: connection.type,
host: connection.host,
sshEnabled: connection.sshEnabled
)
appError = ErrorClassifier.classify(error, context: context)
self.session = nil
}
}
}
private func loadDatabases() async {
guard let session, supportsDatabaseSwitching else { return }
do {
databases = try await session.driver.fetchDatabases()
// Use session's active database (may differ from connection.database after a switch)
if let stored = appState.connectionManager.session(for: connection.id) {
activeDatabase = stored.activeDatabase
} else {
activeDatabase = connection.database
}
} catch {
// Silently fail — just don't show picker
}
}
private func loadSchemas() async {
guard let session, supportsSchemas else { return }
do {
schemas = try await session.driver.fetchSchemas()
activeSchema = session.driver.currentSchema ?? "public"
} catch {
// Silently fail — don't show picker
}
}
private func switchSchema(to name: String) async {
guard let session, name != activeSchema, !isSwitching else { return }
isSwitching = true
defer { isSwitching = false }
do {
try await session.driver.switchSchema(to: name)
activeSchema = name
self.tables = try await session.driver.fetchTables(schema: name)
} catch {
failureAlertMessage = String(localized: "Failed to switch schema")
showFailureAlert = true
}
}
private func switchDatabase(to name: String) async {
guard let session, name != activeDatabase, !isSwitching else { return }
isSwitching = true
defer { isSwitching = false }
if connection.type == .postgresql || connection.type == .redshift {
await reconnectWithDatabase(name)
} else {
do {
try await appState.connectionManager.switchDatabase(connection.id, to: name)
activeDatabase = name
self.tables = try await session.driver.fetchTables(schema: nil)
} catch {
failureAlertMessage = String(localized: "Failed to switch database")
showFailureAlert = true
}
}
}
private func reconnectWithDatabase(_ database: String) async {
await appState.connectionManager.disconnect(connection.id)
self.session = nil
var newConnection = connection
newConnection.database = database
await appState.sshProvider.setPendingConnectionId(connection.id)
do {
let newSession = try await appState.connectionManager.connect(newConnection)
self.session = newSession
self.tables = try await newSession.driver.fetchTables(schema: nil)
activeDatabase = database
await loadSchemas()
} catch {
// Reconnect to original database as fallback
Self.logger.error("Failed to switch to database \(database, privacy: .public): \(error.localizedDescription, privacy: .public)")
await appState.sshProvider.setPendingConnectionId(connection.id)
do {
let fallbackSession = try await appState.connectionManager.connect(connection)
self.session = fallbackSession
self.tables = try await fallbackSession.driver.fetchTables(schema: nil)
failureAlertMessage = String(localized: "Failed to switch database")
showFailureAlert = true
} catch {
// Both failed — show error view
let context = ErrorContext(
operation: "switchDatabase",
databaseType: connection.type,
host: connection.host,
sshEnabled: connection.sshEnabled
)
appError = ErrorClassifier.classify(error, context: context)
self.session = nil
}
}
}
private func refreshTables() async {
guard let session else { return }
do {
let schema = supportsSchemas ? activeSchema : nil
self.tables = try await session.driver.fetchTables(schema: schema)
} catch {
Self.logger.warning("Failed to refresh tables: \(error.localizedDescription, privacy: .public)")
failureAlertMessage = String(localized: "Failed to refresh tables")
showFailureAlert = true
}
}
}