feat: add QuestDB support

Thanks @ptma!
This commit is contained in:
John Jin authored and GitHub committed 2026-06-14 22:58:05 +08:00
1 parent 0ae720d950
commit 1afc271c18
51 files changed
+633 -46

No files matched your search

@@ -913,6 +913,35 @@
"driverManagement": true
}
},
{
"dbType": "questdb",
"label": "QuestDB",
"runtimeMode": "native",
"mcpMode": "direct",
"singleConnectionPool": false,
"metadataConnectionScoped": false,
"skipTcpProbe": false,
"defaultPort": 8812,
"supportLevel": "operate",
"capabilities": {
"queryExecution": true,
"metadataBrowse": true,
"objectBrowser": true,
"objectSource": true,
"schemaSearch": true,
"diagram": false,
"tableDataEdit": true,
"tableStructureEdit": true,
"tableImport": true,
"dataTransfer": true,
"sqlFileExecution": true,
"databaseCreate": false,
"fieldLineage": false,
"sqlExplain": true,
"userAdmin": false,
"driverManagement": true
}
},
{
"dbType": "oceanbase-oracle",
"label": "OceanBase Oracle Mode",
+2 -1
View File
@@ -371,6 +371,7 @@ impl AppState {
| DatabaseType::Redshift
| DatabaseType::Gaussdb
| DatabaseType::Kwdb
| DatabaseType::Questdb
| DatabaseType::OpenGauss => PoolKind::Postgres(db::postgres::connect(&url, connect_timeout).await?),
DatabaseType::Sqlite => {
let extensions = db::sqlite::sqlite_extension_specs_from_url_params(db_config.url_params.as_deref())
@@ -1154,7 +1155,7 @@ fn external_driver_connect_timeout(config: &ConnectionConfig) -> std::time::Dura
fn native_postgres_url_config(config: &ConnectionConfig) -> Option<ConnectionConfig> {
match config.db_type {
DatabaseType::Gaussdb | DatabaseType::Kwdb | DatabaseType::OpenGauss => {
DatabaseType::Gaussdb | DatabaseType::Kwdb | DatabaseType::OpenGauss | DatabaseType::Questdb => {
let mut normalized = config.clone();
normalized.database = normalized.effective_database().map(str::to_string);
if matches!(config.db_type, DatabaseType::Gaussdb | DatabaseType::Kwdb) {
+1
View File
@@ -1318,6 +1318,7 @@ fn uses_keyless_row_predicate(database_type: Option<DatabaseType>) -> bool {
| DatabaseType::Firebird
| DatabaseType::Exasol
| DatabaseType::OpenGauss
| DatabaseType::Questdb
| DatabaseType::OceanbaseOracle
| DatabaseType::Gbase
| DatabaseType::Access
+1
View File
@@ -11,6 +11,7 @@ pub mod mysql;
pub mod ob_oracle;
pub mod postgres;
pub mod proxy_tunnel;
pub mod questdb;
pub mod redis_driver;
pub mod rqlite_driver;
pub mod sqlite;
+147
View File
@@ -0,0 +1,147 @@
use crate::db;
use crate::db::{ColumnInfo, IndexInfo, ObjectInfo, QueryResult, TableInfo};
use crate::models::connection::DatabaseType;
use crate::sql_dialect::quote_table_identifier;
use deadpool_postgres::Pool;
pub async fn list_objects(pool: &Pool, schema: &str) -> Result<Vec<ObjectInfo>, String> {
Ok(list_tables(pool, schema)
.await?
.iter()
.map(|t| ObjectInfo {
name: t.name.clone(),
object_type: t.table_type.clone(),
schema: None,
comment: t.comment.clone(),
created_at: None,
updated_at: None,
parent_schema: None,
parent_name: None,
})
.collect())
}
pub async fn list_tables(pool: &Pool, _schema: &str) -> Result<Vec<TableInfo>, String> {
let client = pool.get().await.map_err(|e| e.to_string())?;
let stmt = client.prepare_cached(questdb_tables_sql()).await.map_err(|e| e.to_string())?;
let rows = client.query(&stmt, &[]).await.map_err(|e| e.to_string())?;
Ok(rows
.iter()
.map(|row| {
let table_type_col = row.get::<_, String>(1);
let table_type = if table_type_col.eq_ignore_ascii_case("T") { "TABLE" } else { "VIEW" };
let comment =
if table_type_col.eq_ignore_ascii_case("M") { Some("Materialized".to_string()) } else { None };
TableInfo {
name: row.get::<_, String>(0),
table_type: table_type.to_string(),
comment,
parent_schema: None,
parent_name: None,
}
})
.collect())
}
fn questdb_tables_sql() -> &'static str {
"SELECT table_name, table_type FROM tables"
}
pub async fn get_columns(pool: &Pool, _schema: &str, table: &str) -> Result<Vec<ColumnInfo>, String> {
let client = pool.get().await.map_err(|e| e.to_string())?;
let sql = format!("SHOW COLUMNS FROM {}", quote_table_identifier(Some(DatabaseType::Questdb), table));
let stmt = client.prepare_cached(&sql).await.map_err(|e| e.to_string())?;
let rows = client.query(&stmt, &[]).await.map_err(|e| e.to_string())?;
let not_null_types: [&str; 3] = ["boolean", "byte", "short"];
Ok(rows
.iter()
.map(|row| {
let column_type = row.get::<_, String>(1);
ColumnInfo {
name: row.get::<_, String>(0),
data_type: column_type.clone().to_lowercase(),
is_nullable: !not_null_types.contains(&column_type.as_str()),
column_default: None,
is_primary_key: column_type.eq_ignore_ascii_case("timestamp")
|| column_type.eq_ignore_ascii_case("symbol"),
extra: None,
comment: None,
numeric_precision: None,
numeric_scale: None,
character_maximum_length: None,
}
})
.collect())
}
pub async fn list_indexes(pool: &Pool, _schema: &str, table: &str) -> Result<Vec<IndexInfo>, String> {
let client = pool.get().await.map_err(|e| e.to_string())?;
let sql = format!("SHOW COLUMNS FROM {}", quote_table_identifier(Some(DatabaseType::Questdb), table));
let stmt = client.prepare_cached(&sql).await.map_err(|e| e.to_string())?;
let rows = client.query(&stmt, &[]).await.map_err(|e| e.to_string())?;
Ok(rows
.iter()
.filter(|r| r.get::<_, bool>(2))
.map(|row| {
let column: String = row.get::<_, String>(0);
let key_cols = vec![column];
IndexInfo {
name: row.get::<_, String>(0),
columns: key_cols,
is_unique: false,
is_primary: true,
filter: None,
index_type: None,
included_columns: None,
comment: None,
}
})
.collect())
}
pub async fn questdb_object_source(pool: &Pool, name: &str) -> Result<String, String> {
questdb_view_ddl(pool, name).await.map_err(|e| e.to_string())
}
pub async fn questdb_table_or_view_ddl(pool: &Pool, table_or_view: &str) -> Result<String, String> {
match questdb_table_ddl(pool, table_or_view).await {
Ok(ddl) => Ok(ddl),
Err(_) => questdb_view_ddl(pool, table_or_view).await,
}
}
async fn questdb_table_ddl(pool: &Pool, table: &str) -> Result<String, String> {
let sql = format!("SHOW CREATE TABLE {}", quote_table_identifier(Some(DatabaseType::Questdb), table));
first_string_cell(db::postgres::execute_query(pool, &sql).await?)
}
async fn questdb_view_ddl(pool: &Pool, view: &str) -> Result<String, String> {
match questdb_mat_view_ddl(pool, view).await {
Ok(ddl) => Ok(ddl),
Err(_) => questdb_normal_view_ddl(pool, view).await,
}
}
async fn questdb_mat_view_ddl(pool: &Pool, view: &str) -> Result<String, String> {
let sql = format!("SHOW CREATE MATERIALIZED VIEW {}", quote_table_identifier(Some(DatabaseType::Questdb), view));
first_string_cell(db::postgres::execute_query(pool, &sql).await?)
}
async fn questdb_normal_view_ddl(pool: &Pool, view: &str) -> Result<String, String> {
let sql = format!("SHOW CREATE VIEW {}", quote_table_identifier(Some(DatabaseType::Questdb), view));
first_string_cell(db::postgres::execute_query(pool, &sql).await?)
}
fn first_string_cell(result: QueryResult) -> Result<String, String> {
result
.rows
.first()
.and_then(|row| row.iter().find_map(|value| value.as_str().map(str::to_string)))
.filter(|value| !value.trim().is_empty())
.ok_or_else(|| "Object source not found".to_string())
}
+47 -1
View File
@@ -193,6 +193,7 @@ pub fn build_drop_table_child_object_sql(options: DropTableChildObjectSqlOptions
| DatabaseType::Gaussdb
| DatabaseType::Kwdb
| DatabaseType::OpenGauss
| DatabaseType::Questdb
| DatabaseType::Highgo
| DatabaseType::Vastbase
| DatabaseType::Kingbase
@@ -223,6 +224,7 @@ pub fn build_drop_table_child_object_sql(options: DropTableChildObjectSqlOptions
| DatabaseType::Gaussdb
| DatabaseType::Kwdb
| DatabaseType::OpenGauss
| DatabaseType::Questdb
| DatabaseType::Highgo
| DatabaseType::Vastbase
| DatabaseType::Kingbase
@@ -249,7 +251,9 @@ pub fn build_empty_table_sql(options: TableAdminSqlOptions) -> String {
match options.database_type {
Some(DatabaseType::ClickHouse) => format!("ALTER TABLE {table} DELETE WHERE 1 = 1;"),
Some(DatabaseType::Bigquery) => format!("DELETE FROM {table} WHERE TRUE;"),
Some(DatabaseType::Cassandra | DatabaseType::Hive | DatabaseType::Kylin) => format!("TRUNCATE TABLE {table};"),
Some(DatabaseType::Cassandra | DatabaseType::Hive | DatabaseType::Kylin | DatabaseType::Questdb) => {
format!("TRUNCATE TABLE {table};")
}
Some(DatabaseType::Iotdb) => format!("DELETE FROM {};", iotdb_timeseries_pattern(&table)),
_ => format!("DELETE FROM {table};"),
}
@@ -289,6 +293,9 @@ pub fn build_duplicate_table_structure_sql(options: DuplicateTableStructureSqlOp
if options.database_type == Some(DatabaseType::Mysql) {
return format!("CREATE TABLE {target} LIKE {source};");
}
if options.database_type == Some(DatabaseType::Questdb) {
return format!("CREATE TABLE {target} (LIKE {source});");
}
if options.database_type.is_some_and(is_postgres_like_structure_copy) {
return format!("CREATE TABLE {target} (LIKE {source} INCLUDING ALL);");
}
@@ -400,6 +407,7 @@ fn is_postgres_like_structure_copy(database_type: DatabaseType) -> bool {
| DatabaseType::Gaussdb
| DatabaseType::Kwdb
| DatabaseType::OpenGauss
| DatabaseType::Questdb
)
}
@@ -607,6 +615,23 @@ mod tests {
}),
"DELETE FROM root.test.DCU_101.*;"
);
assert_eq!(
build_empty_table_sql(TableAdminSqlOptions {
database_type: Some(DatabaseType::Questdb),
schema: None,
table_name: "table_sample".to_string(),
}),
"TRUNCATE TABLE `table_sample`;"
);
assert_eq!(
build_truncate_table_sql(TableAdminSqlOptions {
database_type: Some(DatabaseType::Questdb),
schema: None,
table_name: "table_sample".to_string(),
}),
"TRUNCATE TABLE `table_sample`;"
);
}
#[test]
@@ -711,6 +736,18 @@ mod tests {
.unwrap(),
"DROP TRIGGER \"orders_audit\" ON \"public\".\"orders\";"
);
assert_eq!(
build_drop_table_child_object_sql(DropTableChildObjectSqlOptions {
database_type: Some(DatabaseType::Questdb),
object_type: TableChildObjectType::Column,
schema: Some("public".to_string()),
table_name: "orders".to_string(),
name: "status".to_string(),
})
.unwrap(),
"ALTER TABLE `orders` DROP COLUMN `status`;"
);
}
#[test]
@@ -751,6 +788,15 @@ mod tests {
}),
"CREATE TABLE \"HR\".\"USERS_COPY\" AS SELECT * FROM \"HR\".\"USERS\" WHERE 1=0"
);
assert_eq!(
build_duplicate_table_structure_sql(DuplicateTableStructureSqlOptions {
database_type: Some(DatabaseType::Questdb),
schema: None,
source_name: "users".to_string(),
target_name: "users_copy".to_string(),
}),
"CREATE TABLE `users_copy` (LIKE `users`);"
);
}
#[test]
+6
View File
@@ -292,6 +292,8 @@ pub enum DatabaseType {
Turso,
#[serde(rename = "influxdb")]
InfluxDb,
#[serde(rename = "questdb")]
Questdb,
Jdbc,
}
@@ -725,6 +727,7 @@ impl ConnectionConfig {
format!("{base}?{params}")
}
}
DatabaseType::Questdb => format!("questdb://{host}:{port}{db_part}"),
DatabaseType::Gbase => format!("gbase://{host}:{port}{db_part}"),
DatabaseType::H2 => format!("h2://{host}:{port}{db_part}"),
DatabaseType::Snowflake => format!("snowflake://{host}/{db_part}"),
@@ -886,6 +889,9 @@ impl ConnectionConfig {
format!("{base}?{params}")
}
}
DatabaseType::Questdb => {
format!("questdb://{}:{}@{host}:{port}{db_part}", username, password)
}
DatabaseType::Gbase => {
format!("gbase://{}:{}@{host}:{port}{db_part}", username, password)
}
+11 -4
View File
@@ -127,7 +127,11 @@ pub fn build_executable_object_source_statements(input: EditableObjectSourceSqlI
if matches!(
input.database_type,
DatabaseType::Postgres | DatabaseType::Gaussdb | DatabaseType::Kwdb | DatabaseType::OpenGauss
DatabaseType::Postgres
| DatabaseType::Gaussdb
| DatabaseType::Kwdb
| DatabaseType::OpenGauss
| DatabaseType::Questdb
) && input.object_type == ObjectSourceKind::View
{
return Ok(vec![format!(
@@ -159,9 +163,11 @@ pub fn build_view_ddl_sql(input: BuildViewDdlInput) -> String {
};
if input.database_type.is_none()
|| input
.database_type
.is_some_and(|database_type| is_postgres_like(database_type) || database_type == DatabaseType::OpenGauss)
|| input.database_type.is_some_and(|database_type| {
is_postgres_like(database_type)
|| database_type == DatabaseType::OpenGauss
|| database_type == DatabaseType::Questdb
})
{
return format!("CREATE OR REPLACE VIEW {qualified_name} AS\n{}", ensure_semicolon(source));
}
@@ -215,6 +221,7 @@ fn is_postgres_like(database_type: DatabaseType) -> bool {
| DatabaseType::Gaussdb
| DatabaseType::Kwdb
| DatabaseType::OpenGauss
| DatabaseType::Questdb
| DatabaseType::Kingbase
| DatabaseType::Highgo
| DatabaseType::Vastbase
+12 -7
View File
@@ -41,12 +41,14 @@ pub fn build_explain_sql(options: ExplainSqlOptions) -> ExplainSqlBuildResult {
return explain_err("unsafe");
}
let sql = if options.database_type == Some(DatabaseType::Postgres) {
format!("EXPLAIN (FORMAT JSON) {source}")
} else if options.database_type == Some(DatabaseType::Dameng) {
format!("EXPLAIN {source}")
} else {
format!("EXPLAIN FORMAT=JSON {source}")
let sql = match options.database_type {
Some(DatabaseType::Postgres | DatabaseType::MongoDb) => {
format!("EXPLAIN (FORMAT JSON) {source}")
}
Some(DatabaseType::Dameng | DatabaseType::Questdb) => {
format!("EXPLAIN {source}")
}
_ => format!("EXPLAIN FORMAT=JSON {source}"),
};
ExplainSqlBuildResult { ok: true, sql: Some(sql), reason: None }
}
@@ -71,7 +73,10 @@ pub fn build_dropped_file_preview_sql(options: DroppedFilePreviewSqlOptions) ->
}
pub fn supports_explain_plan(database_type: Option<DatabaseType>) -> bool {
matches!(database_type, Some(DatabaseType::Mysql | DatabaseType::Postgres | DatabaseType::Dameng))
matches!(
database_type,
Some(DatabaseType::Mysql | DatabaseType::Postgres | DatabaseType::Questdb | DatabaseType::Dameng)
)
}
pub fn is_safe_dameng_autotrace_sql(sql: &str) -> bool {
+17 -1
View File
@@ -7,7 +7,7 @@ use crate::sql::find_statement_at_cursor;
use crate::sql_dialect::{quote_table_identifier, uses_fetch_first};
static LIMIT_OFFSET_STRIP_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?i)(\s+LIMIT\s+\d+(\s+OFFSET\s+\d+)?|\s+OFFSET\s+\d+(\s+LIMIT\s+\d+)?|\s+OFFSET\s+\d+\s+ROWS?\s+FETCH\s+(?:FIRST|NEXT)\s+\d+\s+ROWS?\s+ONLY|\s+FETCH\s+(?:FIRST|NEXT)\s+\d+\s+ROWS?\s+ONLY)\s*$").unwrap()
Regex::new(r"(?i)(\s+LIMIT\s+\d+(\s+OFFSET\s+\d+)?|\s+LIMIT\s+\d+(\s*,\s*\d+)?|\s+OFFSET\s+\d+(\s+LIMIT\s+\d+)?|\s+OFFSET\s+\d+\s+ROWS?\s+FETCH\s+(?:FIRST|NEXT)\s+\d+\s+ROWS?\s+ONLY|\s+FETCH\s+(?:FIRST|NEXT)\s+\d+\s+ROWS?\s+ONLY)\s*$").unwrap()
});
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -178,6 +178,10 @@ pub fn build_paginated_query_sql(options: PaginatedQuerySqlOptions) -> QuerySqlB
return ok(add_mysql_limit(&statement, safe_limit, safe_offset));
}
if options.database_type == Some(DatabaseType::Questdb) {
return ok(add_questdb_limit(&statement, safe_limit, safe_offset));
}
if options.database_type == Some(DatabaseType::Elasticsearch) {
// If the user wrote their own LIMIT, leave the SQL alone — they
// explicitly bounded the result set and the front-end will paginate
@@ -431,6 +435,18 @@ fn add_informix_first_limit(statement: &str, limit: usize, offset: usize) -> Str
format!("SELECT {row_limit} * FROM ({statement}) dbx_page;")
}
fn add_questdb_limit(statement: &str, limit: usize, offset: usize) -> String {
if has_top_level_limit(statement) {
return format!("{statement};");
}
if offset > 0 {
let upper_bound = offset + limit;
format!("{statement} LIMIT {offset}, {upper_bound};")
} else {
format!("{statement} LIMIT {limit};")
}
}
fn has_top_level_limit(sql: &str) -> bool {
top_level_sql_tokens(sql).iter().any(|token| token.text == "LIMIT")
}
+29
View File
@@ -549,6 +549,9 @@ async fn list_tables_once(
dispatch_mysql!(p, mode, db::mysql::list_tables, db::ob_oracle::list_tables, schema)
.map(|tables| filter_table_infos(tables, filter, limit, offset))
}
PoolKind::Postgres(p) if db_config.as_ref().is_some_and(is_questdb_config) => {
db::questdb::list_tables(p, schema).await.map(|tables| filter_table_infos(tables, filter, limit, offset))
}
PoolKind::Postgres(p) => db::postgres::list_tables_filtered(p, schema, filter, limit, offset).await,
PoolKind::Sqlite(p) => {
db::sqlite::list_tables(p, schema).await.map(|tables| filter_table_infos(tables, filter, limit, offset))
@@ -944,6 +947,9 @@ async fn list_objects_once(
db::mysql::list_objects(p, database).await
}
}
PoolKind::Postgres(p) if db_config.as_ref().is_some_and(is_questdb_config) => {
db::questdb::list_objects(p, schema).await
}
PoolKind::Postgres(p) => db::postgres::list_objects(p, schema).await,
_ => {
drop(connections);
@@ -1049,6 +1055,9 @@ async fn list_completion_objects_once(
PoolKind::Mysql(p, mode) if *mode == MysqlMode::OceanBaseOracle => {
db::ob_oracle::list_objects(p, schema).await.map(filter_completion_objects)
}
PoolKind::Postgres(p) if db_config.as_ref().is_some_and(is_questdb_config) => {
db::questdb::list_objects(p, schema).await.map(filter_completion_objects)
}
PoolKind::Postgres(p) => db::postgres::list_objects(p, schema).await.map(filter_completion_objects),
PoolKind::SqlServer(_) => {
drop(connections);
@@ -1243,6 +1252,9 @@ pub async fn get_columns_core(
dispatch_mysql!(p, mode, db::mysql::get_columns, db::ob_oracle::get_columns, database, table)
.map(deduplicate_column_infos)
}
PoolKind::Postgres(p) if db_config.as_ref().is_some_and(is_questdb_config) => {
db::questdb::get_columns(p, schema, table).await.map(deduplicate_column_infos)
}
PoolKind::Postgres(p) => db::postgres::get_columns(p, schema, table).await.map(deduplicate_column_infos),
PoolKind::Sqlite(p) => db::sqlite::get_columns(p, schema, table).await.map(deduplicate_column_infos),
PoolKind::Rqlite(client) => {
@@ -1321,6 +1333,9 @@ pub async fn list_indexes_core(
}
dispatch_mysql!(p, mode, db::mysql::list_indexes, db::ob_oracle::list_indexes, schema, table)
}
PoolKind::Postgres(p) if db_config.as_ref().is_some_and(is_questdb_config) => {
db::questdb::list_indexes(p, schema, table).await
}
PoolKind::Postgres(p) => db::postgres::list_indexes(p, schema, table).await,
PoolKind::Sqlite(p) => db::sqlite::list_indexes(p, schema, table).await,
PoolKind::Rqlite(client) => db::rqlite_driver::list_indexes(client, schema, table).await,
@@ -1513,6 +1528,12 @@ pub async fn get_table_ddl_core(
Err(_) => pg_ddl(p, schema, table).await,
}
}
PoolKind::Postgres(p) if db_config.as_ref().is_some_and(is_questdb_config) => {
match db::questdb::questdb_table_or_view_ddl(p, table).await {
Ok(ddl) => Ok(ddl),
Err(_) => pg_ddl(p, schema, table).await,
}
}
PoolKind::Postgres(p) => pg_ddl(p, schema, table).await,
PoolKind::Sqlite(p) => sqlite_ddl(p, table).await,
PoolKind::Rqlite(client) => db::rqlite_driver::table_ddl(client, table).await,
@@ -1562,6 +1583,10 @@ fn is_mysql_system_database(name: &str) -> bool {
matches!(name.to_ascii_lowercase().as_str(), "information_schema" | "mysql" | "performance_schema" | "sys")
}
fn is_questdb_config(config: &ConnectionConfig) -> bool {
matches!(config.db_type, DatabaseType::Questdb) || matches!(config.driver_profile.as_deref(), Some("questdb"))
}
fn sql_string(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
}
@@ -1793,6 +1818,10 @@ pub async fn get_object_source_core(
} else {
match connections.get(&pool_key).ok_or("Pool not found")? {
PoolKind::Mysql(pool, _) => mysql_object_source(pool, name, &object_type).await?,
PoolKind::Postgres(pool) if db_config.as_ref().is_some_and(is_questdb_config) => {
// only view
db::questdb::questdb_object_source(pool, name).await?
}
PoolKind::Postgres(pool) => postgres_object_source(pool, schema, name, &object_type).await?,
PoolKind::Sqlite(pool) => first_string_cell(
db::sqlite::execute_query(pool, &sqlite_object_source_sql(name, &object_type)).await?,
@@ -45,6 +45,9 @@ pub(in crate::schema) async fn list_tables(
let db = if schema.is_empty() { database } else { schema };
db::mysql::list_tables(p, db).await
}
PoolKind::Postgres(p) if config.is_some_and(is_questdb_config) => {
db::questdb::list_tables(p, schema).await
}
PoolKind::Postgres(p) => db::postgres::list_tables(p, schema).await,
PoolKind::Sqlite(p) => db::sqlite::list_tables(p, schema).await,
PoolKind::Rqlite(client) => db::rqlite_driver::list_tables(client, schema).await,
@@ -76,6 +79,9 @@ pub(in crate::schema) async fn list_objects(
db::mysql::list_table_objects_show(p, database).await.map(Some)
}
PoolKind::Mysql(p, _) => db::mysql::list_objects(p, database).await.map(Some),
PoolKind::Postgres(p) if config.is_some_and(is_questdb_config) => {
db::questdb::list_objects(p, schema).await.map(Some)
}
PoolKind::Postgres(p) => db::postgres::list_objects(p, schema).await.map(Some),
_ => Ok(None),
}
@@ -83,6 +89,7 @@ pub(in crate::schema) async fn list_objects(
pub(in crate::schema) async fn list_completion_objects(
pool: &PoolKind,
config: Option<&ConnectionConfig>,
database: &str,
schema: &str,
) -> Result<Option<Vec<db::ObjectInfo>>, String> {
@@ -93,6 +100,9 @@ pub(in crate::schema) async fn list_completion_objects(
PoolKind::Mysql(p, mode) if *mode == MysqlMode::OceanBaseOracle => {
db::ob_oracle::list_objects(p, schema).await.map(Some)
}
PoolKind::Postgres(p) if config.is_some_and(is_questdb_config) => {
db::questdb::list_objects(p, schema).await.map(Some)
}
PoolKind::Postgres(p) => db::postgres::list_objects(p, schema).await.map(Some),
_ => Ok(None),
}
@@ -118,6 +128,9 @@ pub(in crate::schema) async fn get_columns(
db::ob_oracle::get_columns(p, database, table).await
}
PoolKind::Mysql(p, _) => db::mysql::get_columns(p, database, table).await,
PoolKind::Postgres(p) if config.is_some_and(is_questdb_config) => {
db::questdb::get_columns(p, schema, table).await
}
PoolKind::Postgres(p) => db::postgres::get_columns(p, schema, table).await,
PoolKind::Sqlite(p) => db::sqlite::get_columns(p, schema, table).await,
PoolKind::Rqlite(client) => db::rqlite_driver::get_columns(client, schema, table).await,
@@ -129,6 +142,7 @@ pub(in crate::schema) async fn get_columns(
pub(in crate::schema) async fn list_indexes(
pool: &PoolKind,
config: Option<&ConnectionConfig>,
database: &str,
schema: &str,
table: &str,
@@ -138,6 +152,9 @@ pub(in crate::schema) async fn list_indexes(
db::ob_oracle::list_indexes(p, schema, table).await
}
PoolKind::Mysql(p, _) => db::mysql::list_indexes(p, schema, table).await,
PoolKind::Postgres(p) if config.is_some_and(is_questdb_config) => {
db::questdb::list_indexes(p, schema, table).await
}
PoolKind::Postgres(p) => db::postgres::list_indexes(p, schema, table).await,
PoolKind::Sqlite(p) => db::sqlite::list_indexes(p, schema, table).await,
PoolKind::Rqlite(client) => db::rqlite_driver::list_indexes(client, schema, table).await,
@@ -200,6 +217,12 @@ pub(in crate::schema) async fn table_ddl(
Err(_) => super::super::pg_ddl(p, schema, table).await,
}
}
PoolKind::Postgres(p) if config.is_some_and(is_questdb_config) => {
match db::questdb::questdb_table_or_view_ddl(p, table).await {
Ok(ddl) => Ok(ddl),
Err(_) => super::super::pg_ddl(p, schema, table).await,
}
}
PoolKind::Postgres(p) => super::super::pg_ddl(p, schema, table).await,
PoolKind::Sqlite(p) => super::super::sqlite_ddl(p, table).await,
PoolKind::Rqlite(client) => db::rqlite_driver::table_ddl(client, table).await,
@@ -306,3 +329,8 @@ fn filter_mysql_system_databases_for_config(
fn is_mysql_system_database(name: &str) -> bool {
matches!(name.to_ascii_lowercase().as_str(), "information_schema" | "mysql" | "performance_schema" | "sys")
}
fn is_questdb_config(config: &ConnectionConfig) -> bool {
matches!(config.db_type, DatabaseType::Questdb)
|| matches!(config.driver_profile.as_deref(), Some("questdb"))
}
+3 -1
View File
@@ -90,7 +90,9 @@ fn starts_with_duckdb_parser_gap_sql(sql: &str) -> bool {
fn normalize_dialect(dialect: Option<&str>) -> String {
match dialect.unwrap_or("generic").to_ascii_lowercase().as_str() {
"postgres" | "postgresql" | "redshift" | "opengauss" | "gaussdb" | "highgo" => "postgres".to_string(),
"postgres" | "postgresql" | "redshift" | "opengauss" | "gaussdb" | "highgo" | "questdb" => {
"postgres".to_string()
}
"mysql" | "mariadb" | "doris" | "starrocks" | "manticoresearch" | "oceanbase" => "mysql".to_string(),
"sqlite" => "sqlite".to_string(),
"sqlserver" | "mssql" => "sqlserver".to_string(),
@@ -41,7 +41,8 @@ pub fn quote_table_identifier(database_type: Option<DatabaseType>, name: &str) -
| DatabaseType::Databend
| DatabaseType::Tdengine
| DatabaseType::Access
| DatabaseType::Bigquery,
| DatabaseType::Bigquery
| DatabaseType::Questdb,
) => {
format!("`{}`", name.replace('`', "``"))
}
@@ -69,7 +70,8 @@ pub(crate) fn quote_transfer_identifier(name: &str, database_type: &DatabaseType
| DatabaseType::ClickHouse
| DatabaseType::Doris
| DatabaseType::StarRocks
| DatabaseType::Hive => format!("`{}`", name.replace('`', "``")),
| DatabaseType::Hive
| DatabaseType::Questdb => format!("`{}`", name.replace('`', "``")),
DatabaseType::SqlServer => format!("[{}]", name.replace(']', "]]")),
_ => format!("\"{}\"", name.replace('\"', "\"\"")),
}
@@ -77,7 +79,8 @@ pub(crate) fn quote_transfer_identifier(name: &str, database_type: &DatabaseType
pub(crate) fn qualified_transfer_table(table_name: &str, schema: &str, database_type: &DatabaseType) -> String {
let table = quote_transfer_identifier(table_name, database_type);
if schema.is_empty() || matches!(database_type, DatabaseType::Mysql | DatabaseType::MongoDb) {
if schema.is_empty() || matches!(database_type, DatabaseType::Mysql | DatabaseType::MongoDb | DatabaseType::Questdb)
{
table
} else {
format!("{}.{}", quote_transfer_identifier(schema, database_type), table)
@@ -110,6 +110,17 @@ pub fn build_table_data_select_sql(options: TableDataSelectSqlOptions) -> String
);
}
if database_type == Some(DatabaseType::Questdb) {
return build_questdb_table_select_sql(
&table_alias,
&where_clause,
&order,
&options.columns,
limit,
options.offset.unwrap_or(0),
);
}
let offset =
options.offset.filter(|offset| *offset > 0).map(|offset| format!(" OFFSET {offset}")).unwrap_or_default();
format!("SELECT {select_columns} FROM {table_alias}{where_clause}{order} LIMIT {limit}{offset};")
@@ -332,3 +343,27 @@ pub(super) fn build_neo4j_table_select_sql(options: &TableDataSelectSqlOptions,
let skip = options.offset.filter(|offset| *offset > 0).map(|offset| format!(" SKIP {offset}")).unwrap_or_default();
format!("MATCH (n:{label}){where_clause} RETURN {returns}{order}{skip} LIMIT {limit};")
}
pub(super) fn build_questdb_table_select_sql(
table: &str,
where_clause: &str,
order_by: &str,
columns: &[String],
limit: usize,
offset: usize,
) -> String {
let columns_sql = if columns.is_empty() {
"*".to_string()
} else {
columns
.iter()
.map(|column| quote_table_identifier(Some(DatabaseType::Questdb), column))
.collect::<Vec<_>>()
.join(", ")
};
if offset == 0 {
return format!("SELECT {columns_sql} FROM {table}{where_clause}{order_by} LIMIT {limit}");
}
let upper_bound = offset + limit;
return format!("SELECT {columns_sql} FROM {table}{where_clause}{order_by} LIMIT {offset}, {upper_bound}");
}
@@ -551,6 +551,29 @@ pub(super) fn build_sqlite_existing_column_sql(
statements
}
pub(super) fn build_questdb_existing_column_sql(table: &str, column: &EditableStructureColumn) -> Vec<String> {
let Some(original) = &column.original else {
return Vec::new();
};
let mut statements = Vec::new();
let current_name = &column.name;
if column.name != original.name {
statements.push(format!(
"ALTER TABLE {table} RENAME COLUMN {} TO {};",
quote_ident(StructureDialect::Questdb, &original.name),
quote_ident(StructureDialect::Questdb, &column.name)
));
}
if column.data_type.trim() != original.data_type.trim() {
statements.push(format!(
"ALTER TABLE {table} ALTER COLUMN {} TYPE {};",
quote_ident(StructureDialect::Questdb, current_name),
column_data_type(StructureDialect::Questdb, column)
));
}
statements
}
pub(super) fn has_existing_column_attribute_change(column: &EditableStructureColumn) -> bool {
let Some(original) = &column.original else {
return false;
@@ -5,6 +5,11 @@ use super::util::{clean, format_default_for_sql, normalize_default, quote_ident,
pub(super) fn column_definition(dialect: StructureDialect, column: &EditableStructureColumn) -> String {
let data_type = column_data_type(dialect, column);
let mut parts = vec![quote_ident(dialect, &column.name), data_type];
// QuestDB SQL Syntax: ```ALTER TABLE tableName ADD COLUMN [IF NOT EXISTS] columnName typeDef```
if dialect == StructureDialect::Questdb {
parts.insert(0, "IF NOT EXISTS".to_string());
return parts.join(" ");
}
if !column.is_nullable && !is_oracle_like(dialect) && dialect != StructureDialect::ClickHouse {
parts.push("NOT NULL".to_string());
}
@@ -74,6 +79,9 @@ pub(super) fn column_data_type(dialect: StructureDialect, column: &EditableStruc
if dialect == StructureDialect::ManticoreSearch {
return manticore_column_type(column);
}
if dialect == StructureDialect::Questdb {
return questdb_column_type(column);
}
normalize_column_data_type(dialect, &column.data_type)
}
@@ -186,3 +194,22 @@ pub(super) fn unwrap_clickhouse_nullable_type(data_type: &str) -> String {
trimmed.to_string()
}
}
/// QuestDB 类型处理
/// geohash, decimal 这2种类型才能带()
pub(super) fn questdb_column_type(column: &EditableStructureColumn) -> String {
let data_type = column.data_type.trim().to_ascii_lowercase();
let length_types: [&str; 2] = ["geohash", "decimal"];
match data_type.find('(') {
Some(pos) => {
let base_type = &data_type[..pos];
let params = &data_type[pos..];
if length_types.contains(&base_type) {
format!("{}{}", base_type, params)
} else {
base_type.to_string()
}
}
None => data_type,
}
}
@@ -1,8 +1,8 @@
use super::column_alter::{
build_clickhouse_existing_column_sql, build_h2_existing_column_sql, build_informix_existing_column_sql,
build_mysql_existing_column_sql, build_oracle_like_existing_column_sql, build_postgres_existing_column_sql,
build_sqlite_existing_column_sql, build_sqlserver_existing_column_sql, has_column_extra_change,
has_existing_column_attribute_change,
build_questdb_existing_column_sql, build_sqlite_existing_column_sql, build_sqlserver_existing_column_sql,
has_column_extra_change, has_existing_column_attribute_change,
};
use super::column_format::column_definition;
use super::comments::build_sqlserver_column_comment_sql;
@@ -120,6 +120,7 @@ pub(super) fn build_column_sql(options: &TableStructureSqlOptions, warnings: &mu
&options.table_name,
)),
StructureDialect::Sqlite => statements.extend(build_sqlite_existing_column_sql(&table, column, warnings)),
StructureDialect::Questdb => statements.extend(build_questdb_existing_column_sql(&table, column)),
_ => warnings.push(format!("Editing existing columns is not supported for {database_label} yet.")),
}
}
@@ -13,6 +13,7 @@ pub(super) enum StructureDialect {
ClickHouse,
ManticoreSearch,
Informix,
Questdb,
Unsupported,
}
@@ -116,6 +117,23 @@ pub(super) fn capabilities_for(database_type: Option<DatabaseType>) -> TableStru
alter_primary_key: true,
..base
},
Some(DatabaseType::Questdb) => TableStructureCapabilities {
dialect: StructureDialect::Questdb,
add_column: true,
drop_column: true,
rename_column: true,
alter_existing_column: true,
reorder_column: false,
comment: false,
create_index: false,
drop_index: false,
rebuild_index: false,
index_type: false,
index_include: false,
index_filter: false,
index_comment: false,
alter_primary_key: false,
},
Some(DatabaseType::Redshift | DatabaseType::Vertica) => TableStructureCapabilities {
dialect: StructureDialect::Postgres,
add_column: true,
@@ -254,6 +272,7 @@ pub(super) fn dialect_label(dialect: StructureDialect) -> String {
StructureDialect::ClickHouse => "clickhouse",
StructureDialect::ManticoreSearch => "manticoresearch",
StructureDialect::Informix => "informix",
StructureDialect::Questdb => "questdb",
StructureDialect::Unsupported => "this database",
}
.to_string()
@@ -272,6 +291,7 @@ pub(super) fn database_type_for_dialect(dialect: StructureDialect) -> Option<Dat
StructureDialect::ClickHouse => Some(DatabaseType::ClickHouse),
StructureDialect::ManticoreSearch => Some(DatabaseType::ManticoreSearch),
StructureDialect::Informix => Some(DatabaseType::Informix),
StructureDialect::Questdb => Some(DatabaseType::Questdb),
StructureDialect::Unsupported => None,
}
}
@@ -18,7 +18,9 @@ pub(super) fn qualified_table(dialect: StructureDialect, schema: Option<&str>, t
pub(super) fn quote_ident(dialect: StructureDialect, name: &str) -> String {
match dialect {
StructureDialect::Mysql | StructureDialect::ManticoreSearch => format!("`{}`", name.replace('`', "``")),
StructureDialect::Mysql | StructureDialect::ManticoreSearch | StructureDialect::Questdb => {
format!("`{}`", name.replace('`', "``"))
}
StructureDialect::SqlServer => format!("[{}]", name.replace(']', "]]")),
StructureDialect::Informix if is_simple_informix_identifier(name) => name.to_string(),
_ => format!("\"{}\"", name.replace('"', "\"\"")),
+29
View File
@@ -1471,6 +1471,10 @@ pub fn pagination_sql(
"SELECT {col_list} FROM {full_table} ORDER BY (SELECT NULL) OFFSET {offset} ROWS FETCH NEXT {limit} ROWS ONLY"
)
}
DatabaseType::Questdb => {
let upper_bound = offset + limit as u64;
format!("SELECT {col_list} FROM {full_table} LIMIT {offset}, {upper_bound}")
}
_ => {
format!("SELECT {col_list} FROM {full_table} LIMIT {limit} OFFSET {offset}")
}
@@ -1497,6 +1501,11 @@ pub fn pagination_sql_with_order(
"SELECT {col_list} FROM {full_table} ORDER BY {order_by} OFFSET {offset} ROWS FETCH NEXT {limit} ROWS ONLY"
)
}
DatabaseType::Questdb => {
let upper_bound = offset + limit as u64;
let order_by = order_expression.map(|value| format!(" ORDER BY {value}")).unwrap_or_default();
format!("SELECT {col_list} FROM {full_table}{order_by} LIMIT {offset}, {upper_bound}")
}
_ => {
let order_by = order_expression.map(|value| format!(" ORDER BY {value}")).unwrap_or_default();
format!("SELECT {col_list} FROM {full_table}{order_by} LIMIT {limit} OFFSET {offset}")
@@ -1533,6 +1542,11 @@ pub fn pagination_sql_with_filter_order(
"SELECT {col_list} FROM {full_table}{where_clause} ORDER BY {order_by} OFFSET {offset} ROWS FETCH NEXT {limit} ROWS ONLY"
)
}
DatabaseType::Questdb => {
let upper_bound = offset + limit as u64;
let order_by = order_expression.map(|value| format!(" ORDER BY {value}")).unwrap_or_default();
format!("SELECT {col_list} FROM {full_table}{where_clause}{order_by} LIMIT {offset}, {upper_bound}")
}
_ => {
let order_by = order_expression.map(|value| format!(" ORDER BY {value}")).unwrap_or_default();
format!("SELECT {col_list} FROM {full_table}{where_clause}{order_by} LIMIT {limit} OFFSET {offset}")
@@ -3601,6 +3615,21 @@ mod tests {
assert_eq!(sql, "SELECT \"id\", \"name\" FROM \"public\".\"users\" ORDER BY \"id\" LIMIT 100 OFFSET 200");
}
#[test]
fn questdb_pagination_uses_stable_primary_key_order() {
let sql = pagination_sql_with_order(
&[String::from("id"), String::from("name")],
"users",
"public",
&DatabaseType::Questdb,
200,
100,
&[String::from("id")],
);
assert_eq!(sql, "SELECT `id`, `name` FROM `users` ORDER BY `id` LIMIT 200, 300");
}
#[test]
fn filtered_pagination_preserves_where_and_order() {
let sql = pagination_sql_with_filter_order(
@@ -141,6 +141,7 @@ fn classifies_agent_database_types() {
assert!(!is_agent_type(&DatabaseType::Gaussdb));
assert!(!is_agent_type(&DatabaseType::Kwdb));
assert!(!is_agent_type(&DatabaseType::OpenGauss));
assert!(!is_agent_type(&DatabaseType::Questdb));
}
#[test]
@@ -192,6 +193,7 @@ fn skips_tcp_probe_for_local_file_plugin_and_agent_types() {
assert!(!skips_tcp_probe(&DatabaseType::Gaussdb));
assert!(!skips_tcp_probe(&DatabaseType::Kwdb));
assert!(!skips_tcp_probe(&DatabaseType::OpenGauss));
assert!(!skips_tcp_probe(&DatabaseType::Questdb));
}
#[test]