feat(sqlserver): support linked server browsing
This commit is contained in:
1 parent
fc8ae4b69f
commit
9e75f62dbf
20 files changed
+617
-32
No files matched your search
@@ -723,21 +723,20 @@ async fn linked_server_table_rows(
|
||||
schema: Option<&str>,
|
||||
table_name: Option<&str>,
|
||||
) -> Result<Vec<LinkedServerTableRow>, String> {
|
||||
let schema_param = schema.unwrap_or("");
|
||||
let table_name_param = table_name.unwrap_or("");
|
||||
let stream = client
|
||||
.query(
|
||||
"EXEC sp_tables_ex \
|
||||
@table_server = @P1, \
|
||||
@table_name = @P2, \
|
||||
@table_schema = @P3, \
|
||||
@table_catalog = @P4, \
|
||||
@table_type = '''TABLE'',''VIEW''', \
|
||||
@fUsePattern = 0",
|
||||
&[&server, &table_name_param, &schema_param, &catalog],
|
||||
)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let sql = format!(
|
||||
"EXEC sp_tables_ex \
|
||||
@table_server = {}, \
|
||||
@table_name = {}, \
|
||||
@table_schema = {}, \
|
||||
@table_catalog = {}, \
|
||||
@table_type = '''TABLE'',''VIEW''', \
|
||||
@fUsePattern = 0",
|
||||
sqlserver_nstring_literal(server),
|
||||
sqlserver_optional_nstring_literal(table_name),
|
||||
sqlserver_optional_nstring_literal(schema),
|
||||
sqlserver_nstring_literal(catalog),
|
||||
);
|
||||
let stream = client.query(sql.as_str(), &[]).await.map_err(|e| e.to_string())?;
|
||||
let rows = stream.into_first_result().await.map_err(|e| e.to_string())?;
|
||||
Ok(rows
|
||||
.iter()
|
||||
@@ -756,6 +755,14 @@ async fn linked_server_table_rows(
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn sqlserver_optional_nstring_literal(value: Option<&str>) -> String {
|
||||
value.filter(|value| !value.trim().is_empty()).map(sqlserver_nstring_literal).unwrap_or_else(|| "NULL".to_string())
|
||||
}
|
||||
|
||||
fn sqlserver_nstring_literal(value: &str) -> String {
|
||||
format!("N'{}'", value.replace('\'', "''"))
|
||||
}
|
||||
|
||||
fn normalize_linked_server_table_type(value: Option<&str>) -> String {
|
||||
let upper = value.unwrap_or("TABLE").to_ascii_uppercase();
|
||||
if upper.contains("VIEW") {
|
||||
|
||||
@@ -272,6 +272,68 @@ pub async fn list_databases_core(state: &AppState, connection_id: &str) -> Resul
|
||||
retry_metadata_connection(state, connection_id, None, || list_databases_once(state, connection_id)).await
|
||||
}
|
||||
|
||||
pub async fn list_sqlserver_linked_servers_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
) -> Result<Vec<db::LinkedServerInfo>, String> {
|
||||
let connections = state.connections.read().await;
|
||||
if let Some(client) = extract_pool!(&connections, connection_id, SqlServer) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_linked_servers(&mut client).await;
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
pub async fn list_sqlserver_linked_server_catalogs_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
server: &str,
|
||||
) -> Result<Vec<db::DatabaseInfo>, String> {
|
||||
let connections = state.connections.read().await;
|
||||
if let Some(client) = extract_pool!(&connections, connection_id, SqlServer) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_linked_server_catalogs(&mut client, server).await;
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
pub async fn list_sqlserver_linked_server_schemas_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
server: &str,
|
||||
catalog: &str,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let connections = state.connections.read().await;
|
||||
if let Some(client) = extract_pool!(&connections, connection_id, SqlServer) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_linked_server_schemas(&mut client, server, catalog).await;
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
pub async fn list_sqlserver_linked_server_tables_core(
|
||||
state: &AppState,
|
||||
connection_id: &str,
|
||||
server: &str,
|
||||
catalog: &str,
|
||||
schema: &str,
|
||||
filter: Option<&str>,
|
||||
limit: Option<usize>,
|
||||
offset: Option<usize>,
|
||||
) -> Result<Vec<db::TableInfo>, String> {
|
||||
let connections = state.connections.read().await;
|
||||
if let Some(client) = extract_pool!(&connections, connection_id, SqlServer) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_linked_server_tables(&mut client, server, catalog, schema, filter, limit, offset)
|
||||
.await;
|
||||
}
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn list_databases_once(state: &AppState, connection_id: &str) -> Result<Vec<db::DatabaseInfo>, String> {
|
||||
log::info!("[list_databases] connection_id={connection_id}");
|
||||
{
|
||||
@@ -491,6 +553,23 @@ async fn list_tables_once(
|
||||
.await
|
||||
.map(|tables| filter_table_infos(tables, filter, limit, offset, object_types));
|
||||
}
|
||||
if let Some(linked) = crate::sql_dialect::parse_sqlserver_linked_schema_ref(schema) {
|
||||
if let Some(client) = extract_pool!(&connections, &pool_key, SqlServer) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::list_linked_server_tables(
|
||||
&mut client,
|
||||
&linked.server,
|
||||
&linked.catalog,
|
||||
&linked.schema,
|
||||
filter,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map(|tables| filter_table_infos(tables, filter, limit, offset, object_types));
|
||||
}
|
||||
}
|
||||
if object_types.is_some() {
|
||||
if let Some(client) = extract_pool!(&connections, &pool_key, SqlServer) {
|
||||
drop(connections);
|
||||
@@ -1277,6 +1356,21 @@ pub async fn get_columns_core(
|
||||
drop(connections);
|
||||
return db::influxdb_driver::get_columns(&client, database, table).await.map(deduplicate_column_infos);
|
||||
}
|
||||
if let Some(linked) = crate::sql_dialect::parse_sqlserver_linked_schema_ref(schema) {
|
||||
if let Some(client) = extract_pool!(&connections, &pool_key, SqlServer) {
|
||||
drop(connections);
|
||||
let mut client = client.lock().await;
|
||||
return db::sqlserver::get_linked_server_columns(
|
||||
&mut client,
|
||||
&linked.server,
|
||||
&linked.catalog,
|
||||
&linked.schema,
|
||||
table,
|
||||
)
|
||||
.await
|
||||
.map(deduplicate_column_infos);
|
||||
}
|
||||
}
|
||||
try_sqlserver!(connections, &pool_key, get_columns, schema, table);
|
||||
if let Some(client) = extract_pool!(&connections, &pool_key, Agent) {
|
||||
let fallback_config = db_config.clone();
|
||||
@@ -1406,6 +1500,9 @@ pub async fn list_indexes_core(
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> Result<Vec<db::IndexInfo>, String> {
|
||||
if crate::sql_dialect::parse_sqlserver_linked_schema_ref(schema).is_some() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
|
||||
let db_config = connection_config(state, connection_id).await;
|
||||
|
||||
@@ -1442,6 +1539,9 @@ pub async fn list_foreign_keys_core(
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> Result<Vec<db::ForeignKeyInfo>, String> {
|
||||
if crate::sql_dialect::parse_sqlserver_linked_schema_ref(schema).is_some() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
|
||||
|
||||
{
|
||||
@@ -1471,6 +1571,9 @@ pub async fn list_triggers_core(
|
||||
schema: &str,
|
||||
table: &str,
|
||||
) -> Result<Vec<db::TriggerInfo>, String> {
|
||||
if crate::sql_dialect::parse_sqlserver_linked_schema_ref(schema).is_some() {
|
||||
return Ok(vec![]);
|
||||
}
|
||||
let pool_key = state.get_or_create_pool(connection_id, Some(database)).await?;
|
||||
|
||||
{
|
||||
@@ -1566,6 +1669,9 @@ pub async fn get_table_ddl_core(
|
||||
table: &str,
|
||||
object_type: Option<db::ObjectSourceKind>,
|
||||
) -> Result<String, String> {
|
||||
if crate::sql_dialect::parse_sqlserver_linked_schema_ref(schema).is_some() {
|
||||
return Err("DDL is not supported for SQL Server linked server tables".to_string());
|
||||
}
|
||||
if matches!(object_type, Some(db::ObjectSourceKind::View)) {
|
||||
let source =
|
||||
get_object_source_core(state, connection_id, database, schema, table, db::ObjectSourceKind::View).await?;
|
||||
|
||||
@@ -8,6 +8,6 @@ mod tests;
|
||||
|
||||
pub use capabilities::{is_schema_aware, uses_fetch_first};
|
||||
pub use identifiers::{normalize_where_input, qualified_table_name, quote_table_identifier};
|
||||
pub(crate) use identifiers::{qualified_transfer_table, quote_transfer_identifier};
|
||||
pub(crate) use identifiers::{parse_sqlserver_linked_schema_ref, qualified_transfer_table, quote_transfer_identifier};
|
||||
pub use table_select::{build_count_table_sql, build_table_data_select_sql, build_table_select_sql};
|
||||
pub use types::*;
|
||||
@@ -1,7 +1,41 @@
|
||||
use crate::models::connection::DatabaseType;
|
||||
use percent_encoding::percent_decode_str;
|
||||
|
||||
use super::capabilities::{is_schema_aware, is_simple_informix_identifier};
|
||||
|
||||
pub const SQLSERVER_LINKED_SCHEMA_PREFIX: &str = "__dbx_sqlserver_linked__:";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SqlServerLinkedSchemaRef {
|
||||
pub server: String,
|
||||
pub catalog: String,
|
||||
pub schema: String,
|
||||
}
|
||||
|
||||
pub fn parse_sqlserver_linked_schema_ref(schema: &str) -> Option<SqlServerLinkedSchemaRef> {
|
||||
let payload = schema.strip_prefix(SQLSERVER_LINKED_SCHEMA_PREFIX)?;
|
||||
let mut parts = payload.split('|');
|
||||
let server = decode_linked_schema_part(parts.next()?)?;
|
||||
let catalog = decode_linked_schema_part(parts.next()?)?;
|
||||
let schema = decode_linked_schema_part(parts.next()?)?;
|
||||
if parts.next().is_some() || server.trim().is_empty() || catalog.trim().is_empty() || schema.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(SqlServerLinkedSchemaRef { server, catalog, schema })
|
||||
}
|
||||
|
||||
pub fn sqlserver_linked_table_name(linked: &SqlServerLinkedSchemaRef, table_name: &str) -> String {
|
||||
[linked.server.as_str(), linked.catalog.as_str(), linked.schema.as_str(), table_name]
|
||||
.into_iter()
|
||||
.map(|part| quote_table_identifier(Some(DatabaseType::SqlServer), part))
|
||||
.collect::<Vec<_>>()
|
||||
.join(".")
|
||||
}
|
||||
|
||||
fn decode_linked_schema_part(value: &str) -> Option<String> {
|
||||
percent_decode_str(value).decode_utf8().ok().map(|value| value.into_owned())
|
||||
}
|
||||
|
||||
pub fn qualified_table_name(database_type: Option<DatabaseType>, schema: Option<&str>, table_name: &str) -> String {
|
||||
if database_type == Some(DatabaseType::Iotdb) {
|
||||
let table_name = quote_table_identifier(database_type, table_name);
|
||||
@@ -18,6 +52,11 @@ pub fn qualified_table_name(database_type: Option<DatabaseType>, schema: Option<
|
||||
&& database_type != Some(DatabaseType::Jdbc)
|
||||
&& schema.is_some_and(|schema| !schema.trim().is_empty())
|
||||
{
|
||||
if database_type == Some(DatabaseType::SqlServer) {
|
||||
if let Some(linked) = schema.and_then(parse_sqlserver_linked_schema_ref) {
|
||||
return sqlserver_linked_table_name(&linked, table_name);
|
||||
}
|
||||
}
|
||||
return format!(
|
||||
"{}.{}",
|
||||
quote_table_identifier(database_type, schema.unwrap()),
|
||||
|
||||
@@ -42,6 +42,14 @@ fn qualifies_schema_only_for_schema_aware_databases() {
|
||||
qualified_table_name(Some(DatabaseType::Iotdb), Some("root.test"), "root.test.device2"),
|
||||
"root.test.device2"
|
||||
);
|
||||
assert_eq!(
|
||||
qualified_table_name(
|
||||
Some(DatabaseType::SqlServer),
|
||||
Some("__dbx_sqlserver_linked__:ERP%5D01|Finance%20DB|dbo"),
|
||||
"Orders]2026"
|
||||
),
|
||||
"[ERP]]01].[Finance DB].[dbo].[Orders]]2026]"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -5,6 +5,14 @@ pub struct DatabaseInfo {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LinkedServerInfo {
|
||||
pub name: String,
|
||||
pub product: Option<String>,
|
||||
pub provider: Option<String>,
|
||||
pub data_source: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TableInfo {
|
||||
pub name: String,
|
||||
|
||||
Reference in new issue
Block a user