Skip to content

A native macOS / windows / Linux database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.

C++

feat(import): add connection import from external database tools

Tobib750f4fe3515
diff --git a/macos/Core/Enums/ColorTag.swift b/macos/Core/Enums/ColorTag.swift
index a07c7f2..2446592 100644
--- a/macos/Core/Enums/ColorTag.swift
+++ b/macos/Core/Enums/ColorTag.swift
@@ -37,4 +37,16 @@ enum ColorTag: String, Codable, Sendable, CaseIterable {
case .gray: return "Other"
}
}
+
+ static func fromHex(_ hex: String) -> ColorTag? {
+ let h = hex.lowercased().trimmingCharacters(in: CharacterSet(charactersIn: "#"))
+ switch h {
+ case "ff0000", "e74c4a", "dc3545", "ff4d4d": return .red
+ case "ff9500", "ffa500", "f0a028", "ef9f27": return .orange
+ case "28a745", "34c759", "4cd964", "63993d": return .green
+ case "007aff", "378ae5", "0d6efd", "3a8bdd": return .blue
+ case "5856d6", "534ab7", "6f42c1", "534bb8": return .purple
+ default: return .gray
+ }
+ }
}
diff --git a/macos/Presentation/Views/Main/MainView.swift b/macos/Presentation/Views/Main/MainView.swift
index 49983a0..03a9c98 100644
--- a/macos/Presentation/Views/Main/MainView.swift
+++ b/macos/Presentation/Views/Main/MainView.swift
@@ -121,6 +121,7 @@ struct HomeView: View {
@State private var renameGroupName = ""
@State private var editingConnection: ConnectionConfig?
@State private var showConnectionError = false
+ @State private var showTablePlusImport = false
@ObservedObject private var updater = UpdaterService.shared
var body: some View {
@@ -211,6 +212,9 @@ struct HomeView: View {
appState: appState
)
}
+ .sheet(isPresented: $showTablePlusImport) {
+ ImportConnectionsSheet()
+ }
}
// MARK: - Left Branding Panel
@@ -253,6 +257,10 @@ struct HomeView: View {
Spacer()
VStack(spacing: 2) {
+ HomeActionButton(icon: "square.and.arrow.down.fill", title: "Import Connections") {
+ showTablePlusImport = true
+ }
+
HomeActionButton(icon: "arrow.up.doc.fill", title: "Backup database…") {
BackupRestorePanel.openBackupWizard(appState: appState)
}
@@ -2186,3 +2194,406 @@ final class ResizeHandleView: NSView {
setWidth?(newWidth)
}
}
+
+// MARK: - TablePlus Import Sheet
+
+struct ImportConnectionsSheet: View {
+ @EnvironmentObject private var appState: AppState
+ @Environment(\.dismiss) private var dismiss
+ @State private var selectedSource: ImportSource?
+ @State private var connections: [ImportedConnection] = []
+ @State private var selected: Set<String> = []
+ @State private var isLoading = false
+ @State private var errorMessage: String?
+ @State private var isImporting = false
+ @State private var navicatFileURL: URL?
+
+ private var availableSources: [ImportSource] {
+ ImportSource.allCases
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ Text("Import Connections")
+ .font(.system(size: 15, weight: .semibold))
+ .padding(.top, 20)
+ .padding(.bottom, 4)
+
+ Text(selectedSource == nil ? "Select a source to import from" : "Select connections to import")
+ .font(.system(size: 12))
+ .foregroundStyle(.secondary)
+ .padding(.bottom, 16)
+
+ if selectedSource == nil {
+ sourceSelectionView
+ } else if isLoading {
+ ProgressView()
+ .padding(40)
+ } else if let error = errorMessage {
+ errorView(error)
+ } else if connections.isEmpty {
+ emptyView
+ } else {
+ connectionsList
+ }
+
+ Divider()
+ bottomBar
+ }
+ .frame(width: 520, height: 450)
+ }
+
+ private var sourceSelectionView: some View {
+ VStack(spacing: 12) {
+ ForEach(availableSources, id: \.self) { source in
+ SourceRow(source: source) {
+ if source == .navicat {
+ pickNavicatFile()
+ } else {
+ selectedSource = source
+ loadConnections(from: source)
+ }
+ }
+ }
+
+ if availableSources.isEmpty {
+ VStack(spacing: 12) {
+ Image(systemName: "app.dashed")
+ .font(.system(size: 32))
+ .foregroundStyle(.tertiary)
+ Text("No supported database tools detected")
+ .font(.system(size: 12))
+ .foregroundStyle(.secondary)
+ }
+ .padding(40)
+ }
+ }
+ .padding(.horizontal, 20)
+ .frame(maxHeight: .infinity)
+ }
+
+ private func errorView(_ error: String) -> some View {
+ VStack(spacing: 12) {
+ Image(systemName: "exclamationmark.triangle")
+ .font(.system(size: 32))
+ .foregroundStyle(.orange)
+ Text(error)
+ .font(.system(size: 12))
+ .foregroundStyle(.secondary)
+ .multilineTextAlignment(.center)
+ }
+ .padding(40)
+ }
+
+ private var emptyView: some View {
+ VStack(spacing: 12) {
+ Image(systemName: "tray")
+ .font(.system(size: 32))
+ .foregroundStyle(.tertiary)
+ Text("No connections found")
+ .font(.system(size: 12))
+ .foregroundStyle(.secondary)
+ }
+ .padding(40)
+ }
+
+ private var connectionsList: some View {
+ List(connections, id: \.id) { conn in
+ HStack(spacing: 12) {
+ Image(systemName: selected.contains(conn.id) ? "checkmark.circle.fill" : "circle")
+ .font(.system(size: 16))
+ .foregroundStyle(selected.contains(conn.id) ? Color.blue : Color.secondary.opacity(0.4))
+
+ DatabaseTypeIcon(type: conn.databaseType, size: 28)
+
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 6) {
+ Text(conn.name)
+ .font(.system(size: 13, weight: .medium))
+
+ if let group = conn.group {
+ Text(group)
+ .font(.system(size: 9, weight: .medium))
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 5)
+ .padding(.vertical, 1)
+ .background(Color.secondary.opacity(0.1))
+ .clipShape(RoundedRectangle(cornerRadius: 3))
+ }
+ }
+
+ Text(connectionSubtitle(conn))
+ .font(.system(size: 11, design: .monospaced))
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ }
+
+ Spacer()
+
+ Text(conn.databaseType.displayName)
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(.tertiary)
+ }
+ .padding(.vertical, 4)
+ .contentShape(Rectangle())
+ .onTapGesture {
+ if selected.contains(conn.id) {
+ selected.remove(conn.id)
+ } else {
+ selected.insert(conn.id)
+ }
+ }
+ }
+ .listStyle(.plain)
+ }
+
+ private var bottomBar: some View {
+ HStack {
+ if selectedSource != nil {
+ Button {
+ selectedSource = nil
+ connections = []
+ selected = []
+ errorMessage = nil
+ } label: {
+ HStack(spacing: 4) {
+ Image(systemName: "chevron.left")
+ .font(.system(size: 10, weight: .semibold))
+ Text("Back")
+ }
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(.blue)
+ }
+
+ if !connections.isEmpty && errorMessage == nil {
+ Button(selected.count == connections.count ? "Deselect All" : "Select All") {
+ if selected.count == connections.count {
+ selected.removeAll()
+ } else {
+ selected = Set(connections.map(\.id))
+ }
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(.blue)
+ }
+
+ Spacer()
+
+ Button("Cancel") { dismiss() }
+ .keyboardShortcut(.cancelAction)
+
+ if selectedSource != nil && !connections.isEmpty {
+ Button {
+ Task { await importSelected() }
+ } label: {
+ if isImporting {
+ ProgressView().controlSize(.small)
+ }
+ Text("Import \(selected.count)")
+ }
+ .buttonStyle(.borderedProminent)
+ .disabled(selected.isEmpty || isImporting)
+ .keyboardShortcut(.defaultAction)
+ }
+ }
+ .padding(.horizontal, 20)
+ .padding(.vertical, 14)
+ }
+
+ private func connectionSubtitle(_ conn: ImportedConnection) -> String {
+ if conn.databaseType == .sqlite {
+ return conn.filePath ?? "No file"
+ }
+ var parts: [String] = []
+ if let host = conn.host {
+ parts.append(host)
+ if let port = conn.port {
+ parts.append(":\(port)")
+ }
+ }
+ if let db = conn.database, !db.isEmpty {
+ parts.append(" / \(db)")
+ }
+ return parts.joined()
+ }
+
+ private func pickNavicatFile() {
+ let panel = NSOpenPanel()
+ panel.title = "Select Navicat Export File (.ncx)"
+ panel.allowsMultipleSelection = false
+ panel.canChooseDirectories = false
+ panel.canChooseFiles = true
+ panel.allowedContentTypes = [.xml, .data]
+
+ if panel.runModal() == .OK, let url = panel.url {
+ selectedSource = .navicat
+ loadNavicatConnections(from: url)
+ }
+ }
+
+ private func loadNavicatConnections(from url: URL) {
+ isLoading = true
+ errorMessage = nil
+
+ do {
+ connections = try NavicatImporter.importFromNCX(at: url)
+ selected = Set(connections.map(\.id))
+ } catch {
+ errorMessage = error.localizedDescription
+ }
+
+ isLoading = false
+ }
+
+ private func loadConnections(from source: ImportSource) {
+ isLoading = true
+ errorMessage = nil
+
+ do {
+ switch source {
+ case .tableplus:
+ connections = try TablePlusImporter.importConnections()
+ case .dbeaver:
+ connections = try DBeaverImporter.importConnections()
+ case .datagrip:
+ connections = try DataGripImporter.importConnections()
+ case .navicat:
+ break
+ }
+ selected = Set(connections.map(\.id))
+ } catch {
+ errorMessage = error.localizedDescription
+ }
+
+ isLoading = false
+ }
+
+ private func importSelected() async {
+ isImporting = true
+
+ let toImport = connections.filter { selected.contains($0.id) }
+ let keychain = appState.container.keychainService
+
+ for imported in toImport {
+ let config = imported.toConnectionConfig()
+
+ do {
+ try await appState.container.connectionRepository.save(config)
+
+ if let pw = imported.password, !pw.isEmpty {
+ try? keychain.save(key: "db.password.\(config.id.uuidString)", value: pw)
+ }
+
+ if let group = imported.group {
+ appState.connectionGroups.insert(group)
+ }
+ } catch {
+ // Continue importing others
+ }
+ }
+
+ await appState.loadSavedConnections()
+ isImporting = false
+ dismiss()
+ }
+}
+
+struct SourceRow: View {
+ let source: ImportSource
+ let action: () -> Void
+ @State private var isHovered = false
+
+ private var isEnabled: Bool {
+ source.isInstalled || source == .navicat
+ }
+
+ var body: some View {
+ Button(action: action) {
+ HStack(spacing: 14) {
+ ZStack {
+ RoundedRectangle(cornerRadius: 8)
+ .fill(sourceGradient)
+ .frame(width: 40, height: 40)
+ Text(source.iconLetter)
+ .font(.system(size: 14, weight: .bold, design: .rounded))
+ .foregroundStyle(.white)
+ }
+
+ VStack(alignment: .leading, spacing: 2) {
+ Text(source.rawValue)
+ .font(.system(size: 14, weight: .medium))
+ Text(sourceDescription)
+ .font(.system(size: 11))
+ .foregroundStyle(.secondary)
+ }
+
+ Spacer()
+
+ if source.isInstalled {
+ Text("Installed")
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(.green)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 3)
+ .background(Color.green.opacity(0.1))
+ .clipShape(RoundedRectangle(cornerRadius: 4))
+ } else if source == .navicat {
+ Text("Select .ncx")
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(.blue)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 3)
+ .background(Color.blue.opacity(0.1))
+ .clipShape(RoundedRectangle(cornerRadius: 4))
+ } else {
+ Text("Not Found")
+ .font(.system(size: 10, weight: .medium))
+ .foregroundStyle(.secondary)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 3)
+ .background(Color.secondary.opacity(0.1))
+ .clipShape(RoundedRectangle(cornerRadius: 4))
+ }
+
+ Image(systemName: "chevron.right")
+ .font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(.tertiary)
+ }
+ .padding(.horizontal, 14)
+ .padding(.vertical, 12)
+ .background(isHovered && isEnabled ? Color.primary.opacity(0.05) : Color.clear)
+ .clipShape(RoundedRectangle(cornerRadius: 10))
+ .overlay(
+ RoundedRectangle(cornerRadius: 10)
+ .stroke(Color.primary.opacity(0.08), lineWidth: 1)
+ )
+ }
+ .buttonStyle(.plain)
+ .onHover { isHovered = $0 }
+ .disabled(!isEnabled)
+ .opacity(source.isInstalled || source == .navicat ? 1 : 0.5)
+ }
+
+ private var sourceGradient: LinearGradient {
+ switch source {
+ case .tableplus:
+ return LinearGradient(colors: [Color(red: 0.95, green: 0.55, blue: 0.15), Color(red: 0.85, green: 0.40, blue: 0.10)], startPoint: .top, endPoint: .bottom)
+ case .dbeaver:
+ return LinearGradient(colors: [Color(red: 0.55, green: 0.45, blue: 0.35), Color(red: 0.40, green: 0.30, blue: 0.25)], startPoint: .top, endPoint: .bottom)
+ case .datagrip:
+ return LinearGradient(colors: [Color(red: 0.20, green: 0.75, blue: 0.60), Color(red: 0.10, green: 0.55, blue: 0.45)], startPoint: .top, endPoint: .bottom)
+ case .navicat:
+ return LinearGradient(colors: [Color(red: 0.0, green: 0.65, blue: 0.85), Color(red: 0.0, green: 0.50, blue: 0.70)], startPoint: .top, endPoint: .bottom)
+ }
+ }
+
+ private var sourceDescription: String {
+ switch source {
+ case .tableplus: return "Import from TablePlus favorites"
+ case .dbeaver: return "Import from DBeaver workspace"
+ case .datagrip: return "Import from JetBrains DataGrip"
+ case .navicat: return "Import from Navicat .ncx export file"
+ }
+ }
+}
diff --git a/macos/Resources/Info.plist b/macos/Resources/Info.plist
index 3d11006..af1c770 100644
--- a/macos/Resources/Info.plist
+++ b/macos/Resources/Info.plist
@@ -32,9 +32,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
- <string>0.0.2</string>
+ <string>0.0.3</string>
<key>CFBundleVersion</key>
- <string>2</string>
+ <string>3</string>
<key>LSMinimumSystemVersion</key>
<string>14.0</string>
<key>NSAppTransportSecurity</key>
diff --git a/macos/Services/Import/DBeaverImporter.swift b/macos/Services/Import/DBeaverImporter.swift
new file mode 100644
index 0000000..a5146a4
--- /dev/null
+++ b/macos/Services/Import/DBeaverImporter.swift
@@ -0,0 +1,172 @@
+// DBeaverImporter.swift
+// Gridex
+//
+// Imports database connections from DBeaver.
+
+import Foundation
+
+struct DBeaverImporter {
+
+ static let dataSourcesPath = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/DBeaverData/workspace6/General/.dbeaver/data-sources.json")
+
+ static let credentialsPath = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/DBeaverData/workspace6/General/.dbeaver/credentials-config.json")
+
+ static var isInstalled: Bool {
+ FileManager.default.fileExists(atPath: dataSourcesPath.path)
+ }
+
+ static func importConnections() throws -> [ImportedConnection] {
+ guard FileManager.default.fileExists(atPath: dataSourcesPath.path) else {
+ throw ImportError.fileNotFound
+ }
+
+ let data = try Data(contentsOf: dataSourcesPath)
+ guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ throw ImportError.invalidFormat
+ }
+
+ let credentials = loadCredentials()
+ var results: [ImportedConnection] = []
+
+ for (_, folderValue) in json {
+ guard let folder = folderValue as? [String: Any],
+ let connections = folder["connections"] as? [String: Any] else { continue }
+
+ for (connId, connValue) in connections {
+ guard let conn = connValue as? [String: Any],
+ let name = conn["name"] as? String,
+ let provider = conn["provider"] as? String else { continue }
+
+ let dbType = mapProvider(provider)
+ let config = conn["configuration"] as? [String: Any] ?? [:]
+
+ let host = config["host"] as? String
+ let port = config["port"] as? String
+ let database = config["database"] as? String
+ let url = config["url"] as? String
+
+ var username: String?
+ var password: String?
+
+ if let authModel = config["auth-model"] as? String, authModel == "native" {
+ username = credentials[connId]?["user"]
+ password = credentials[connId]?["password"]
+ }
+
+ let sslEnabled = (config["ssl"] as? String) == "true"
+
+ let imported = ImportedConnection(
+ id: connId,
+ source: .dbeaver,
+ name: name,
+ databaseType: dbType,
+ host: host ?? parseHostFromURL(url),
+ port: port.flatMap { Int($0) } ?? parsePortFromURL(url),
+ database: database ?? parseDatabaseFromURL(url),
+ username: username,
+ password: password,
+ sslEnabled: sslEnabled,
+ filePath: nil,
+ sshHost: nil,
+ sshPort: nil,
+ sshUser: nil,
+ colorHex: nil,
+ group: nil
+ )
+ results.append(imported)
+ }
+ }
+
+ return results
+ }
+
+ private static func loadCredentials() -> [String: [String: String]] {
+ guard FileManager.default.fileExists(atPath: credentialsPath.path),
+ let data = try? Data(contentsOf: credentialsPath),
+ let decrypted = decryptDBeaverCredentials(data),
+ let json = try? JSONSerialization.jsonObject(with: decrypted) as? [String: Any] else {
+ return [:]
+ }
+
+ var result: [String: [String: String]] = [:]
+ for (key, value) in json {
+ if let creds = value as? [String: String] {
+ let connId = key.replacingOccurrences(of: "data-source|", with: "")
+ result[connId] = creds
+ }
+ }
+ return result
+ }
+
+ private static func decryptDBeaverCredentials(_ data: Data) -> Data? {
+ guard let content = String(data: data, encoding: .utf8) else { return nil }
+ guard let decoded = Data(base64Encoded: content) else { return nil }
+
+ let key: [UInt8] = [
+ 0xBA, 0xBB, 0x4A, 0x9F, 0x7A, 0xEE, 0x8F, 0xC1
+ ]
+
+ var decrypted = [UInt8](repeating: 0, count: decoded.count)
+ let bytes = [UInt8](decoded)
+
+ for i in 0..<bytes.count {
+ decrypted[i] = bytes[i] ^ key[i % key.count]
+ }
+
+ return Data(decrypted)
+ }
+
+ private static func mapProvider(_ provider: String) -> DatabaseType {
+ let lower = provider.lowercased()
+ if lower.contains("postgres") { return .postgresql }
+ if lower.contains("mysql") || lower.contains("maria") { return .mysql }
+ if lower.contains("sqlite") { return .sqlite }
+ if lower.contains("redis") { return .redis }
+ if lower.contains("mongo") { return .mongodb }
+ if lower.contains("sqlserver") || lower.contains("mssql") { return .mssql }
+ return .postgresql
+ }
+
+ private static func parseHostFromURL(_ url: String?) -> String? {
+ guard let url = url else { return nil }
+ let pattern = #"://([^:/]+)"#
+ guard let regex = try? NSRegularExpression(pattern: pattern),
+ let match = regex.firstMatch(in: url, range: NSRange(url.startIndex..., in: url)),
+ let range = Range(match.range(at: 1), in: url) else { return nil }
+ return String(url[range])
+ }
+
+ private static func parsePortFromURL(_ url: String?) -> Int? {
+ guard let url = url else { return nil }
+ let pattern = #":(\d+)/"#
+ guard let regex = try? NSRegularExpression(pattern: pattern),
+ let match = regex.firstMatch(in: url, range: NSRange(url.startIndex..., in: url)),
+ let range = Range(match.range(at: 1), in: url) else { return nil }
+ return Int(url[range])
+ }
+
+ private static func parseDatabaseFromURL(_ url: String?) -> String? {
+ guard let url = url else { return nil }
+ let pattern = #"/([^/?]+)(?:\?|$)"#
+ guard let regex = try? NSRegularExpression(pattern: pattern),
+ let match = regex.firstMatch(in: url, range: NSRange(url.startIndex..., in: url)),
+ let range = Range(match.range(at: 1), in: url) else { return nil }
+ return String(url[range])
+ }
+
+ enum ImportError: LocalizedError {
+ case fileNotFound
+ case invalidFormat
+
+ var errorDescription: String? {
+ switch self {
+ case .fileNotFound:
+ return "DBeaver data sources file not found."
+ case .invalidFormat:
+ return "Unable to parse DBeaver data sources."
+ }
+ }
+ }
+}
diff --git a/macos/Services/Import/DataGripImporter.swift b/macos/Services/Import/DataGripImporter.swift
new file mode 100644
index 0000000..4b40cfb
--- /dev/null
+++ b/macos/Services/Import/DataGripImporter.swift
@@ -0,0 +1,209 @@
+// DataGripImporter.swift
+// Gridex
+//
+// Imports database connections from JetBrains DataGrip.
+
+import Foundation
+
+struct DataGripImporter {
+
+ static var dataGripBasePath: URL? {
+ let appSupport = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Application Support/JetBrains")
+
+ guard FileManager.default.fileExists(atPath: appSupport.path) else { return nil }
+
+ let contents = (try? FileManager.default.contentsOfDirectory(at: appSupport, includingPropertiesForKeys: nil)) ?? []
+ let dataGripDirs = contents.filter { $0.lastPathComponent.hasPrefix("DataGrip") }
+ .sorted { $0.lastPathComponent > $1.lastPathComponent }
+
+ return dataGripDirs.first
+ }
+
+ static var isInstalled: Bool {
+ dataGripBasePath != nil
+ }
+
+ static func importConnections() throws -> [ImportedConnection] {
+ guard let basePath = dataGripBasePath else {
+ throw ImportError.fileNotFound
+ }
+
+ var results: [ImportedConnection] = []
+
+ let optionsPath = basePath.appendingPathComponent("options/dataSources.xml")
+ if FileManager.default.fileExists(atPath: optionsPath.path) {
+ results.append(contentsOf: try parseDataSourcesXML(at: optionsPath))
+ }
+
+ let projectsPath = basePath.appendingPathComponent("projects")
+ if FileManager.default.fileExists(atPath: projectsPath.path) {
+ let projects = (try? FileManager.default.contentsOfDirectory(at: projectsPath, includingPropertiesForKeys: nil)) ?? []
+ for project in projects {
+ let dsPath = project.appendingPathComponent(".idea/dataSources.xml")
+ if FileManager.default.fileExists(atPath: dsPath.path) {
+ results.append(contentsOf: (try? parseDataSourcesXML(at: dsPath)) ?? [])
+ }
+ }
+ }
+
+ return results
+ }
+
+ private static func parseDataSourcesXML(at url: URL) throws -> [ImportedConnection] {
+ let data = try Data(contentsOf: url)
+ let parser = DataGripXMLParser(data: data)
+ return parser.parse()
+ }
+
+ enum ImportError: LocalizedError {
+ case fileNotFound
+ case invalidFormat
+
+ var errorDescription: String? {
+ switch self {
+ case .fileNotFound:
+ return "DataGrip configuration not found."
+ case .invalidFormat:
+ return "Unable to parse DataGrip data sources."
+ }
+ }
+ }
+}
+
+private class DataGripXMLParser: NSObject, XMLParserDelegate {
+ private let data: Data
+ private var connections: [ImportedConnection] = []
+ private var currentDataSource: [String: String] = [:]
+ private var currentElement = ""
+ private var inDataSource = false
+
+ init(data: Data) {
+ self.data = data
+ }
+
+ func parse() -> [ImportedConnection] {
+ let parser = XMLParser(data: data)
+ parser.delegate = self
+ parser.parse()
+ return connections
+ }
+
+ func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?,
+ qualifiedName qName: String?, attributes: [String: String] = [:]) {
+ currentElement = elementName
+
+ if elementName == "data-source" {
+ inDataSource = true
+ currentDataSource = [:]
+ if let name = attributes["name"] { currentDataSource["name"] = name }
+ if let uuid = attributes["uuid"] { currentDataSource["id"] = uuid }
+ }
+
+ if inDataSource {
+ if elementName == "driver-ref" {
+ currentDataSource["driver"] = attributes[""]
+ }
+ if elementName == "jdbc-url", let text = attributes["value"] {
+ currentDataSource["url"] = text
+ }
+ }
+ }
+
+ func parser(_ parser: XMLParser, foundCharacters string: String) {
+ guard inDataSource else { return }
+ let trimmed = string.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return }
+
+ switch currentElement {
+ case "driver-ref":
+ currentDataSource["driver"] = trimmed
+ case "jdbc-url":
+ currentDataSource["url"] = trimmed
+ case "jdbc-driver":
+ currentDataSource["jdbcDriver"] = trimmed
+ default:
+ break
+ }
+ }
+
+ func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
+ if elementName == "data-source" {
+ if let name = currentDataSource["name"] {
+ let driver = currentDataSource["driver"] ?? currentDataSource["jdbcDriver"] ?? ""
+ let url = currentDataSource["url"] ?? ""
+
+ let dbType = mapDriver(driver, url: url)
+ let (host, port, database) = parseJDBCUrl(url)
+
+ let conn = ImportedConnection(
+ id: currentDataSource["id"] ?? UUID().uuidString,
+ source: .datagrip,
+ name: name,
+ databaseType: dbType,
+ host: host,
+ port: port,
+ database: database,
+ username: nil,
+ password: nil,
+ sslEnabled: url.contains("ssl=true"),
+ filePath: nil,
+ sshHost: nil,
+ sshPort: nil,
+ sshUser: nil,
+ colorHex: nil,
+ group: nil
+ )
+ connections.append(conn)
+ }
+ inDataSource = false
+ currentDataSource = [:]
+ }
+ }
+
+ private func mapDriver(_ driver: String, url: String) -> DatabaseType {
+ let combined = (driver + url).lowercased()
+ if combined.contains("postgres") { return .postgresql }
+ if combined.contains("mysql") || combined.contains("maria") { return .mysql }
+ if combined.contains("sqlite") { return .sqlite }
+ if combined.contains("redis") { return .redis }
+ if combined.contains("mongo") { return .mongodb }
+ if combined.contains("sqlserver") || combined.contains("mssql") { return .mssql }
+ return .postgresql
+ }
+
+ private func parseJDBCUrl(_ url: String) -> (String?, Int?, String?) {
+ var host: String?
+ var port: Int?
+ var database: String?
+
+ let hostPattern = #"://([^:/]+)"#
+ if let regex = try? NSRegularExpression(pattern: hostPattern),
+ let match = regex.firstMatch(in: url, range: NSRange(url.startIndex..., in: url)),
+ let range = Range(match.range(at: 1), in: url) {
+ host = String(url[range])
+ }
+
+ let portPattern = #":(\d+)[/;]"#
+ if let regex = try? NSRegularExpression(pattern: portPattern),
+ let match = regex.firstMatch(in: url, range: NSRange(url.startIndex..., in: url)),
+ let range = Range(match.range(at: 1), in: url) {
+ port = Int(url[range])
+ }
+
+ let dbPatterns = [
+ #"/([^/?;]+)(?:\?|;|$)"#,
+ #"databaseName=([^;&]+)"#
+ ]
+ for pattern in dbPatterns {
+ if let regex = try? NSRegularExpression(pattern: pattern),
+ let match = regex.firstMatch(in: url, range: NSRange(url.startIndex..., in: url)),
+ let range = Range(match.range(at: 1), in: url) {
+ database = String(url[range])
+ break
+ }
+ }
+
+ return (host, port, database)
+ }
+}
diff --git a/macos/Services/Import/ImportedConnection.swift b/macos/Services/Import/ImportedConnection.swift
new file mode 100644
index 0000000..ba84bd4
--- /dev/null
+++ b/macos/Services/Import/ImportedConnection.swift
@@ -0,0 +1,79 @@
+// ImportedConnection.swift
+// Gridex
+//
+// Shared model for imported connections from external tools.
+
+import Foundation
+
+enum ImportSource: String, CaseIterable {
+ case tableplus = "TablePlus"
+ case dbeaver = "DBeaver"
+ case datagrip = "DataGrip"
+ case navicat = "Navicat"
+
+ var iconLetter: String {
+ switch self {
+ case .tableplus: return "T+"
+ case .dbeaver: return "DB"
+ case .datagrip: return "DG"
+ case .navicat: return "N"
+ }
+ }
+
+ var isInstalled: Bool {
+ switch self {
+ case .tableplus: return TablePlusImporter.isInstalled
+ case .dbeaver: return DBeaverImporter.isInstalled
+ case .datagrip: return DataGripImporter.isInstalled
+ case .navicat: return NavicatImporter.isInstalled
+ }
+ }
+}
+
+struct ImportedConnection: Identifiable {
+ let id: String
+ let source: ImportSource
+ let name: String
+ let databaseType: DatabaseType
+ let host: String?
+ let port: Int?
+ let database: String?
+ let username: String?
+ let password: String?
+ let sslEnabled: Bool
+ let filePath: String?
+ let sshHost: String?
+ let sshPort: Int?
+ let sshUser: String?
+ let colorHex: String?
+ let group: String?
+
+ func toConnectionConfig() -> ConnectionConfig {
+ var sshConfig: SSHTunnelConfig?
+ if let sshHost = sshHost, let sshUser = sshUser {
+ sshConfig = SSHTunnelConfig(
+ host: sshHost,
+ port: sshPort ?? 22,
+ username: sshUser,
+ authMethod: .password
+ )
+ }
+
+ let colorTag = colorHex.flatMap { ColorTag.fromHex($0) }
+
+ return ConnectionConfig(
+ id: UUID(),
+ name: name,
+ databaseType: databaseType,
+ host: host,
+ port: port,
+ database: database,
+ username: username,
+ sslEnabled: sslEnabled,
+ colorTag: colorTag,
+ group: group,
+ filePath: filePath,
+ sshConfig: sshConfig
+ )
+ }
+}
diff --git a/macos/Services/Import/NavicatImporter.swift b/macos/Services/Import/NavicatImporter.swift
new file mode 100644
index 0000000..7089a67
--- /dev/null
+++ b/macos/Services/Import/NavicatImporter.swift
@@ -0,0 +1,215 @@
+// NavicatImporter.swift
+// Gridex
+//
+// Imports database connections from Navicat via NCX export files.
+
+import Foundation
+import CommonCrypto
+
+struct NavicatImporter {
+
+ static let profilesPath = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Application Support/PremiumSoft CyberTech/Navicat CC/Navicat Premium/profiles")
+
+ static var isInstalled: Bool {
+ let appSupport = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Application Support/PremiumSoft CyberTech")
+ return FileManager.default.fileExists(atPath: appSupport.path)
+ }
+
+ static func importFromNCX(at url: URL) throws -> [ImportedConnection] {
+ let data = try Data(contentsOf: url)
+ let parser = NavicatNCXParser(data: data)
+ return parser.parse()
+ }
+
+ static func decryptPassword(_ encrypted: String) -> String? {
+ guard !encrypted.isEmpty else { return nil }
+
+ let keyString = "3DC5CA39"
+ guard let keyData = keyString.data(using: .ascii) else { return nil }
+
+ var sha1Hash = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
+ keyData.withUnsafeBytes { ptr in
+ _ = CC_SHA1(ptr.baseAddress, CC_LONG(keyData.count), &sha1Hash)
+ }
+
+ guard let encryptedData = hexStringToData(encrypted) else { return nil }
+
+ var decrypted = [UInt8]()
+ var previousBlock = [UInt8](repeating: 0xFF, count: 8)
+
+ let bytes = [UInt8](encryptedData)
+ var i = 0
+ while i < bytes.count {
+ let blockSize = min(8, bytes.count - i)
+ var block = Array(bytes[i..<i+blockSize])
+
+ while block.count < 8 {
+ block.append(0)
+ }
+
+ let decryptedBlock = blowfishDecrypt(block: block, key: sha1Hash)
+
+ for j in 0..<blockSize {
+ decrypted.append(decryptedBlock[j] ^ previousBlock[j])
+ }
+
+ previousBlock = block
+ i += 8
+ }
+
+ while let last = decrypted.last, last == 0 {
+ decrypted.removeLast()
+ }
+
+ return String(bytes: decrypted, encoding: .utf8)
+ }
+
+ private static func hexStringToData(_ hex: String) -> Data? {
+ var data = Data()
+ var index = hex.startIndex
+ while index < hex.endIndex {
+ let nextIndex = hex.index(index, offsetBy: 2, limitedBy: hex.endIndex) ?? hex.endIndex
+ if let byte = UInt8(hex[index..<nextIndex], radix: 16) {
+ data.append(byte)
+ }
+ index = nextIndex
+ }
+ return data.isEmpty ? nil : data
+ }
+
+ private static func blowfishDecrypt(block: [UInt8], key: [UInt8]) -> [UInt8] {
+ var outBuffer = [UInt8](repeating: 0, count: 8)
+ var numBytesDecrypted: size_t = 0
+
+ key.withUnsafeBytes { keyPtr in
+ block.withUnsafeBytes { dataPtr in
+ outBuffer.withUnsafeMutableBytes { outPtr in
+ CCCrypt(
+ CCOperation(kCCDecrypt),
+ CCAlgorithm(kCCAlgorithmBlowfish),
+ CCOptions(kCCOptionECBMode),
+ keyPtr.baseAddress, min(key.count, kCCKeySizeMaxBlowfish),
+ nil,
+ dataPtr.baseAddress, 8,
+ outPtr.baseAddress, 8,
+ &numBytesDecrypted
+ )
+ }
+ }
+ }
+
+ return outBuffer
+ }
+
+ enum ImportError: LocalizedError {
+ case fileNotFound
+ case invalidFormat
+
+ var errorDescription: String? {
+ switch self {
+ case .fileNotFound:
+ return "Navicat NCX file not found."
+ case .invalidFormat:
+ return "Unable to parse Navicat NCX file."
+ }
+ }
+ }
+}
+
+private class NavicatNCXParser: NSObject, XMLParserDelegate {
+ private let data: Data
+ private var connections: [ImportedConnection] = []
+ private var currentConnection: [String: String] = [:]
+ private var currentElement = ""
+ private var inConnection = false
+ private var elementStack: [String] = []
+
+ init(data: Data) {
+ self.data = data
+ }
+
+ func parse() -> [ImportedConnection] {
+ let parser = XMLParser(data: data)
+ parser.delegate = self
+ parser.parse()
+ return connections
+ }
+
+ func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?,
+ qualifiedName qName: String?, attributes: [String: String] = [:]) {
+ elementStack.append(elementName)
+ currentElement = elementName
+
+ if elementName == "Connection" {
+ inConnection = true
+ currentConnection = [:]
+ if let connType = attributes["ConnType"] {
+ currentConnection["connType"] = connType
+ }
+ }
+ }
+
+ func parser(_ parser: XMLParser, foundCharacters string: String) {
+ guard inConnection else { return }
+ let trimmed = string.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { return }
+
+ currentConnection[currentElement] = (currentConnection[currentElement] ?? "") + trimmed
+ }
+
+ func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
+ if elementName == "Connection" {
+ if let name = currentConnection["ConnectionName"] ?? currentConnection["Name"] {
+ let connType = currentConnection["connType"] ?? currentConnection["ConnType"] ?? ""
+ let dbType = mapConnType(connType)
+
+ let encryptedPw = currentConnection["Password"] ?? ""
+ let password = NavicatImporter.decryptPassword(encryptedPw)
+
+ let conn = ImportedConnection(
+ id: UUID().uuidString,
+ source: .navicat,
+ name: name,
+ databaseType: dbType,
+ host: currentConnection["Host"],
+ port: currentConnection["Port"].flatMap { Int($0) },
+ database: currentConnection["DatabaseName"] ?? currentConnection["InitialDatabase"],
+ username: currentConnection["UserName"],
+ password: password,
+ sslEnabled: currentConnection["SSL"] == "true" || currentConnection["UseSSL"] == "1",
+ filePath: currentConnection["DatabaseFile"],
+ sshHost: currentConnection["SSH_Host"],
+ sshPort: currentConnection["SSH_Port"].flatMap { Int($0) },
+ sshUser: currentConnection["SSH_UserName"],
+ colorHex: nil,
+ group: nil
+ )
+ connections.append(conn)
+ }
+ inConnection = false
+ currentConnection = [:]
+ }
+
+ if !elementStack.isEmpty {
+ elementStack.removeLast()
+ }
+ }
+
+ private func mapConnType(_ connType: String) -> DatabaseType {
+ let lower = connType.lowercased()
+ if lower.contains("postgres") { return .postgresql }
+ if lower.contains("mysql") || lower.contains("maria") { return .mysql }
+ if lower.contains("sqlite") { return .sqlite }
+ if lower.contains("redis") { return .redis }
+ if lower.contains("mongo") { return .mongodb }
+ if lower.contains("sqlserver") || lower.contains("mssql") { return .mssql }
+ if lower == "1" { return .mysql }
+ if lower == "2" { return .postgresql }
+ if lower == "3" { return .sqlite }
+ if lower == "7" { return .mssql }
+ if lower == "8" { return .mongodb }
+ return .postgresql
+ }
+}
diff --git a/macos/Services/Import/TablePlusImporter.swift b/macos/Services/Import/TablePlusImporter.swift
new file mode 100644
index 0000000..fe6e784
--- /dev/null
+++ b/macos/Services/Import/TablePlusImporter.swift
@@ -0,0 +1,162 @@
+// TablePlusImporter.swift
+// Gridex
+//
+// Imports database connections from TablePlus.
+
+import Foundation
+import Security
+
+struct TablePlusImporter {
+
+ static let connectionsPlistPath = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Application Support/com.tinyapp.TablePlus/Data/Connections.plist")
+
+ static let groupsPlistPath = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Library/Application Support/com.tinyapp.TablePlus/Data/ConnectionGroups.plist")
+
+ static var isInstalled: Bool {
+ FileManager.default.fileExists(atPath: connectionsPlistPath.path)
+ }
+
+ static func importConnections() throws -> [ImportedConnection] {
+ guard FileManager.default.fileExists(atPath: connectionsPlistPath.path) else {
+ throw ImportError.fileNotFound
+ }
+
+ let data = try Data(contentsOf: connectionsPlistPath)
+ guard let plist = try PropertyListSerialization.propertyList(from: data, format: nil) as? [[String: Any]] else {
+ throw ImportError.invalidFormat
+ }
+
+ let groups = loadGroups()
+
+ return plist.compactMap { dict -> ImportedConnection? in
+ guard let id = dict["ID"] as? String,
+ let name = dict["ConnectionName"] as? String,
+ let driver = dict["Driver"] as? String else { return nil }
+
+ let dbType = mapDriver(driver)
+ let host = dict["DatabaseHost"] as? String
+ let portStr = dict["DatabasePort"] as? String
+ let port = portStr.flatMap { Int($0) }
+ let database = dict["DatabaseName"] as? String
+ let username = dict["DatabaseUser"] as? String
+ let tlsMode = dict["tLSMode"] as? Int
+ let sslEnabled = (tlsMode ?? 0) > 0
+
+ let filePath = dict["DatabasePath"] as? String
+
+ let isOverSSH = dict["isOverSSH"] as? Bool ?? false
+ var sshHost: String?
+ var sshPort: Int?
+ var sshUser: String?
+ if isOverSSH {
+ sshHost = dict["ServerAddress"] as? String
+ let sshPortStr = dict["ServerPort"] as? String
+ sshPort = sshPortStr.flatMap { Int($0) } ?? 22
+ sshUser = dict["ServerUser"] as? String
+ }
+
+ let colorHex = dict["statusColor"] as? String
+ let groupId = dict["GroupID"] as? String
+ let groupName = groupId.flatMap { groups[$0] }
+
+ let dbPassword = loadPassword(connectionId: id, type: .database)
+ let sshPassword = isOverSSH ? loadPassword(connectionId: id, type: .ssh) : nil
+
+ return ImportedConnection(
+ id: id,
+ source: .tableplus,
+ name: name,
+ databaseType: dbType,
+ host: host,
+ port: port,
+ database: database,
+ username: username,
+ password: dbPassword,
+ sslEnabled: sslEnabled,
+ filePath: filePath,
+ sshHost: sshHost,
+ sshPort: sshPort,
+ sshUser: sshUser,
+ colorHex: colorHex,
+ group: groupName
+ )
+ }
+ }
+
+ static func loadPassword(connectionId: String, type: PasswordType) -> String? {
+ let account: String
+ switch type {
+ case .database:
+ account = "\(connectionId)_database"
+ case .ssh:
+ account = "\(connectionId)_server"
+ }
+
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: "com.tableplus.TablePlus",
+ kSecAttrAccount as String: account,
+ kSecReturnData as String: true,
+ kSecMatchLimit as String: kSecMatchLimitOne
+ ]
+
+ var result: AnyObject?
+ let status = SecItemCopyMatching(query as CFDictionary, &result)
+
+ guard status == errSecSuccess,
+ let data = result as? Data,
+ let password = String(data: data, encoding: .utf8) else {
+ return nil
+ }
+ return password
+ }
+
+ enum PasswordType {
+ case database
+ case ssh
+ }
+
+ enum ImportError: LocalizedError {
+ case fileNotFound
+ case invalidFormat
+
+ var errorDescription: String? {
+ switch self {
+ case .fileNotFound:
+ return "TablePlus connections file not found."
+ case .invalidFormat:
+ return "Unable to parse TablePlus connections file."
+ }
+ }
+ }
+
+ private static func loadGroups() -> [String: String] {
+ guard FileManager.default.fileExists(atPath: groupsPlistPath.path),
+ let data = try? Data(contentsOf: groupsPlistPath),
+ let plist = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [[String: Any]] else {
+ return [:]
+ }
+
+ var groups: [String: String] = [:]
+ for dict in plist {
+ if let id = dict["ID"] as? String,
+ let name = dict["GroupName"] as? String {
+ groups[id] = name
+ }
+ }
+ return groups
+ }
+
+ private static func mapDriver(_ driver: String) -> DatabaseType {
+ let lower = driver.lowercased()
+ if lower.contains("postgres") { return .postgresql }
+ if lower.contains("mysql") || lower.contains("maria") { return .mysql }
+ if lower.contains("sqlite") { return .sqlite }
+ if lower.contains("redis") { return .redis }
+ if lower.contains("mongo") { return .mongodb }
+ if lower.contains("mssql") || lower.contains("sqlserver") { return .mssql }
+ return .postgresql
+ }
+}