Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(import): carry over DataGrip username and warn on fallback

lxk95514eb34921201
diff --git a/apps/desktop/src/composables/__tests__/useDialogSources.spec.ts b/apps/desktop/src/composables/__tests__/useDialogSources.spec.ts
index d00e648a21..e0319c61ff 100644
--- a/apps/desktop/src/composables/__tests__/useDialogSources.spec.ts
+++ b/apps/desktop/src/composables/__tests__/useDialogSources.spec.ts
@@ -24,6 +24,7 @@ const mocks = vi.hoisted(() => ({
parseConnectionsImport: vi.fn(),
applyConnectionsImport: vi.fn(),
applyDataGripKeychainPasswords: vi.fn(),
+ lastDataGripFallbackUsernamesCount: 0,
exportConnectionsToFile: vi.fn(),
},
}));
diff --git a/apps/desktop/src/composables/useDialogSources.ts b/apps/desktop/src/composables/useDialogSources.ts
index 733cc5c901..4074973894 100644
--- a/apps/desktop/src/composables/useDialogSources.ts
+++ b/apps/desktop/src/composables/useDialogSources.ts
@@ -429,6 +429,9 @@ export function useDialogSources() {
keychainFilled = await connectionStore.applyDataGripKeychainPasswords();
}
toast(importSuccessMessage(source, count, keychainFilled), source === "dbx" ? 2000 : 4000);
+ if (source === "datagrip" && (connectionStore.lastDataGripFallbackUsernamesCount ?? 0) > 0) {
+ toast(t("configExport.importDatagripUsernamesFallbackWarning"), 5000);
+ }
if (hasSidebarLayoutEntries(layout)) {
pendingImportLayout.value = layout;
showImportLayoutConfirm.value = true;
diff --git a/apps/desktop/src/i18n/locales/az.ts b/apps/desktop/src/i18n/locales/az.ts
index 6eae9f2540..f2908f82f1 100644
--- a/apps/desktop/src/i18n/locales/az.ts
+++ b/apps/desktop/src/i18n/locales/az.ts
@@ -2913,6 +2913,7 @@ export default withEnglishFallback({
importDatagripSuccess: "{count} DataGrip əlaqəsi idxal edildi, macOS Keychain-dən {filled} parol dolduruldu.",
importDatagripSelectFiles: "Lütfən, dataSources.xml (məcburi) və istəyə bağlı olaraq dataSources.local.xml / db-forest-config.xml seçin",
importDatagripDialogTitle: "DataGrip konfiqurasiya fayllarını seçin",
+ importDatagripUsernamesFallbackWarning: "Bəzi DataGrip əlaqələrində istifadəçi adı tapılmadı və standart istifadəçi adı istifadə edildi. Zəhmət olmasa etimadnamələri yoxlayın və yeniləyin.",
importDbeaverSuccess: "{count} DBeaver əlaqəsi idxal edildi. Sınaqdan əvvəl parolu hələ boş olan əlaqələrin parollarını doldurun.",
importNone: "İdxal ediləcək yeni əlaqə yoxdur",
importLayoutConfirm: "İdxal edilən faylda əlaqə qrupları var. Onlar tətbiq edilsin?",
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index b61d66827b..e6bf50e5ca 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -3411,6 +3411,7 @@ export default {
importDatagripSuccess: "Imported {count} DataGrip connection(s), filled {filled} password(s) from macOS Keychain.",
importDatagripSelectFiles: "Please select dataSources.xml (required), and optionally dataSources.local.xml / db-forest-config.xml",
importDatagripDialogTitle: "Select DataGrip configuration files",
+ importDatagripUsernamesFallbackWarning: "Some DataGrip connections could not determine usernames and used default database usernames. Please verify and update connection credentials.",
importDbeaverSuccess: "Imported {count} DBeaver connection(s). Fill in any connection whose password is still empty before testing.",
importNone: "No new connections to import",
importLayoutConfirm: "The imported file contains connection groups. Apply them?",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index 928972d25e..2026d0d970 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -3319,6 +3319,7 @@ export default withEnglishFallback({
importLayoutApply: "Aplicar",
importDatagripSelectFiles: "Seleccione dataSources.xml (obligatorio); también puede seleccionar dataSources.local.xml y db-forest-config.xml.",
importDatagripDialogTitle: "Seleccionar archivos de configuración de DataGrip",
+ importDatagripUsernamesFallbackWarning: "Algunas conexiones de DataGrip no pudieron determinar el nombre de usuario y usaron el predeterminado. Verifique y actualice las credenciales.",
selectExportTitle: "Seleccionar conexiones para exportar",
selectImportTitle: "Seleccionar conexiones para importar",
selectAll: "Seleccionar todo",
diff --git a/apps/desktop/src/i18n/locales/id.ts b/apps/desktop/src/i18n/locales/id.ts
index f8c9142cad..d0f5dda6f8 100644
--- a/apps/desktop/src/i18n/locales/id.ts
+++ b/apps/desktop/src/i18n/locales/id.ts
@@ -3215,6 +3215,7 @@ export default withEnglishFallback({
importDatagripSuccess: "{count} koneksi DataGrip diimpor, {filled} kata sandi terisi dari macOS Keychain.",
importDatagripSelectFiles: "Silakan pilih dataSources.xml (wajib), dan secara opsional dataSources.local.xml / db-forest-config.xml",
importDatagripDialogTitle: "Pilih file konfigurasi DataGrip",
+ importDatagripUsernamesFallbackWarning: "Beberapa koneksi DataGrip tidak dapat menentukan nama pengguna dan menggunakan nama pengguna default. Silakan periksa dan perbarui kredensial koneksi.",
importDbeaverSuccess: "{count} koneksi DBeaver diimpor. Isi kata sandi untuk setiap koneksi yang masih kosong sebelum menguji.",
importNone: "Tidak ada koneksi baru untuk diimpor",
importLayoutConfirm: "File yang diimpor berisi grup koneksi. Terapkan grup tersebut?",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 69a34aace7..b633cf2895 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -3170,6 +3170,7 @@ export default withEnglishFallback({
importLayoutApply: "Applica",
importDatagripSelectFiles: "Seleziona dataSources.xml (obbligatorio), puoi selezionare anche dataSources.local.xml e db-forest-config.xml",
importDatagripDialogTitle: "Seleziona i file di configurazione DataGrip",
+ importDatagripUsernamesFallbackWarning: "Alcune connessioni DataGrip non hanno trovato il nome utente e hanno usato quello predefinito. Verificare e aggiornare le credenziali.",
selectExportTitle: "Seleziona le connessioni da esportare",
selectImportTitle: "Seleziona le connessioni da importare",
selectAll: "Seleziona tutto",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index bafaaeb8a6..02e589b68e 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -3194,6 +3194,7 @@ export default withEnglishFallback({
importLayoutApply: "適用",
importDatagripSelectFiles: "dataSources.xml(必須)を選択してください。dataSources.local.xml と db-forest-config.xml も同時に選択できます。",
importDatagripDialogTitle: "DataGrip 設定ファイルを選択",
+ importDatagripUsernamesFallbackWarning: "一部のDataGrip接続でユーザー名が見つからなかったため、デフォルトのユーザー名が設定されました。接続情報を確認・更新してください。",
selectExportTitle: "エクスポートする接続を選択",
selectImportTitle: "インポートする接続を選択",
selectAll: "すべて選択",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 2fe221e7a5..d75f06a348 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -3115,6 +3115,9 @@ export default withEnglishFallback({
importSuccess: "연결 {count}개를 가져왔습니다",
importNavicatSuccess: "Navicat 연결 {count}개를 가져왔습니다. 테스트하기 전에 비밀번호가 비어 있는 연결의 비밀번호를 입력하세요.",
importDatagripSuccess: "DataGrip 연결 {count}개를 가져왔으며, macOS 키체인에서 비밀번호 {filled}개를 채웠습니다.",
+ importDatagripSelectFiles: "dataSources.xml(필수)을 선택하세요. dataSources.local.xml 및 db-forest-config.xml도 함께 선택할 수 있습니다.",
+ importDatagripDialogTitle: "DataGrip 설정 파일 선택",
+ importDatagripUsernamesFallbackWarning: "일부 DataGrip 연결에서 사용자 이름을 찾을 수 없어 기본 사용자 이름이 사용되었습니다. 연결 정보를 확인하고 업데이트하세요.",
importDbeaverSuccess: "DBeaver 연결 {count}개를 가져왔습니다. 테스트하기 전에 비밀번호가 비어 있는 연결의 비밀번호를 입력하세요.",
importNone: "가져올 새 연결이 없습니다",
importLayoutConfirm: "가져온 파일에 연결 그룹이 포함되어 있습니다. 적용하시겠습니까?",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index a765f2c5b1..2dcf69c99d 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -3171,6 +3171,7 @@ export default withEnglishFallback({
importLayoutApply: "Aplicar",
importDatagripSelectFiles: "Selecione dataSources.xml (obrigatório), você também pode selecionar dataSources.local.xml e db-forest-config.xml",
importDatagripDialogTitle: "Selecione o arquivo de configuração do DataGrip",
+ importDatagripUsernamesFallbackWarning: "Algumas conexões do DataGrip não conseguiram determinar o nome de usuário e usaram o padrão. Verifique e atualize as credenciais.",
selectExportTitle: "Selecionar conexões para exportar",
selectImportTitle: "Selecionar conexões para importar",
selectAll: "Selecionar tudo",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index 3869b963fd..0ee68d8608 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -3269,6 +3269,7 @@ export default withEnglishFallback({
importDatagripSuccess: "Импортировано подключений DataGrip: {count}, заполнено паролей из связки ключей macOS: {filled}.",
importDatagripSelectFiles: "Выберите dataSources.xml (обязательно) и, при необходимости, dataSources.local.xml / db-forest-config.xml",
importDatagripDialogTitle: "Выберите файлы конфигурации DataGrip",
+ importDatagripUsernamesFallbackWarning: "Для некоторых подключений DataGrip не удалось определить имя пользователя, использованы значения по умолчанию. Проверьте и обновите учетные данные.",
importDbeaverSuccess: "Импортировано подключений DBeaver: {count}. Перед проверкой заполните пароль для подключений, где он остался пустым.",
importNone: "Нет новых подключений для импорта",
importLayoutConfirm: "Импортированный файл содержит группы подключений. Применить их?",
diff --git a/apps/desktop/src/i18n/locales/tr.ts b/apps/desktop/src/i18n/locales/tr.ts
index 0199fbdb1b..a763d0d5e0 100644
--- a/apps/desktop/src/i18n/locales/tr.ts
+++ b/apps/desktop/src/i18n/locales/tr.ts
@@ -2888,6 +2888,7 @@ export default withEnglishFallback({
importDatagripSuccess: "{count} DataGrip bağlantısı içe aktarıldı, macOS Anahtar Zinciri'nden {filled} parola dolduruldu.",
importDatagripSelectFiles: "Lütfen dataSources.xml (zorunlu) ve isteğe bağlı olarak dataSources.local.xml / db-forest-config.xml dosyalarını seçin",
importDatagripDialogTitle: "DataGrip yapılandırma dosyalarını seçin",
+ importDatagripUsernamesFallbackWarning: "Bazı DataGrip bağlantılarında kullanıcı adı bulunamadı ve varsayılan kullanıcı adı kullanıldı. Lütfen kimlik bilgilerini kontrol edin ve güncelleyin.",
importDbeaverSuccess: "{count} DBeaver bağlantısı içe aktarıldı. Test etmeden önce parolası boş kalan bağlantıları doldurun.",
importNone: "İçe aktarılacak yeni bağlantı yok",
importLayoutConfirm: "İçe aktarılan dosya bağlantı grupları içeriyor. Uygulansın mı?",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 2ce228f366..299854f0b2 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -3345,6 +3345,7 @@ export default withEnglishFallback({
importDatagripSuccess: "已导入 {count} 个 DataGrip 连接,已自动读取 {filled} 个密码(来自 macOS 钥匙串)",
importDatagripSelectFiles: "请选择 dataSources.xml(必需),可同时选择 dataSources.local.xml 和 db-forest-config.xml",
importDatagripDialogTitle: "选择 DataGrip 配置文件",
+ importDatagripUsernamesFallbackWarning: "部分 DataGrip 连接未找到用户名,已使用数据库默认用户名,请核对并更新连接凭据。",
importDbeaverSuccess: "已导入 {count} 个 DBeaver 连接,若个别连接密码为空请补填后测试连接",
importNone: "没有新的连接需要导入",
importLayoutConfirm: "导入文件包含连接分组信息,是否一并应用?",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index b267629f5e..5f620df1fe 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -3171,6 +3171,7 @@ export default withEnglishFallback({
importDatagripSuccess: "已匯入 {count} 個 DataGrip 連線,已自動讀取 {filled} 個密碼(來自 macOS 鑰匙圈)",
importDatagripSelectFiles: "請選擇 dataSources.xml(必需),可同時選擇 dataSources.local.xml 和 db-forest-config.xml",
importDatagripDialogTitle: "選擇 DataGrip 設定檔",
+ importDatagripUsernamesFallbackWarning: "部分 DataGrip 連線未找到使用者名稱,已使用資料庫預設使用者名稱,請核對並更新連線憑證。",
importDbeaverSuccess: "已匯入 {count} 個 DBeaver 連線,若個別連線密碼為空請補填後測試連線",
importNone: "沒有新的連線需要匯入",
importLayoutConfirm: "匯入檔案包含連線群組資訊,是否一併套用?",
diff --git a/apps/desktop/src/lib/__tests__/imports/datagripImport.spec.ts b/apps/desktop/src/lib/__tests__/imports/datagripImport.spec.ts
index e83e548ce3..2420e560aa 100644
--- a/apps/desktop/src/lib/__tests__/imports/datagripImport.spec.ts
+++ b/apps/desktop/src/lib/__tests__/imports/datagripImport.spec.ts
@@ -232,6 +232,143 @@ describe("DataGrip connection import", () => {
expect(parseDataGripConnections(importPayload)).toHaveLength(1);
expect(parseDataGripImport(importPayload).layout).toBeUndefined();
});
+
+ it("extracts username and password from JDBC authority and query parameters", () => {
+ const result = parseDataGripImport(
+ payload(`
+ <project>
+ <component name="DataSourceManagerImpl">
+ <data-source name="MySQL Auth" uuid="mysql-1">
+ <driver-ref>mysql</driver-ref>
+ <jdbc-url>jdbc:mysql://myuser:[email protected]:3306/appdb</jdbc-url>
+ </data-source>
+ <data-source name="Postgres Query" uuid="pg-1">
+ <driver-ref>postgresql</driver-ref>
+ <jdbc-url>jdbc:postgresql://127.0.0.1:5432/appdb?user=custom_pg&amp;password=secret</jdbc-url>
+ </data-source>
+ <data-source name="SQL Server Params" uuid="mssql-1">
+ <driver-ref>sqlserver</driver-ref>
+ <jdbc-url>jdbc:sqlserver://127.0.0.1:1433;database=testdb;user=sa_user;password=sapass</jdbc-url>
+ </data-source>
+ <data-source name="Oracle Thin Auth" uuid="ora-1">
+ <driver-ref>oracle</driver-ref>
+ <jdbc-url>jdbc:oracle:thin:scott/tiger@//127.0.0.1:1521/orcl</jdbc-url>
+ </data-source>
+ </component>
+ </project>
+ `),
+ );
+
+ expect(result.fallbackUsernamesCount).toBe(0);
+ expect(result.connections).toHaveLength(4);
+
+ const mysqlConn = result.connections.find((c) => c.name === "MySQL Auth");
+ expect(mysqlConn?.username).toBe("myuser");
+ expect(mysqlConn?.password).toBe("mypass");
+
+ const pgConn = result.connections.find((c) => c.name === "Postgres Query");
+ expect(pgConn?.username).toBe("custom_pg");
+ expect(pgConn?.password).toBe("secret");
+
+ const mssqlConn = result.connections.find((c) => c.name === "SQL Server Params");
+ expect(mssqlConn?.username).toBe("sa_user");
+ expect(mssqlConn?.password).toBe("sapass");
+
+ const oraConn = result.connections.find((c) => c.name === "Oracle Thin Auth");
+ expect(oraConn?.username).toBe("scott");
+ expect(oraConn?.password).toBe("tiger");
+ });
+
+ it("keeps a literal percent sequence in URL credentials instead of aborting the import", () => {
+ const result = parseDataGripImport(
+ payload(`
+ <project>
+ <component name="DataSourceManagerImpl">
+ <data-source name="Literal Percent" uuid="pct-1">
+ <driver-ref>mysql</driver-ref>
+ <jdbc-url>jdbc:mysql://myuser:p%40ss%[email protected]:3306/appdb</jdbc-url>
+ </data-source>
+ </component>
+ </project>
+ `),
+ );
+
+ expect(result.connections).toHaveLength(1);
+ const conn = result.connections.find((c) => c.name === "Literal Percent");
+ expect(conn?.username).toBe("myuser");
+ // Any invalid `%` sequence keeps the credential verbatim rather than throwing URIError.
+ expect(conn?.password).toBe("p%40ss%zz");
+ });
+
+ it("extracts usernames from XML properties and tags without importing encrypted passwords", () => {
+ const result = parseDataGripImport(
+ payload(
+ `
+ <project>
+ <component name="DataSourceManagerImpl">
+ <data-source name="Prop User" uuid="prop-1">
+ <driver-ref>mysql</driver-ref>
+ <jdbc-url>jdbc:mysql://localhost:3306/db</jdbc-url>
+ <property name="user" value="xml_user" />
+ <property name="password" value="xml_pass" />
+ </data-source>
+ <data-source name="Tag Username" uuid="tag-1" user="attr_user">
+ <driver-ref>postgresql</driver-ref>
+ <jdbc-url>jdbc:postgresql://localhost:5432/db</jdbc-url>
+ </data-source>
+ </component>
+ </project>
+ `,
+ `
+ <project>
+ <component name="DataSourceManagerImpl">
+ <data-source uuid="tag-1">
+ <user-name>local_user</user-name>
+ <password>local_pass</password>
+ </data-source>
+ </component>
+ </project>
+ `,
+ ),
+ );
+
+ expect(result.fallbackUsernamesCount).toBe(0);
+ const propConn = result.connections.find((c) => c.name === "Prop User");
+ expect(propConn?.username).toBe("xml_user");
+ // DataGrip XML always stores encrypted ciphertext; importing it as the working password
+ // would break auth, so XML passwords are ignored (URL-embedded credentials still apply).
+ expect(propConn?.password).toBe("");
+
+ const tagConn = result.connections.find((c) => c.name === "Tag Username");
+ expect(tagConn?.username).toBe("local_user");
+ expect(tagConn?.password).toBe("");
+ });
+
+ it("tracks fallback usernames count when no username is provided", () => {
+ const result = parseDataGripImport(
+ payload(`
+ <project>
+ <component name="DataSourceManagerImpl">
+ <data-source name="MySQL Default" uuid="mysql-def">
+ <driver-ref>mysql</driver-ref>
+ <jdbc-url>jdbc:mysql://localhost:3306/db</jdbc-url>
+ </data-source>
+ <data-source name="Explicit User" uuid="mysql-exp">
+ <driver-ref>mysql</driver-ref>
+ <jdbc-url>jdbc:mysql://myuser@localhost:3306/db</jdbc-url>
+ </data-source>
+ </component>
+ </project>
+ `),
+ );
+
+ expect(result.fallbackUsernamesCount).toBe(1);
+ const defConn = result.connections.find((c) => c.name === "MySQL Default");
+ expect(defConn?.username).toBe("root");
+
+ const expConn = result.connections.find((c) => c.name === "Explicit User");
+ expect(expConn?.username).toBe("myuser");
+ });
});
describe("matchDataGripImportFiles", () => {
diff --git a/apps/desktop/src/lib/imports/datagripImport.ts b/apps/desktop/src/lib/imports/datagripImport.ts
index 096ee00853..a0c0808f47 100644
--- a/apps/desktop/src/lib/imports/datagripImport.ts
+++ b/apps/desktop/src/lib/imports/datagripImport.ts
@@ -10,6 +10,7 @@ type PartialConnection = Omit<ConnectionConfig, "id">;
export type DataGripImportResult = {
connections: ConnectionConfig[];
layout?: SidebarLayout;
+ fallbackUsernamesCount?: number;
};
export type DataGripImportPayload = {
@@ -26,6 +27,7 @@ type DataSourceFragment = {
jdbcUrl: string;
driverClass: string;
username: string;
+ password?: string;
product: string;
groupName?: string;
};
@@ -134,14 +136,23 @@ function parseJdbcUrl(jdbcUrl: string): {
host: string;
port: number;
database: string;
+ username?: string;
+ password?: string;
oracleConnectionType?: "service_name" | "sid";
} {
const url = jdbcUrl.replace(/^jdbc:/i, "").trim();
- const result = {
+ const result: {
+ host: string;
+ port: number;
+ database: string;
+ username?: string;
+ password?: string;
+ oracleConnectionType?: "service_name" | "sid";
+ } = {
host: "",
port: 0,
database: "",
- oracleConnectionType: undefined as "service_name" | "sid" | undefined,
+ oracleConnectionType: undefined,
};
// SQL Server: jdbc:sqlserver://host[:port][;key=value]
@@ -151,13 +162,26 @@ function parseJdbcUrl(jdbcUrl: string): {
result.port = getNumber(sqlServerMatch[2]);
for (const part of (sqlServerMatch[3] || "").split(";")) {
const [key, ...rest] = part.split("=");
- if (/^(databasename|database)$/i.test(key)) result.database = rest.join("=");
+ const val = rest.join("=");
+ if (/^(databasename|database)$/i.test(key)) result.database = val;
+ else if (/^(user|username|uid)$/i.test(key)) result.username = val;
+ else if (/^(password|pwd)$/i.test(key)) result.password = val;
}
return result;
}
+ // Oracle thin: optional user[:password]@ or user/password@ before @// or @host
+ let oracleUrl = url;
+ const oracleAuthMatch = url.match(/^oracle:thin:([^/@:]+)(?::([^@]+)|\/([^@]+))?@/i);
+ if (oracleAuthMatch) {
+ result.username = safeDecodeURIComponent(oracleAuthMatch[1]);
+ const pass = oracleAuthMatch[2] || oracleAuthMatch[3];
+ if (pass) result.password = safeDecodeURIComponent(pass);
+ oracleUrl = "oracle:thin:@" + url.slice(oracleAuthMatch[0].length);
+ }
+
// Oracle thin with service_name: jdbc:oracle:thin:@//host:port/service
- const oracleService = url.match(/^oracle:thin:@\/\/([^:/]+)(?::(\d+))?\/([^?]+)/i);
+ const oracleService = oracleUrl.match(/^oracle:thin:@\/\/([^:/]+)(?::(\d+))?\/([^?]+)/i);
if (oracleService) {
result.host = oracleService[1];
result.port = getNumber(oracleService[2]);
@@ -167,7 +191,7 @@ function parseJdbcUrl(jdbcUrl: string): {
}
// Oracle thin with SID: jdbc:oracle:thin:@host:port:sid
- const oracleSid = url.match(/^oracle:thin:@([^:/]+)(?::(\d+))?:([^?]+)/i);
+ const oracleSid = oracleUrl.match(/^oracle:thin:@([^:/]+)(?::(\d+))?:([^?]+)/i);
if (oracleSid) {
result.host = oracleSid[1];
result.port = getNumber(oracleSid[2]);
@@ -202,12 +226,47 @@ function parseJdbcUrl(jdbcUrl: string): {
if (schemeEnd === -1) return result;
let remainder = url.slice(schemeEnd + 3);
- remainder = remainder.split("?")[0];
+ let queryParams = "";
+ const queryIndex = remainder.indexOf("?");
+ if (queryIndex >= 0) {
+ queryParams = remainder.slice(queryIndex + 1);
+ remainder = remainder.slice(0, queryIndex);
+ }
const slashIndex = remainder.indexOf("/");
- const authority = (slashIndex >= 0 ? remainder.slice(0, slashIndex) : remainder).split("@").pop() || "";
+ const authorityWithAuth = slashIndex >= 0 ? remainder.slice(0, slashIndex) : remainder;
const database = slashIndex >= 0 ? remainder.slice(slashIndex + 1) : "";
+ let authority = authorityWithAuth;
+ const atIndex = authorityWithAuth.lastIndexOf("@");
+ if (atIndex >= 0) {
+ const authPart = authorityWithAuth.slice(0, atIndex);
+ authority = authorityWithAuth.slice(atIndex + 1);
+ const colonIndex = authPart.indexOf(":");
+ if (colonIndex >= 0) {
+ result.username = safeDecodeURIComponent(authPart.slice(0, colonIndex));
+ result.password = safeDecodeURIComponent(authPart.slice(colonIndex + 1));
+ } else {
+ result.username = safeDecodeURIComponent(authPart);
+ }
+ }
+
+ if (queryParams) {
+ try {
+ const searchParams = new URLSearchParams(queryParams);
+ const user = searchParams.get("user") || searchParams.get("username") || searchParams.get("user-name") || searchParams.get("userName") || searchParams.get("uid");
+ if (user && !result.username) {
+ result.username = user;
+ }
+ const pass = searchParams.get("password") || searchParams.get("pwd");
+ if (pass && !result.password) {
+ result.password = pass;
+ }
+ } catch {
+ // ignore query parsing errors
+ }
+ }
+
const firstHost = authority.split(",")[0] || authority;
if (firstHost.startsWith("[")) {
const closing = firstHost.indexOf("]");
@@ -273,6 +332,57 @@ function inferProfile(driverRef: string, subprotocol: string, driverClass: strin
// --- XML parsing ---
+function extractUserName(element: Element): string {
+ // 1. Common direct text elements: <user-name>, <username>, <user>
+ for (const tag of ["user-name", "username", "user"]) {
+ const val = getText(element, tag);
+ if (val) return val;
+ }
+
+ // 2. Direct XML attributes on <data-source>: user-name, username, user
+ for (const attr of ["user-name", "username", "user"]) {
+ const val = element.getAttribute(attr)?.trim();
+ if (val) return val;
+ }
+
+ // 3. Child <property name="..." value="..." /> tags
+ const properties = element.getElementsByTagName("property");
+ for (const prop of Array.from(properties)) {
+ const name = prop.getAttribute("name")?.toLowerCase().trim();
+ if (name === "user" || name === "username" || name === "user-name" || name === "user_name") {
+ const val = prop.getAttribute("value")?.trim() || prop.getAttribute("text")?.trim() || prop.textContent?.trim();
+ if (val) return val;
+ }
+ }
+
+ // 4. Nested elements in <database-info>, <auth>, <credentials>, <auth-provider>
+ for (const containerTag of ["database-info", "auth", "credentials", "auth-provider"]) {
+ const container = element.getElementsByTagName(containerTag)[0];
+ if (container) {
+ for (const attr of ["user-name", "username", "user"]) {
+ const val = container.getAttribute(attr)?.trim();
+ if (val) return val;
+ }
+ for (const tag of ["user-name", "username", "user"]) {
+ const val = getText(container, tag);
+ if (val) return val;
+ }
+ }
+ }
+
+ return "";
+}
+
+// Real DataGrip passwords can contain literal `%` sequences that are not valid
+// percent-encoding; decoding must never abort the whole import for those.
+function safeDecodeURIComponent(value: string): string {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return value;
+ }
+}
+
function parseDataSourcesXml(xml: string): Map<string, Partial<DataSourceFragment>> {
const doc = new DOMParser().parseFromString(xml, "application/xml");
if (doc.querySelector("parsererror")) return new Map();
@@ -298,7 +408,7 @@ function parseDataSourcesXml(xml: string): Map<string, Partial<DataSourceFragmen
const driverClass = getText(element, "jdbc-driver");
if (driverClass) fragment.driverClass = driverClass;
- const userName = getText(element, "user-name");
+ const userName = extractUserName(element);
if (userName) fragment.username = userName;
// DataGrip stores the folder grouping as a `group` attribute on each
@@ -328,7 +438,7 @@ function parseDataSourcesLocalXml(xml: string): Map<string, Partial<DataSourceFr
name: element.getAttribute("name") || undefined,
};
- const userName = getText(element, "user-name");
+ const userName = extractUserName(element);
if (userName) fragment.username = userName;
// Extract product from <database-info product="...">
@@ -415,6 +525,8 @@ function mergeFragments(shared: Map<string, Partial<DataSourceFragment>>, local:
driverRef: existing.driverRef || localFrag.driverRef,
jdbcUrl: existing.jdbcUrl || localFrag.jdbcUrl,
driverClass: existing.driverClass || localFrag.driverClass,
+ username: localFrag.username || existing.username,
+ password: localFrag.password || existing.password,
groupName: existing.groupName || localFrag.groupName,
});
}
@@ -430,6 +542,7 @@ function mergeFragments(shared: Map<string, Partial<DataSourceFragment>>, local:
jdbcUrl: frag.jdbcUrl,
driverClass: frag.driverClass || "",
username: frag.username || "",
+ password: frag.password || "",
product: frag.product || "",
groupName: frag.groupName,
});
@@ -438,7 +551,7 @@ function mergeFragments(shared: Map<string, Partial<DataSourceFragment>>, local:
return resolved;
}
-function buildConnection(fragment: DataSourceFragment): ConnectionConfig {
+function buildConnection(fragment: DataSourceFragment): { connection: ConnectionConfig; usernameFallback: boolean } {
const subprotocol = extractSubprotocol(fragment.jdbcUrl);
const profile = inferProfile(fragment.driverRef, subprotocol, fragment.driverClass, fragment.product);
const parsed = parseJdbcUrl(fragment.jdbcUrl);
@@ -446,7 +559,10 @@ function buildConnection(fragment: DataSourceFragment): ConnectionConfig {
const host = parsed.host || (profile.dbType === "sqlite" ? "" : "127.0.0.1");
const port = parsed.port || profile.port;
const database = parsed.database || undefined;
- const username = fragment.username || profile.user;
+ const explicitUsername = fragment.username || parsed.username;
+ const usernameFallback = !explicitUsername && Boolean(profile.user);
+ const username = explicitUsername || profile.user;
+ const password = fragment.password || parsed.password || "";
const name = fragment.name || database || host || profile.label;
const partial: PartialConnection = {
@@ -458,7 +574,7 @@ function buildConnection(fragment: DataSourceFragment): ConnectionConfig {
host,
port,
username,
- password: "",
+ password,
database,
color: "",
transport_layers: [],
@@ -471,7 +587,7 @@ function buildConnection(fragment: DataSourceFragment): ConnectionConfig {
jdbc_driver_paths: [],
};
- return { ...partial, id: uuid() };
+ return { connection: { ...partial, id: uuid() }, usernameFallback };
}
// --- Public API ---
@@ -494,9 +610,10 @@ export function parseDataGripImport(payload: DataGripImportPayload): DataGripImp
const configs: ConnectionConfig[] = [];
const connectionGroupPaths = new Map<string, string>();
const seen = new Set<string>();
+ let fallbackUsernamesCount = 0;
for (const fragment of fragments) {
- const config = buildConnection(fragment);
+ const { connection: config, usernameFallback } = buildConnection(fragment);
// Custom-driver sources without a <driver-ref> are kept only when a concrete
// database type is recognised. DataGrip ships no built-in Kingbase driver, so
// every Kingbase connection is custom (configured by URL, no driver-ref).
@@ -508,6 +625,7 @@ export function parseDataGripImport(payload: DataGripImportPayload): DataGripImp
if (seen.has(key)) continue;
seen.add(key);
configs.push(config);
+ if (usernameFallback) fallbackUsernamesCount++;
const groupPath = forestGroupPaths.get(fragment.uuid) || fragment.groupName;
if (groupPath) connectionGroupPaths.set(config.id, groupPath);
}
@@ -519,7 +637,7 @@ export function parseDataGripImport(payload: DataGripImportPayload): DataGripImp
new Set(connectionGroupPaths.values()),
connectionGroupPaths,
);
- return { connections: configs, layout };
+ return { connections: configs, layout, fallbackUsernamesCount };
}
export function parseDataGripConnections(payload: DataGripImportPayload): ConnectionConfig[] {
diff --git a/apps/desktop/src/stores/connectionStore.ts b/apps/desktop/src/stores/connectionStore.ts
index 715e9b03f8..db1a3388b5 100644
--- a/apps/desktop/src/stores/connectionStore.ts
+++ b/apps/desktop/src/stores/connectionStore.ts
@@ -659,6 +659,7 @@ export const useConnectionStore = defineStore("connection", () => {
} | null>(null);
const sidebarLayout = ref<SidebarLayout>(emptyLayout());
const tableVGroupLayouts = ref<Record<string, TableVGroupLayout>>({});
+ const lastDataGripFallbackUsernamesCount = ref(0);
const dirtyTableVGroupScopeKeys = new Set<string>();
let tableVGroupPersistTimer: ReturnType<typeof setTimeout> | null = null;
const connectionGroupPaths = computed(() => buildConnectionGroupPathMap(sidebarLayout.value));
@@ -9989,12 +9990,22 @@ export const useConnectionStore = defineStore("connection", () => {
if (picked.local) {
dataSourcesLocal = await readTextFile(picked.local);
} else {
- console.warn("[DataGrip Import] dataSources.local.xml not selected; usernames will fall back to defaults");
+ try {
+ const siblingLocal = picked.dataSources.replace(/[^\\/]+$/, "dataSources.local.xml");
+ dataSourcesLocal = await readTextFile(siblingLocal);
+ } catch {
+ console.warn("[DataGrip Import] dataSources.local.xml not selected or readable; usernames will fall back to defaults");
+ }
}
if (picked.forest) {
dbForestConfig = await readTextFile(picked.forest);
} else {
- console.warn("[DataGrip Import] db-forest-config.xml not selected; legacy group tree skipped");
+ try {
+ const siblingForest = picked.dataSources.replace(/[^\\/]+$/, "db-forest-config.xml");
+ dbForestConfig = await readTextFile(siblingForest);
+ } catch {
+ console.warn("[DataGrip Import] db-forest-config.xml not selected or readable; legacy group tree skipped");
+ }
}
} else {
const files = await new Promise<FileList>((resolve, reject) => {
@@ -10097,6 +10108,7 @@ export const useConnectionStore = defineStore("connection", () => {
};
pendingDataGripPayload = payload;
const result = parseDataGripImport(payload);
+ lastDataGripFallbackUsernamesCount.value = result.fallbackUsernamesCount || 0;
return { connections: result.connections, layout: result.layout };
}
if (isDbeaverImportPayload(content)) {
@@ -10456,6 +10468,7 @@ export const useConnectionStore = defineStore("connection", () => {
applyConnectionsImport,
importConnectionsFromFile,
applyDataGripKeychainPasswords,
+ lastDataGripFallbackUsernamesCount,
applySidebarLayout,
transferSource,
schemaDiffSource,