mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 08:03:19 +00:00
fix(database): complete columns of custom JDBC data sources (#4692)
SQL completion for custom JDBC data sources knew tables but no columns: the JDBC completion model left every table's columns empty (no alias. members, no WHERE columns, no SELECT * expansion). The bridge returns a namespace's columns in one DatabaseMetaData.getColumns call (schemaColumns) and the model fills each table; a driver refusing it still completes tables.
This commit is contained in:
@@ -5,6 +5,7 @@ use crate::{DataSource, DbManager, QueryResult, ResultColumn};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::io::{Cursor, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
@@ -600,14 +601,26 @@ fn decode(data: &[u8], sql: &str, elapsed_ms: f64) -> IdeResult<QueryResult> {
|
||||
impl DbManager {
|
||||
pub(crate) async fn jdbc_completion(&self, id: &str, pool: &JdbcPool) -> IdeResult<crate::CompletionModel> {
|
||||
let mut tables = vec![];
|
||||
let mut column_count = 0;
|
||||
let schemas = self.schemas(id).await?;
|
||||
for schema in &schemas {
|
||||
// Columns of the whole namespace in one call; a driver that refuses it still completes tables.
|
||||
let mut columns = if column_count < crate::MAX_META_ROWS {
|
||||
pool.metadata(&["schemaColumns", schema]).await.map(schema_columns).unwrap_or_else(|e| {
|
||||
tracing::warn!("JDBC columns of {schema}: {}", e.message);
|
||||
HashMap::new()
|
||||
})
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
for table in self.tables(id, schema).await? {
|
||||
let columns = columns.remove(&table.name).unwrap_or_default();
|
||||
column_count += columns.len();
|
||||
tables.push(crate::CompletionTable {
|
||||
schema: schema.clone(),
|
||||
name: table.name,
|
||||
kind: table.kind,
|
||||
columns: vec![],
|
||||
columns,
|
||||
});
|
||||
if tables.len() >= crate::MAX_META_ROWS {
|
||||
break;
|
||||
@@ -632,10 +645,49 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bridge's `schemaColumns` rows (table, name, type, nullable, default) by table.
|
||||
fn schema_columns(rows: Vec<Vec<Option<String>>>) -> HashMap<String, Vec<crate::CompletionColumn>> {
|
||||
let mut by_table: HashMap<String, Vec<crate::CompletionColumn>> = HashMap::new();
|
||||
for row in rows {
|
||||
let mut it = row.into_iter();
|
||||
let (Some(Some(table)), Some(Some(name))) = (it.next(), it.next()) else { continue };
|
||||
let data_type = it.next().flatten().unwrap_or_default();
|
||||
let nullable = it.next().flatten().as_deref() != Some("0");
|
||||
let has_default = it.next().flatten().is_some();
|
||||
by_table.entry(table).or_default().push(crate::CompletionColumn {
|
||||
name,
|
||||
data_type,
|
||||
nullable,
|
||||
primary_key: false,
|
||||
has_default,
|
||||
});
|
||||
}
|
||||
by_table
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn schema_columns_group_by_table() {
|
||||
let row = |t: &str, n: &str, null: &str, def: Option<&str>| {
|
||||
vec![Some(t.into()), Some(n.into()), Some("INT".into()), Some(null.into()), def.map(Into::into)]
|
||||
};
|
||||
let by_table = schema_columns(vec![
|
||||
row("orders", "id", "0", None),
|
||||
row("orders", "note", "1", Some("'none'")),
|
||||
row("items", "sku", "1", None),
|
||||
vec![None, Some("orphan".into())],
|
||||
]);
|
||||
let orders = &by_table["orders"];
|
||||
assert_eq!(orders.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "note"]);
|
||||
assert_eq!((orders[0].nullable, orders[0].has_default), (false, false));
|
||||
assert_eq!((orders[1].nullable, orders[1].has_default), (true, true));
|
||||
assert_eq!(by_table["items"].len(), 1);
|
||||
assert_eq!(by_table.len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn frame_codec_checks_both_16_mib_boundaries() {
|
||||
assert_eq!(encode(7, &["a"]).unwrap(), [0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 1, b'a']);
|
||||
|
||||
@@ -90,7 +90,10 @@ async fn duckdb_custom_driver_through_database_manager() -> IdeResult<()> {
|
||||
assert!(result.has_more);
|
||||
assert_eq!(result.rows, vec![vec![Some("1".into()), None]]);
|
||||
assert_eq!(result.columns[1].name, "label");
|
||||
assert_eq!(db.completion("test").await?.default_schema, "main");
|
||||
let completion = db.completion("test").await?;
|
||||
assert_eq!(completion.default_schema, "main");
|
||||
let items = completion.tables.iter().find(|t| t.schema == "main" && t.name == "items").expect("items");
|
||||
assert_eq!(items.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "label"]);
|
||||
db.execute("test", "create temporary table session_marker as select 42 as id", 1, &c).await?;
|
||||
let stop = CancellationToken::new();
|
||||
let (cancelled, ()) =
|
||||
|
||||
Binary file not shown.
@@ -120,6 +120,17 @@ public final class OpenIdeaJdbc {
|
||||
n++;
|
||||
}
|
||||
}
|
||||
} else if (op.equals("schemaColumns")) {
|
||||
// Every column of the namespace in one call (SQL completion), without primary keys.
|
||||
header(out, "table", "name", "type", "nullable", "default");
|
||||
try (ResultSet rs = m.getColumns(catalog, schema, "%", "%")) {
|
||||
int n = 0;
|
||||
while (rs.next() && n < 100000) {
|
||||
row(out, rs.getString("TABLE_NAME"), rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"),
|
||||
rs.getInt("NULLABLE") == 0 ? "0" : "1", rs.getString("COLUMN_DEF"));
|
||||
n++;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
header(out, "name", "type", "nullable", "default", "primary");
|
||||
String table = a.get(1);
|
||||
@@ -233,7 +244,7 @@ public final class OpenIdeaJdbc {
|
||||
switch (op) {
|
||||
case "open" -> open(a, reply);
|
||||
case "schemas" -> schemas(reply);
|
||||
case "tables", "columns" -> metadata(op, a, reply);
|
||||
case "tables", "columns", "schemaColumns" -> metadata(op, a, reply);
|
||||
case "namespace" -> {
|
||||
header(reply, "namespace");
|
||||
String name = null;
|
||||
|
||||
@@ -30,6 +30,12 @@ public class SelfTest {
|
||||
case "getDatabaseProductName" -> "Fixture";
|
||||
case "getDatabaseProductVersion" -> "1";
|
||||
case "getIdentifierQuoteString" -> "\"";
|
||||
case "getSearchStringEscape" -> "\\";
|
||||
case "getSchemas" -> rows(List.of(Map.of("TABLE_SCHEM", "app")));
|
||||
case "getColumns" -> "app".equals(a[1]) && "%".equals(a[2]) ? rows(List.of(
|
||||
Map.of("TABLE_NAME", "orders", "COLUMN_NAME", "id", "TYPE_NAME", "INT", "NULLABLE", 0),
|
||||
Map.of("TABLE_NAME", "orders", "COLUMN_NAME", "note", "TYPE_NAME", "VARCHAR", "NULLABLE", 1,
|
||||
"COLUMN_DEF", "'none'"))) : rows(List.of());
|
||||
default -> throw new SQLFeatureNotSupportedException();
|
||||
});
|
||||
return proxy(Connection.class, (p, m, a) -> switch (m.getName()) {
|
||||
@@ -39,6 +45,19 @@ public class SelfTest {
|
||||
case "createStatement" -> statement();
|
||||
case "isClosed" -> false;
|
||||
case "isValid" -> !dropped;
|
||||
case "getCatalog" -> null;
|
||||
default -> throw new SQLFeatureNotSupportedException();
|
||||
});
|
||||
}
|
||||
|
||||
/** A forward-only result set over `data`, read by column label. */
|
||||
static ResultSet rows(List<Map<String, Object>> data) {
|
||||
int[] at = {-1};
|
||||
return proxy(ResultSet.class, (p, m, a) -> switch (m.getName()) {
|
||||
case "next" -> ++at[0] < data.size();
|
||||
case "getString" -> (String) data.get(at[0]).get((String) a[0]);
|
||||
case "getInt" -> (Integer) data.get(at[0]).getOrDefault((String) a[0], 0);
|
||||
case "close" -> null;
|
||||
default -> throw new SQLFeatureNotSupportedException();
|
||||
});
|
||||
}
|
||||
@@ -132,6 +151,9 @@ public class SelfTest {
|
||||
assert reply(in)[0] == 0;
|
||||
send(out, 8, "valid");
|
||||
assert new String(reply(in), StandardCharsets.UTF_8).contains("false");
|
||||
send(out, 9, "schemaColumns", "app");
|
||||
var columns = new String(reply(in), StandardCharsets.UTF_8);
|
||||
assert columns.contains("orders") && columns.contains("note") && columns.contains("'none'") : columns;
|
||||
} finally {
|
||||
child.destroyForcibly().waitFor();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user