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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
use crate::models::connection::DatabaseType;
use serde::{Deserialize, Serialize};
/// Agent drivers can serialize an empty native slice as JSON `null` instead of
/// `[]` (for example a Vastbase `UPDATE ... FROM` that returns no result
/// columns). A present `null` must deserialize as an empty vector: one driver's
/// serialization detail must not fail the whole agent call with
/// "invalid type: null, expected a sequence".
fn deserialize_vec_or_default<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: Deserialize<'de>,
{
Ok(Option::<Vec<T>>::deserialize(deserializer)?.unwrap_or_default())
}
/// A data-grid statement whose BLOB values travel outside the executable SQL.
/// The preview must match the caller's reviewed SQL before any statement runs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BlobBoundStatement {
pub preview_sql: String,
pub sql: String,
pub blob_parameters: Vec<String>,
}
pub fn validate_blob_bound_statements(previews: &[String], bound: &[BlobBoundStatement]) -> Result<(), String> {
if previews.len() != bound.len()
|| previews.iter().zip(bound).any(|(preview, statement)| preview != &statement.preview_sql)
{
return Err("The reviewed SQL changed; regenerate the BLOB save preview before saving.".into());
}
if bound.iter().any(|statement| {
statement.sql.trim().is_empty()
|| statement.blob_parameters.is_empty() && statement.sql != statement.preview_sql
|| statement
.blob_parameters
.iter()
.any(|hex| hex.len() % 2 != 0 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
}) {
return Err("Invalid BLOB statement parameters.".into());
}
Ok(())
}
pub use crate::mysql_event::MysqlEventInfo;
pub use crate::oracle_trigger::{
MetadataIdentityMode, MetadataReadOptions, OracleTriggerDefinition, OracleTriggerError, OracleTriggerMetadata,
OracleTriggerParent, OracleTriggerReadState,
};
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DatabaseInfo {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size_bytes: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub created_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub updated_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_charset: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_collation: Option<String>,
/// Database-level compatibility mode reported by compatible engines.
/// openGauss uses values such as A, B, C, and PG.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub compatibility_mode: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DatabaseStorageInfo {
pub name: String,
pub size_bytes: Option<i64>,
}
/// XuguDB storage metadata exposed by the read-only schema browser.
///
/// Xugu stores tablespaces and their data files inside the selected database,
/// so these types intentionally remain driver-specific instead of widening
/// the common database model used by other engines.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct XuguDatafileInfo {
pub node_id: String,
pub space_id: i64,
pub path: String,
pub file_no: i64,
pub max_size: Option<i64>,
pub step_size: Option<i64>,
pub curr_size: Option<i64>,
pub reserved1: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct XuguTablespaceInfo {
pub node_id: String,
pub space_id: i64,
pub space_name: String,
pub datafile_num: i64,
pub space_type: String,
pub media_error: Option<String>,
pub total_chunk_num: Option<i64>,
pub free_chunk_num: Option<i64>,
#[serde(default)]
pub datafiles: Vec<XuguDatafileInfo>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaInfo {
pub name: String,
pub comment: Option<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>,
}
/// A catalog exposed by a multi-catalog engine (e.g. Doris / StarRocks).
/// `internal` is the engine's native catalog; other entries are external
/// catalogs (iceberg, hive, jdbc, ...) federated through the same connection.
///
/// Note: the built-in catalog is named `internal` in Doris (Type=`internal`)
/// but `default_catalog` in StarRocks (Type=`Internal`). The `catalog_type`
/// column is the cross-engine signal, so `is_internal()` matches it
/// case-insensitively and falls back to the canonical Doris name when the
/// column is absent (very old / proxied deployments).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CatalogInfo {
pub name: String,
pub catalog_type: String,
pub is_current: bool,
pub comment: Option<String>,
}
impl CatalogInfo {
/// Whether this is the engine's built-in (non-federated) catalog.
pub fn is_internal(&self) -> bool {
if !self.catalog_type.trim().is_empty() {
self.catalog_type.eq_ignore_ascii_case("internal")
} else {
self.name == "internal"
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableInfo {
pub name: String,
pub table_type: String, // "TABLE" or "VIEW"
#[serde(default, skip_serializing_if = "Option::is_none")]
pub valid: Option<bool>,
pub comment: Option<String>,
pub parent_schema: Option<String>,
pub parent_name: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObjectInfo {
pub name: String,
pub object_type: String,
pub schema: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub valid: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signature: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub custom_type_kind: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub has_members: Option<bool>,
pub comment: Option<String>,
pub created_at: Option<String>,
pub updated_at: Option<String>,
pub parent_schema: Option<String>,
pub parent_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trigger: Option<TriggerInfo>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub xugu_type_members_expandable: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtensionInfo {
pub name: String,
pub version: String,
pub comment: Option<String>,
pub schema: Option<String>,
}
/// A PostgreSQL event trigger (`pg_event_trigger`). Event triggers fire on DDL
/// commands at the database level, independent of any schema. This is distinct
/// from MySQL events (`MysqlEventInfo`) and per-table triggers (`TriggerInfo`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventTriggerInfo {
pub name: String,
/// DDL event: ddl_command_start | ddl_command_end | sql_drop | table_rewrite.
pub event: String,
/// Owner role name.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub owner: Option<String>,
/// `schema.function(args)` executed by the trigger.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub function: Option<String>,
/// Session replica status char: O | A | R | D.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<String>,
/// Command tags in the WHEN clause (NULL = all tags).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tags: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
/// `pg_get_eventtriggerdef` reconstruction of the CREATE statement.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ObjectStatistics {
pub name: String,
pub schema: Option<String>,
pub estimated_rows: Option<i64>,
pub total_bytes: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data_length: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub engine: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub created_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub updated_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub collation: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub row_format: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub avg_row_length: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_data_length: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub check_time: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub index_length: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auto_increment: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data_free: Option<i64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ObjectSourceKind {
View,
MaterializedView,
Procedure,
Function,
Trigger,
Event,
Sequence,
Synonym,
Job,
Package,
PackageBody,
Type,
TypeBody,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RoutineParameterMode {
In,
Out,
Inout,
Return,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct RoutineParameterMetadata {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
pub mode: RoutineParameterMode,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub jdbc_type: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub type_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub precision: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub length: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scale: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub nullable: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ordinal: Option<i32>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObjectSource {
pub name: String,
pub object_type: ObjectSourceKind,
pub schema: Option<String>,
pub source: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub editable: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub routine_parameters: Option<Vec<RoutineParameterMetadata>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trigger: Option<TriggerInfo>,
}
/// Provenance for structured metadata fields that are optional in [`ColumnInfo`].
/// This stays internal to the metadata mapping path and is not serialized.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ColumnMetadataCapabilities {
pub default: bool,
pub length: bool,
pub precision: bool,
pub scale: bool,
}
impl ColumnMetadataCapabilities {
pub const fn all_supported() -> Self {
Self { default: true, length: true, precision: true, scale: true }
}
pub const fn default_only() -> Self {
Self { default: true, length: false, precision: false, scale: false }
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ColumnInfo {
pub name: String,
pub data_type: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolved_schema: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolved_table: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolved_object_type: Option<String>,
pub is_nullable: bool,
pub column_default: Option<String>,
pub is_primary_key: bool,
#[serde(default)]
pub is_unique: bool,
pub extra: Option<String>,
pub comment: Option<String>,
pub numeric_precision: Option<i32>,
pub numeric_scale: Option<i32>,
pub character_maximum_length: Option<i32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enum_values: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub character_set: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub collation: Option<String>,
#[serde(skip)]
pub metadata_capabilities: Option<ColumnMetadataCapabilities>,
}
/// Doris aggregate-state columns contain opaque engine serialization, not a
/// value that DBX can safely edit or emit as an INSERT literal.
pub fn is_opaque_aggregate_state_type(data_type: &str) -> bool {
let data_type = data_type.trim();
let Some(prefix) = data_type.get(.."agg_state".len()) else { return false };
if !prefix.eq_ignore_ascii_case("agg_state") {
return false;
}
let Some(arguments) =
data_type.get("agg_state".len()..).map(str::trim_start).and_then(|value| value.strip_prefix('<'))
else {
return false;
};
arguments.strip_suffix('>').is_some_and(|inner| !inner.trim().is_empty())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableColumnsResult {
pub table_name: String,
pub columns: Vec<ColumnInfo>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CompletionAssistantObjectKind {
Database,
Schema,
Table,
View,
Routine,
Procedure,
Function,
Column,
Sequence,
}
impl CompletionAssistantObjectKind {
pub fn is_table_like(&self) -> bool {
matches!(self, Self::Table | Self::View)
}
pub fn is_routine_like(&self) -> bool {
matches!(self, Self::Routine | Self::Procedure | Self::Function)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CompletionAssistantCandidateKind {
#[serde(alias = "DATABASE")]
Database,
#[serde(alias = "SCHEMA")]
Schema,
#[serde(alias = "TABLE")]
Table,
#[serde(alias = "VIEW")]
View,
#[serde(alias = "PROCEDURE")]
Procedure,
#[serde(alias = "FUNCTION")]
Function,
#[serde(alias = "COLUMN")]
Column,
#[serde(alias = "SEQUENCE")]
Sequence,
#[serde(alias = "OBJECT")]
Object,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CompletionAssistantMatchMode {
Prefix,
Contains,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionAssistantRequest {
pub connection_id: String,
pub database: String,
pub schema: Option<String>,
#[serde(default)]
pub object_kinds: Vec<CompletionAssistantObjectKind>,
#[serde(default)]
pub mask: String,
#[serde(default)]
pub case_sensitive: bool,
#[serde(default)]
pub global_search: bool,
pub max_results: Option<usize>,
#[serde(default)]
pub search_in_comments: bool,
#[serde(default)]
pub search_in_definitions: bool,
pub parent_schema: Option<String>,
pub parent_name: Option<String>,
pub match_mode: Option<CompletionAssistantMatchMode>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionAssistantCandidate {
pub name: String,
pub kind: CompletionAssistantCandidateKind,
pub database: Option<String>,
pub schema: Option<String>,
pub parent_schema: Option<String>,
pub parent_name: Option<String>,
pub comment: Option<String>,
pub data_type: Option<String>,
pub signature: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub routine_id: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionAssistantResponse {
pub candidates: Vec<CompletionAssistantCandidate>,
pub incomplete: bool,
pub fallback_used: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpatialColumn {
/// Zero-based index into `QueryResult.columns`.
pub column_index: usize,
/// SRID shared by the column's geometry cells. `None` when unknown/absent
/// (or SRID 0). A column reports the first non-null SRID it observes.
pub srid: Option<u32>,
}
/// Stable identity for one column selected for SQL INSERT export.
///
/// `source_index` preserves duplicate result labels. `name` and
/// `name_occurrence` let paginated exports recover the same identity when a
/// driver reports later-page metadata in a different order.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SqlExportColumnSelection {
pub source_index: usize,
pub name: String,
#[serde(default)]
pub name_occurrence: usize,
}
#[derive(Debug, Default)]
pub struct SpatialColumnBuilder {
// column_index -> first non-null srid seen (sticky once set)
columns: std::collections::BTreeMap<usize, Option<u32>>,
}
impl SpatialColumnBuilder {
pub fn new(column_indices: impl IntoIterator<Item = usize>) -> Self {
let mut builder = Self::default();
for column_index in column_indices {
builder.columns.entry(column_index).or_insert(None);
}
builder
}
/// Record a geometry cell's SRID. The first non-null (and non-zero) value
/// wins; later observations for the same column are ignored.
pub fn observe(&mut self, column_index: usize, srid: Option<u32>) {
let entry = self.columns.entry(column_index).or_insert(None);
if entry.is_none() {
if let Some(value) = srid.filter(|value| *value != 0) {
*entry = Some(value);
}
}
}
fn finish(self) -> Vec<SpatialColumn> {
self.columns.into_iter().map(|(column_index, srid)| SpatialColumn { column_index, srid }).collect()
}
/// Drivers collect one SRID slot per cell while streaming rows; a result
/// without spatial columns drops that all-`None` matrix instead of sending
/// it to every consumer.
pub fn finish_with_values(
self,
spatial_values: Vec<Vec<Option<u32>>>,
) -> (Vec<SpatialColumn>, Vec<Vec<Option<u32>>>) {
let spatial_columns = self.finish();
let spatial_values = if spatial_columns.is_empty() { Vec::new() } else { spatial_values };
(spatial_columns, spatial_values)
}
}
/// A message emitted by the database server while executing a statement:
/// PostgreSQL `RAISE NOTICE`/`WARNING`, MySQL warnings and OK-packet info
/// strings, SQL Server `PRINT`/`RAISERROR` info messages, and similar.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryMessage {
/// Severity/level as reported by the server (e.g. `NOTICE`, `WARNING`,
/// `INFO`, `ERROR`, MySQL's `Note`/`Warning`).
pub severity: String,
pub message: String,
/// Server error/condition code (PostgreSQL SQLSTATE, MySQL error code).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hint: Option<String>,
}
impl QueryMessage {
/// One-line text rendering shared by the CLI, MCP, and agent tool output:
/// `SEVERITY: message` plus inline `(code: …, detail: …, hint: …)` extras.
pub fn format_line(&self) -> String {
let mut line = format!("{}: {}", self.severity.to_uppercase(), self.message);
let extras = [
self.code.as_ref().map(|value| format!("code: {value}")),
self.detail.as_ref().map(|value| format!("detail: {value}")),
self.hint.as_ref().map(|value| format!("hint: {value}")),
];
let extras: Vec<_> = extras.into_iter().flatten().collect();
if !extras.is_empty() {
line.push_str(&format!(" ({})", extras.join(", ")));
}
line
}
}
/// A result cell whose full variable-length value was replaced by a bounded
/// preview before the result crossed the desktop/web transport boundary.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LargeValueCell {
pub row_index: usize,
pub column_index: usize,
/// With `value_ref`, zero can mean an unknown byte size, not an empty value.
pub original_bytes: usize,
/// Opaque original-result locator. Absent for legacy preview/re-query drivers.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value_ref: Option<String>,
/// A server-truncated carrier cannot be strictly decoded until explicitly
/// fetching the complete value. The preview is not presentation data.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pending_decode: Option<bool>,
}
/// Original, complete key cells retained before presentation-only decoding.
/// These are internal read locators, never inverse-encoded displayed values.
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub struct OriginalKeyCell {
pub row_index: usize,
pub column_index: usize,
pub value: serde_json::Value,
}
impl Serialize for OriginalKeyCell {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
let mut state = serializer.serialize_struct("OriginalKeyCell", 3)?;
state.serialize_field("row_index", &self.row_index)?;
state.serialize_field("column_index", &self.column_index)?;
// Original locators already use the driver's lossless representation
// (MySQL DECIMAL/BIGINT are strings), not the display column's type.
state.serialize_field("value", &JsSafeCell(&self.value, None))?;
state.end()
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct QueryResult {
#[serde(default, rename = "large_value_cells", deserialize_with = "deserialize_vec_or_default")]
pub deferred_large_value_cells: Vec<LargeValueCell>,
#[serde(default, deserialize_with = "deserialize_vec_or_default")]
pub columns: Vec<String>,
/// Database type name for each column, parallel to `columns`. May be empty
/// when a driver cannot supply types (e.g. schemaless stores or fallback
/// query paths); consumers must tolerate a shorter/empty vector.
#[serde(default, deserialize_with = "deserialize_vec_or_default")]
pub column_types: Vec<String>,
/// Sortable for each column. Parallel to `columns`. Optional and may
/// be shorter/empty when a driver cannot supply sortable information.
#[serde(default, deserialize_with = "deserialize_vec_or_default")]
pub column_sortables: Vec<bool>,
/// Spatial reference metadata for geometry/geography cells. Kept outside
/// `rows` so displayed, copied, exported, and edited values remain WKT.
#[serde(default, deserialize_with = "deserialize_vec_or_default", skip_serializing_if = "Vec::is_empty")]
pub spatial_columns: Vec<SpatialColumn>,
/// Per-cell SRID metadata, parallel to `rows`: `spatial_values[row][column]`
/// is the SRID of that cell's geometry value (`None` for non-spatial cells
/// or unknown SRID). Unlike `spatial_columns` (a column-level hint), every
/// geometry value keeps its own SRID so mixed-SRID results stay correct.
#[serde(default, deserialize_with = "deserialize_vec_or_default", skip_serializing_if = "Vec::is_empty")]
pub spatial_values: Vec<Vec<Option<u32>>>,
#[serde(default, deserialize_with = "deserialize_vec_or_default")]
pub rows: Vec<Vec<serde_json::Value>>,
/// Sparse original key values for internal full-value reads. Empty means
/// no authoritative locator metadata, not permission to guess decoded keys.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub raw_key_cells: Vec<OriginalKeyCell>,
pub affected_rows: u64,
pub execution_time_ms: u128,
/// OceanBase SQL Audit EXECUTE_TIME in microseconds. Absent when the
/// completed statement cannot be correlated to one audit row.
#[serde(default)]
pub server_execute_time_us: Option<u64>,
/// Optional measured query phases in milliseconds; absent on older agents.
#[serde(default)]
pub query_timings_ms: Option<std::collections::BTreeMap<String, f64>>,
#[serde(default)]
pub truncated: bool,
#[serde(default)]
pub session_id: Option<String>,
#[serde(default)]
pub has_more: bool,
/// For Elasticsearch REST search results parsed into a table from _source,
/// this carries the raw HTTP response body so the UI can offer a toggle
/// between the tabular view and the original JSON.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub elasticsearch_raw_body: Option<String>,
/// Messages emitted by the database server while executing the statement
/// (notices, warnings, info messages). Empty for drivers that do not
/// capture server messages.
#[serde(default, deserialize_with = "deserialize_vec_or_default", skip_serializing_if = "Vec::is_empty")]
pub messages: Vec<QueryMessage>,
}
/// Integer cells outside JavaScript's safe integer range (±(2^53 - 1)) cross
/// the transport boundary as decimal strings so `JSON.parse` /
/// `response.json()` in the webview cannot silently round them (#7832).
/// This mirrors the driver-level convention that already ships DECIMAL and
/// MySQL BIGINT cells as strings; the manual `Serialize` impl below applies
/// the same guarantee to every `QueryResult` consumer (Tauri IPC, dbx-web
/// HTTP, agent bridges) even for paths that bypass
/// `db::json_value_for_js` normalization.
impl Serialize for QueryResult {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
// Nine always-present fields (columns, column_types, column_sortables,
// rows, affected_rows, execution_time_ms, truncated, session_id,
// has_more) plus the optional ones, matching the previous derive.
let field_count = 9
+ usize::from(!self.spatial_columns.is_empty())
+ usize::from(!self.spatial_values.is_empty())
+ usize::from(!self.raw_key_cells.is_empty())
+ usize::from(self.elasticsearch_raw_body.is_some())
+ usize::from(self.server_execute_time_us.is_some())
+ usize::from(self.query_timings_ms.is_some())
+ usize::from(!self.messages.is_empty());
let mut state = serializer.serialize_struct("QueryResult", field_count)?;
state.serialize_field("columns", &self.columns)?;
state.serialize_field("column_types", &self.column_types)?;
state.serialize_field("column_sortables", &self.column_sortables)?;
if !self.spatial_columns.is_empty() {
state.serialize_field("spatial_columns", &self.spatial_columns)?;
}
if !self.spatial_values.is_empty() {
state.serialize_field("spatial_values", &self.spatial_values)?;
}
state.serialize_field("rows", &JsSafeRows(&self.rows, &self.column_types))?;
if !self.raw_key_cells.is_empty() {
state.serialize_field("raw_key_cells", &self.raw_key_cells)?;
}
state.serialize_field("affected_rows", &self.affected_rows)?;
state.serialize_field("execution_time_ms", &self.execution_time_ms)?;
if let Some(server_execute_time_us) = &self.server_execute_time_us {
state.serialize_field("server_execute_time_us", server_execute_time_us)?;
}
if let Some(timings) = &self.query_timings_ms {
state.serialize_field("query_timings_ms", timings)?;
}
state.serialize_field("truncated", &self.truncated)?;
state.serialize_field("session_id", &self.session_id)?;
state.serialize_field("has_more", &self.has_more)?;
if let Some(body) = &self.elasticsearch_raw_body {
state.serialize_field("elasticsearch_raw_body", body)?;
}
if !self.messages.is_empty() {
state.serialize_field("messages", &self.messages)?;
}
state.end()
}
}
/// Serializes result rows with [`JsSafeCell`] wrapping so values which cannot
/// round-trip through JavaScript without losing precision become strings.
struct JsSafeRows<'a>(&'a [Vec<serde_json::Value>], &'a [String]);
impl Serialize for JsSafeRows<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeSeq;
let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
for row in self.0 {
seq.serialize_element(&JsSafeCells(row, self.1))?;
}
seq.end()
}
}
struct JsSafeCells<'a>(&'a [serde_json::Value], &'a [String]);
impl Serialize for JsSafeCells<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeSeq;
let mut seq = serializer.serialize_seq(Some(self.0.len()))?;
for (index, cell) in self.0.iter().enumerate() {
seq.serialize_element(&JsSafeCell(cell, self.1.get(index).map(String::as_str)))?;
}
seq.end()
}
}
/// Serializes one cell, replacing unsafe integers and non-round-trippable exact
/// decimal values with strings. Nested JSON values retain their existing
/// normalization behavior.
struct JsSafeCell<'a>(&'a serde_json::Value, Option<&'a str>);
impl Serialize for JsSafeCell<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeMap;
match self.0 {
serde_json::Value::Number(number) => {
let value = number.as_str();
if self.1.is_some_and(is_exact_decimal_type) && !decimal_round_trips_through_f64(value) {
return serializer.serialize_str(value);
}
if let Some(value) = number.as_i64() {
if !(-crate::json::JS_MAX_SAFE_INTEGER..=crate::json::JS_MAX_SAFE_INTEGER).contains(&value) {
return serializer.serialize_str(&value.to_string());
}
} else if let Some(value) = number.as_u64() {
if value > crate::json::JS_MAX_SAFE_INTEGER as u64 {
return serializer.serialize_str(&value.to_string());
}
} else {
let value = number.as_str();
if value.bytes().all(|byte| byte == b'-' || byte.is_ascii_digit()) {
return serializer.serialize_str(value);
}
}
self.0.serialize(serializer)
}
serde_json::Value::Array(values) => {
use serde::ser::SerializeSeq;
let mut seq = serializer.serialize_seq(Some(values.len()))?;
for value in values {
seq.serialize_element(&JsSafeCell(value, None))?;
}
seq.end()
}
serde_json::Value::Object(entries) => {
let mut map = serializer.serialize_map(Some(entries.len()))?;
for (key, value) in entries {
map.serialize_entry(key, &JsSafeCell(value, None))?;
}
map.end()
}
_ => self.0.serialize(serializer),
}
}
}
fn is_exact_decimal_type(data_type: &str) -> bool {
let normalized = data_type.trim().to_ascii_lowercase();
let normalized = normalized.strip_suffix(" unsigned").unwrap_or(&normalized).trim_end();
let base_end = normalized
.find(|character: char| character == '(' || character == '[' || character.is_whitespace())
.unwrap_or(normalized.len());
let base = &normalized[..base_end];
if !matches!(
base,
"decimal"
| "numeric"
| "number"
| "dec"
| "fixed"
| "money"
| "smallmoney"
| "bigdecimal"
| "bignumeric"
| "big_numeric"
) {
return false;
}
let suffix = normalized[base_end..].trim();
if suffix.is_empty() {
return true;
}
suffix.starts_with('(')
&& suffix.ends_with(')')
&& suffix[1..suffix.len() - 1]
.chars()
.all(|character| character.is_ascii_digit() || character == ',' || character.is_whitespace())
}
fn decimal_round_trips_through_f64(value: &str) -> bool {
let Ok(number) = value.parse::<f64>() else { return false };
if !number.is_finite() || (number == 0.0 && canonical_decimal(value).is_some_and(|decimal| decimal.digits != "0")) {
return false;
}
canonical_decimal(value)
.is_some_and(|original| canonical_decimal(&number.to_string()).is_some_and(|round_trip| original == round_trip))
}
#[derive(Debug, PartialEq, Eq)]
struct CanonicalDecimal {
negative: bool,
digits: String,
exponent: i64,
}
fn canonical_decimal(value: &str) -> Option<CanonicalDecimal> {
let (mantissa, exponent) = value
.split_once(['e', 'E'])
.map(|(mantissa, exponent)| Some((mantissa, exponent.parse::<i64>().ok()?)))
.unwrap_or_else(|| Some((value, 0)))?;
let (negative, unsigned) = match mantissa.strip_prefix('-') {
Some(unsigned) => (true, unsigned),
None => (false, mantissa.strip_prefix('+').unwrap_or(mantissa)),
};
let (integer, fraction) = unsigned.split_once('.').unwrap_or((unsigned, ""));
if integer.is_empty() && fraction.is_empty()
|| !integer.bytes().chain(fraction.bytes()).all(|byte| byte.is_ascii_digit())
{
return None;
}
let mut digits = format!("{integer}{fraction}");
let first_significant = digits.bytes().position(|digit| digit != b'0');
let Some(first_significant) = first_significant else {
return Some(CanonicalDecimal { negative: false, digits: "0".to_string(), exponent: 0 });
};
digits.drain(..first_significant);
let trailing_zero_count = digits.bytes().rev().take_while(|digit| *digit == b'0').count();
digits.truncate(digits.len() - trailing_zero_count);
let exponent = exponent.checked_sub(fraction.len() as i64)?.checked_add(trailing_zero_count as i64)?;
Some(CanonicalDecimal { negative, digits, exponent })
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexInfo {
/// Dictionary-derived index owner, independent of the parent table owner.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub owner: Option<String>,
pub name: String,
pub columns: Vec<String>,
pub is_unique: bool,
pub is_primary: bool,
pub filter: Option<String>,
pub index_type: Option<String>,
pub included_columns: Option<Vec<String>>,
pub comment: Option<String>,
/// Parallel to `columns`: `true` at index `i` means `columns[i]` is a raw expression
/// (e.g. sourced from `pg_get_indexdef`), not a plain column name. Empty when the
/// introspection source doesn't track this (provenance unknown for that dialect/path).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub key_is_expression: Vec<bool>,
/// Parallel to `columns`: Oracle-family key order (`ASC` or `DESC`). Empty when
/// the source does not expose direction metadata.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub key_directions: Vec<String>,
/// Oracle-family index visibility (`VISIBLE` or `INVISIBLE`), when available.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub visibility: Option<String>,
/// True only when the source returned aligned expression, direction and visibility metadata.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub key_metadata_complete: bool,
/// Parallel to `columns`: operator class name for each key column, if non-default.
/// For example, a GIN trigram index on a varchar column will have `"gin_trgm_ops"`.
/// `None` means the default operator class is used (can be omitted in DDL).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub column_opclasses: Vec<Option<String>>,
/// Parallel to `columns`: PostgreSQL `pg_index.indoption` flags for each key.
/// Bit 0 is DESC and bit 1 is NULLS FIRST. Empty when the introspection source
/// does not expose per-key ordering metadata.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub key_options: Vec<i16>,
/// `true` when this index is the object *behind* a table constraint (PRIMARY KEY or
/// UNIQUE) rather than a standalone index. Dameng lists both kinds in `ALL_INDEXES`
/// but only a standalone ("real") index accepts index-level DDL: a constraint-backed
/// ("virtual") one must be changed through `ALTER TABLE ... ADD/DROP CONSTRAINT`
/// (#7959). Defaults to `false` for every introspection source that does not report
/// it, which keeps those indexes on the index-level DDL path.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub constraint_backed: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForeignKeyInfo {
pub name: String,
pub column: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ref_schema: Option<String>,
pub ref_table: String,
pub ref_column: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_update: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_delete: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TriggerInfo {
pub name: String,
pub event: String,
pub timing: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub level: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub condition: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub language: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub valid: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub created_at: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub statement: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub oracle_metadata: Option<OracleTriggerMetadata>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConstraintInfo {
pub name: String,
pub constraint_type: String,
pub definition: String,
#[serde(default)]
pub columns: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ref_schema: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ref_table: Option<String>,
#[serde(default)]
pub ref_columns: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub match_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_update: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_delete: Option<String>,
#[serde(default)]
pub deferrable: Option<bool>,
#[serde(default)]
pub initially_deferred: Option<bool>,
#[serde(default)]
pub enabled: Option<bool>,
#[serde(default)]
pub valid: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub oracle_metadata: Option<OracleConstraintMetadata>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleConstraintMetadata {
pub metadata_complete: bool,
pub owner: String,
pub constraint_type: Option<String>,
pub status: Option<String>,
pub validated: Option<String>,
pub deferrable: Option<String>,
pub deferred: Option<String>,
pub rely: Option<String>,
pub index_owner: Option<String>,
pub index_name: Option<String>,
pub index_sharing: Option<String>,
pub index: Option<OracleConstraintIndexMetadata>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleConstraintIndexMetadata {
pub metadata_complete: bool,
pub owner: String,
pub table_owner: String,
pub table_name: String,
pub index_type: String,
pub uniqueness: String,
pub status: String,
pub partitioned: bool,
pub visibility: String,
pub secondary: Option<String>,
pub columns: Vec<String>,
pub directions: Vec<String>,
pub key_is_expression: Vec<bool>,
pub included_columns: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PartitionInfo {
pub name: String,
pub position: i32,
pub value: String,
pub partition_type: String,
pub partition_key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub online: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auto_partition_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub auto_partition_span: Option<i32>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubpartitionInfo {
pub name: String,
pub position: i32,
pub value: String,
pub partition_type: String,
pub partition_key: String,
}
/// PostgreSQL declarative partitioning strategy (`pg_partitioned_table.partstrat`:
/// `r` = range, `l` = list, `h` = hash).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PgPartitionKind {
Range,
List,
Hash,
}
/// Structured form of a partition's `pg_get_expr(relpartbound)` definition.
///
/// Values are kept as SQL literal text (`'2024-01-01'`, `1`, `MINVALUE`,
/// `MAXVALUE`, `'a'`) so the UI can round-trip exactly what PostgreSQL
/// reported without re-typing or re-quoting them client-side.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum PgPartitionBound {
Range { from: Vec<String>, to: Vec<String> },
List { values: Vec<String> },
Hash { modulus: i32, remainder: i32 },
Default,
}
/// One relation in a PostgreSQL partition hierarchy, as returned by
/// `get_table_partitioning_core`. `children` is nested to the same depth as
/// the catalog's partition tree (PG supports multi-level partitioning).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PgPartitionNode {
pub schema: String,
pub name: String,
/// Set only when this node is itself a partitioned parent.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub strategy: Option<PgPartitionKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_definition: Option<String>,
/// This node's own partition bound (set for every non-root node).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bound: Option<PgPartitionBound>,
/// Raw `pg_get_expr(relpartbound)` text; retained as a display fallback
/// when `bound` could not be parsed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bound_definition: Option<String>,
#[serde(default)]
pub is_leaf: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub row_estimate: Option<i64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub total_bytes: Option<i64>,
#[serde(default)]
pub children: Vec<PgPartitionNode>,
}
/// Structured partitioning view of one PostgreSQL relation, used by the table
/// structure editor's "Partitions" tab. Works for the partitioned parent
/// (`is_partitioned`), for a member partition (`is_partition`), and reports
/// the whole subtree rooted at the requested relation either way.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PgTablePartitioning {
pub is_partitioned: bool,
pub is_partition: bool,
/// Display form `"schema.table"` of the owning parent, when this relation
/// is itself a partition.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent: Option<String>,
/// Parent parts, kept separate so a dotted identifier cannot be mis-split.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent_schema: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent_table: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub own_bound: Option<PgPartitionBound>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub strategy: Option<PgPartitionKind>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_definition: Option<String>,
#[serde(default)]
pub key_columns: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub key_expression: Option<String>,
/// Name of the default partition, when the parent has one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_partition: Option<String>,
/// Descendant partitions (the root itself is not included).
#[serde(default)]
pub partitions: Vec<PgPartitionNode>,
/// Server version (`current_setting('server_version_num')`), used by the UI
/// to gate `DETACH PARTITION CONCURRENTLY` (PostgreSQL 14+).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub server_version_num: Option<i32>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FunctionInfo {
pub name: String,
pub function_type: String,
pub data_type: String,
pub definition: String,
pub arguments: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SequenceInfo {
pub name: String,
pub data_type: String,
pub start_value: String,
pub min_value: String,
pub max_value: String,
pub increment: String,
pub cycle: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_value: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RuleInfo {
pub name: String,
pub table_name: String,
pub definition: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OwnerInfo {
pub object_name: String,
pub object_type: String,
pub owner: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CustomTypeKind {
Base,
Composite,
Domain,
Enum,
Range,
Multirange,
Object,
Collection,
Other,
}
impl CustomTypeKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Base => "base",
Self::Composite => "composite",
Self::Domain => "domain",
Self::Enum => "enum",
Self::Range => "range",
Self::Multirange => "multirange",
Self::Object => "object",
Self::Collection => "collection",
Self::Other => "other",
}
}
}
/// A member of a user-defined type.
///
/// Composite types expose fields (`name`/`data_type`/`ordinal`/`nullable`/
/// `default`/`comment`), enums expose values (`ordinal`/`enum_value`), and
/// domains/ranges/base types expose neither (their members list stays empty;
/// the UI shows an explanatory empty state instead).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomTypeMember {
pub name: String,
pub data_type: String,
pub ordinal: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub nullable: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub enum_value: Option<String>,
}
/// A domain CHECK constraint, keeping its name so generated DDL never invents
/// duplicate constraint identifiers.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomTypeDomainConstraint {
pub name: String,
pub definition: String,
}
/// Category-specific type attributes. Fields that do not apply to a category
/// are `None`, never empty strings, so the UI can distinguish “unknown” from
/// “not applicable”.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomTypeProperties {
pub base_type: Option<String>,
pub not_null: Option<bool>,
pub default: Option<String>,
pub collation: Option<String>,
#[serde(default)]
pub domain_constraints: Vec<CustomTypeDomainConstraint>,
pub range_subtype: Option<String>,
pub range_multirange_name: Option<String>,
pub range_canonical_function: Option<String>,
pub range_subtype_diff_function: Option<String>,
pub range_subtype_opclass: Option<String>,
pub input_function: Option<String>,
pub output_function: Option<String>,
pub receive_function: Option<String>,
pub send_function: Option<String>,
pub analyze_function: Option<String>,
pub internallength: Option<i32>,
pub passed_by_value: Option<bool>,
pub alignment: Option<String>,
pub storage: Option<String>,
}
/// Generated `CREATE TYPE` text for a user-defined type.
///
/// `complete = true` means the text can be executed standalone in the current
/// schema. `complete = false` means the text is for viewing only (it may depend
/// on other types/functions or internal attributes); `warnings` must be shown
/// in the UI and the text must never be presented as executable source.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomTypeDdl {
pub sql: String,
pub complete: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<String>,
}
/// Completeness of one Oracle-family dictionary section, within the current
/// user's visible scope. An unavailable section retains its read error.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TypeMetadataState {
Available,
Incomplete,
Unavailable,
Unsupported,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TypeMetadataRead {
pub state: TypeMetadataState,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeAttribute {
pub name: String,
pub ordinal: Option<i32>,
pub type_owner: Option<String>,
pub type_name: Option<String>,
pub type_modifier: Option<String>,
pub length: Option<i64>,
pub precision: Option<i32>,
pub scale: Option<i32>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeMethodParameter {
pub name: Option<String>,
pub ordinal: Option<i32>,
pub mode: Option<String>,
pub type_owner: Option<String>,
pub type_name: Option<String>,
pub type_modifier: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeMethod {
pub name: String,
pub number: Option<i32>,
pub kind: Option<String>,
pub parameter_count: Option<u32>,
pub result_count: Option<u32>,
pub parameters: Vec<OracleTypeMethodParameter>,
pub results: Vec<OracleTypeMethodParameter>,
pub parameters_read: TypeMetadataRead,
pub results_read: TypeMetadataRead,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeCollection {
pub kind: Option<String>,
pub upper_bound: Option<i64>,
pub element_owner: Option<String>,
pub element_name: Option<String>,
pub element_modifier: Option<String>,
pub length: Option<i64>,
pub precision: Option<i32>,
pub scale: Option<i32>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeMetadata {
pub status: Option<String>,
pub type_code: Option<String>,
pub is_final: Option<bool>,
pub instantiable: Option<bool>,
pub supertype_owner: Option<String>,
pub supertype_name: Option<String>,
pub attribute_count: Option<u32>,
pub method_count: Option<u32>,
/// `false` means no body in this successful dictionary read, not globally absent.
pub body_visible: Option<bool>,
pub body_status: Option<String>,
pub properties_read: TypeMetadataRead,
pub body_read: TypeMetadataRead,
pub attributes_read: TypeMetadataRead,
pub methods_read: TypeMetadataRead,
pub collection_read: TypeMetadataRead,
pub attributes: Vec<OracleTypeAttribute>,
pub methods: Vec<OracleTypeMethod>,
pub collection: Option<OracleTypeCollection>,
}
/// A readback value used by the controlled Oracle-family TYPE manager. `None`
/// is kept distinct from an empty value when the relevant dictionary read is
/// incomplete or unavailable.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeManagementSnapshot {
pub target: OracleTypeManagementTarget,
/// Catalogues queried by this snapshot are limited to the current user's visible scope.
pub visibility_scope: String,
pub acting_user: Option<String>,
pub acting_user_read: TypeMetadataRead,
pub details: Option<CustomTypeDetails>,
pub details_read: TypeMetadataRead,
pub type_source: Option<String>,
pub type_source_read: TypeMetadataRead,
pub body_source: Option<String>,
pub body_source_read: TypeMetadataRead,
pub objects: Vec<OracleTypeManagementObject>,
pub dependencies: Vec<OracleTypeManagementDependency>,
pub dependencies_read: TypeMetadataRead,
pub persistent_references: Vec<OracleTypeManagementReference>,
pub persistent_references_read: TypeMetadataRead,
pub direct_privileges: Vec<OracleTypeManagementPrivilege>,
pub privileges_read: TypeMetadataRead,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OracleTypeManagementSqlOperation {
SaveSpec,
SaveBody,
DropSpec,
DropBody,
GrantExecute,
GrantPrivilege,
RebuildSource,
CompileSpec,
CompileTrigger,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeManagementSqlInput {
pub database_type: DatabaseType,
pub operation: OracleTypeManagementSqlOperation,
pub owner: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub grantee: Option<String>,
#[serde(default)]
pub grantable: bool,
#[serde(default)]
pub object_type: Option<ObjectSourceKind>,
#[serde(default)]
pub privilege: Option<String>,
#[serde(default)]
pub trigger_enabled: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeManagementSqlResult {
pub statements: Vec<String>,
pub source_fingerprint: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeManagementTarget {
pub connection_id: String,
pub database: String,
pub owner: String,
pub name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeManagementObjectKey {
pub owner: String,
pub name: String,
pub object_type: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeManagementSnapshotRequest {
pub target: OracleTypeManagementTarget,
#[serde(default)]
pub known_objects: Vec<OracleTypeManagementObjectKey>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeManagementObject {
pub owner: String,
pub name: String,
pub object_type: String,
pub exists: Option<bool>,
pub object_id: Option<String>,
pub status: Option<String>,
pub status_read: TypeMetadataRead,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trigger_enabled: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trigger_enabled_read: Option<TypeMetadataRead>,
pub source: Option<String>,
pub source_read: TypeMetadataRead,
pub source_fingerprint: Option<String>,
pub errors: Vec<OracleTypeManagementError>,
pub errors_read: TypeMetadataRead,
#[serde(default)]
pub direct_privileges: Vec<OracleTypeManagementPrivilege>,
pub privileges_read: TypeMetadataRead,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeManagementError {
pub line: u32,
pub position: u32,
pub text: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeManagementDependency {
pub owner: String,
pub name: String,
pub object_type: String,
pub referenced_owner: String,
pub referenced_name: String,
pub referenced_type: String,
pub referenced_link: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeManagementReference {
pub owner: String,
pub table_name: String,
pub column_name: Option<String>,
pub data_type_owner: Option<String>,
pub data_type: Option<String>,
pub table_status: Option<String>,
pub table_read_only: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeManagementPrivilege {
pub grantee: String,
pub privilege: String,
pub grantable: Option<bool>,
pub hierarchy: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub grantor: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub privilege_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub privilege_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub column_id: Option<String>,
}
/// Exact durable scalar relations used only by a TYPE migration. No business rows
/// are serialized into this manifest or returned by the verification endpoint.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeDataRelationKey {
pub owner: String,
pub name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeDataField {
pub source_path: Vec<String>,
#[serde(default)]
pub object_null: bool,
pub old_column: String,
pub expected_column: String,
pub target_path: Vec<String>,
#[serde(default)]
pub target_object_null: bool,
#[serde(default)]
pub unchanged: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeDataMappingInput {
pub id: String,
pub source: OracleTypeDataRelationKey,
pub old: OracleTypeDataRelationKey,
pub expected: OracleTypeDataRelationKey,
pub target: OracleTypeDataRelationKey,
pub fields: Vec<OracleTypeDataField>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeDataProjection {
pub path: Vec<String>,
pub object_null: bool,
pub data_type: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeDataRelation {
pub relation: OracleTypeDataRelationKey,
pub object_id: String,
pub read_only: Option<bool>,
/// Directly inspectable metadata, not a digest of ordinary definitions.
pub structure: String,
pub projection: Vec<OracleTypeDataProjection>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeDataBaseline {
pub relation: OracleTypeDataRelation,
pub row_count: u32,
pub fingerprint: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeDataManifest {
pub mapping: OracleTypeDataMappingInput,
pub original: OracleTypeDataBaseline,
pub old: OracleTypeDataBaseline,
pub expected: OracleTypeDataBaseline,
#[serde(default)]
pub prepared_target: Option<OracleTypeDataBaseline>,
#[serde(default)]
pub verified_target: Option<OracleTypeDataBaseline>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeDataRequest {
pub target: OracleTypeManagementTarget,
pub action: String,
#[serde(default)]
pub relation: Option<OracleTypeDataRelationKey>,
#[serde(default)]
pub mapping: Option<OracleTypeDataMappingInput>,
#[serde(default)]
pub manifest: Option<OracleTypeDataManifest>,
#[serde(default)]
pub sql: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeDataResult {
pub relation: Option<OracleTypeDataRelation>,
pub manifest: Option<OracleTypeDataManifest>,
pub insert_sql: Option<String>,
}
/// Native ALTER TYPE never exports UDT values or requires user-prepared baselines.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeEvolutionManifest {
pub target: OracleTypeManagementTarget,
pub source_before: String,
pub source_after: String,
pub statements: Vec<String>,
/// Inspectable identity/restriction metadata and row counts, not a data hash.
pub metadata: String,
pub phase: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OracleTypeEvolutionRequest {
pub target: OracleTypeManagementTarget,
pub source_before: String,
pub source_after: String,
#[serde(default)]
pub manifest: Option<OracleTypeEvolutionManifest>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CustomTypeDetails {
pub name: String,
pub schema: String,
pub kind: CustomTypeKind,
pub comment: Option<String>,
#[serde(default)]
pub members: Vec<CustomTypeMember>,
pub properties: CustomTypeProperties,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ddl: Option<CustomTypeDdl>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub oracle_metadata: Option<OracleTypeMetadata>,
}
#[cfg(test)]
mod tests {
#[test]
fn custom_type_details_accepts_old_pg_json_without_oracle_metadata() {
let old = serde_json::json!({
"name": "state", "schema": "public", "kind": "enum", "comment": null,
"members": [{"name": "", "dataType": "", "ordinal": 1, "enumValue": "ready"}],
"properties": {}, "ddl": {"sql": "CREATE TYPE state AS ENUM ('ready');", "complete": true}
});
let details: super::CustomTypeDetails = serde_json::from_value(old).unwrap();
assert!(details.oracle_metadata.is_none());
assert!(details.ddl.as_ref().unwrap().complete);
assert_eq!(details.members[0].enum_value.as_deref(), Some("ready"));
let serialized = serde_json::to_value(details).unwrap();
assert!(serialized.get("oracleMetadata").is_none());
for (kind, label) in [
(super::CustomTypeKind::Object, "object"),
(super::CustomTypeKind::Collection, "collection"),
(super::CustomTypeKind::Other, "other"),
] {
assert_eq!(kind.as_str(), label);
assert_eq!(serde_json::to_value(kind).unwrap(), label);
assert_eq!(serde_json::from_value::<super::CustomTypeKind>(serde_json::json!(label)).unwrap(), kind);
}
}
#[test]
fn blob_bindings_refuse_edited_previews_and_invalid_later_parameters() {
let previews = vec!["first reviewed save".to_string(), "second reviewed save".to_string()];
let mut bound = previews
.iter()
.map(|preview| super::BlobBoundStatement {
preview_sql: preview.clone(),
sql: "BEGIN UPDATE T SET B=?; END;".into(),
blob_parameters: vec!["00ff".into()],
})
.collect::<Vec<_>>();
assert!(super::validate_blob_bound_statements(&previews, &bound).is_ok());
bound[1].blob_parameters[0] = "xyz".into();
assert!(super::validate_blob_bound_statements(&previews, &bound).is_err());
bound[1].blob_parameters[0] = "00ff".into();
bound[1].preview_sql = "user edited SQL".into();
assert!(super::validate_blob_bound_statements(&previews, &bound).is_err());
assert!(super::validate_blob_bound_statements(&previews, &bound[..1]).is_err());
}
use super::{
is_opaque_aggregate_state_type, CompletionAssistantCandidate, CompletionAssistantCandidateKind, ObjectInfo,
ObjectSource, ObjectSourceKind, QueryMessage, RoutineParameterMode, SpatialColumn, SpatialColumnBuilder,
TableInfo,
};
#[test]
fn opaque_aggregate_state_type_is_narrow() {
assert!(is_opaque_aggregate_state_type("agg_state<group_concat(text)>"));
assert!(is_opaque_aggregate_state_type(" AGG_STATE <sum(int)> "));
assert!(!is_opaque_aggregate_state_type("agg_state"));
assert!(!is_opaque_aggregate_state_type("agg_state<"));
assert!(!is_opaque_aggregate_state_type("agg_state<>"));
assert!(!is_opaque_aggregate_state_type("😺agg_state<sum(int)>"));
assert!(!is_opaque_aggregate_state_type("varchar"));
}
#[test]
fn query_message_format_line_uppercases_severity() {
let message = QueryMessage {
severity: "notice".to_string(),
message: "hello world".to_string(),
code: None,
detail: None,
hint: None,
};
assert_eq!(message.format_line(), "NOTICE: hello world");
}
#[test]
fn query_message_format_line_appends_code_detail_hint_extras() {
let message = QueryMessage {
severity: "WARNING".to_string(),
message: "careful".to_string(),
code: Some("01000".to_string()),
detail: Some("column truncated".to_string()),
hint: Some("widen the column".to_string()),
};
assert_eq!(
message.format_line(),
"WARNING: careful (code: 01000, detail: column truncated, hint: widen the column)"
);
}
#[test]
fn query_message_format_line_skips_missing_extras() {
let message = QueryMessage {
severity: "INFO".to_string(),
message: "Records: 3".to_string(),
code: None,
detail: None,
hint: Some("use a table".to_string()),
};
assert_eq!(message.format_line(), "INFO: Records: 3 (hint: use a table)");
}
#[test]
fn query_message_omits_empty_optional_fields_in_json() {
let minimal = QueryMessage {
severity: "NOTICE".to_string(),
message: "hello".to_string(),
code: None,
detail: None,
hint: None,
};
assert_eq!(
serde_json::to_value(&minimal).unwrap(),
serde_json::json!({ "severity": "NOTICE", "message": "hello" })
);
let full = QueryMessage {
severity: "NOTICE".to_string(),
message: "hello".to_string(),
code: Some("00000".to_string()),
detail: Some("d".to_string()),
hint: Some("h".to_string()),
};
assert_eq!(
serde_json::to_value(&full).unwrap(),
serde_json::json!({ "severity": "NOTICE", "message": "hello", "code": "00000", "detail": "d", "hint": "h" })
);
}
#[test]
fn query_message_deserializes_without_optional_fields() {
let message: QueryMessage = serde_json::from_str(r#"{"severity":"Note","message":"Records: 1"}"#).unwrap();
assert_eq!(message.severity, "Note");
assert_eq!(message.message, "Records: 1");
assert_eq!(message.code, None);
assert_eq!(message.detail, None);
assert_eq!(message.hint, None);
}
#[test]
fn list_objects_payload_preserves_optional_validity() {
let objects: Vec<ObjectInfo> =
serde_json::from_str(
r#"[{"name":"TRG_AUDIT","object_type":"TRIGGER","schema":"APP","valid":false,"trigger":{"name":"TRG_AUDIT","event":"INSERT","timing":"BEFORE","level":"FOR EACH ROW","enabled":false,"valid":false,"comment":"audit","created_at":"2026-08-10 09:30:00"}},{"name":"ORDER_TYPE","object_type":"TYPE","schema":"APP","xugu_type_members_expandable":true}]"#,
)
.unwrap();
assert_eq!(objects[0].valid, Some(false));
assert_eq!(objects[0].object_type, "TRIGGER");
let trigger = objects[0].trigger.as_ref().unwrap();
assert_eq!(trigger.level.as_deref(), Some("FOR EACH ROW"));
assert_eq!(trigger.enabled, Some(false));
assert_eq!(trigger.comment.as_deref(), Some("audit"));
assert_eq!(objects[1].xugu_type_members_expandable, Some(true));
}
#[test]
fn dameng_table_validity_round_trips_true_false_and_unknown() {
for validity in [Some(true), Some(false), None] {
let payload = serde_json::json!({"name": "VIEW_A", "table_type": "VIEW", "valid": validity});
let table: TableInfo = serde_json::from_value(payload).unwrap();
assert_eq!(table.valid, validity);
let encoded = serde_json::to_value(&table).unwrap();
assert_eq!(encoded.get("valid").and_then(serde_json::Value::as_bool), validity);
assert_eq!(encoded.get("valid").is_some(), validity.is_some());
let decoded: TableInfo = serde_json::from_value(encoded).unwrap();
assert_eq!(decoded.valid, validity);
}
let legacy: TableInfo = serde_json::from_str(r#"{"name":"TABLE_A","table_type":"TABLE"}"#).unwrap();
assert_eq!(legacy.valid, None);
}
#[test]
fn dameng_object_validity_round_trips_true_false_and_unknown() {
for validity in [Some(true), Some(false), None] {
let payload =
serde_json::json!({"name": "VIEW_A", "object_type": "VIEW", "schema": "APP", "valid": validity});
let object: ObjectInfo = serde_json::from_value(payload).unwrap();
assert_eq!(object.valid, validity);
let encoded = serde_json::to_value(&object).unwrap();
assert_eq!(encoded.get("valid").and_then(serde_json::Value::as_bool), validity);
assert_eq!(encoded.get("valid").is_some(), validity.is_some());
let decoded: ObjectInfo = serde_json::from_value(encoded).unwrap();
assert_eq!(decoded.valid, validity);
}
let legacy: ObjectInfo = serde_json::from_str(r#"{"name":"TABLE_A","object_type":"TABLE"}"#).unwrap();
assert_eq!(legacy.valid, None);
}
#[test]
fn spatial_builder_reports_first_non_null_srid_per_column() {
let mut builder = SpatialColumnBuilder::new([3]);
builder.observe(3, None);
builder.observe(1, Some(4326));
builder.observe(3, Some(3857));
builder.observe(3, Some(4490)); // ignored: column 3 already set
builder.observe(1, None); // ignored: column 1 already set
assert_eq!(
builder.finish(),
vec![
SpatialColumn { column_index: 1, srid: Some(4326) },
SpatialColumn { column_index: 3, srid: Some(3857) },
]
);
}
#[test]
fn spatial_builder_normalizes_zero_and_all_null() {
let mut builder = SpatialColumnBuilder::new([0]);
builder.observe(0, Some(0)); // SRID 0 -> unknown
assert_eq!(builder.finish(), vec![SpatialColumn { column_index: 0, srid: None }]);
assert!(SpatialColumnBuilder::default().finish().is_empty());
}
#[test]
fn spatial_builder_omits_values_without_spatial_columns() {
let values = vec![vec![None, None]];
let (columns, values) = SpatialColumnBuilder::default().finish_with_values(values);
assert!(columns.is_empty());
assert!(values.is_empty());
let expected_values = vec![vec![None, None]];
let (columns, values) = SpatialColumnBuilder::new([0]).finish_with_values(expected_values.clone());
assert_eq!(columns, vec![SpatialColumn { column_index: 0, srid: None }]);
assert_eq!(values, expected_values);
}
#[test]
fn object_source_kind_accepts_synonym_wire_value() {
let kind: ObjectSourceKind = serde_json::from_str("\"SYNONYM\"").unwrap();
assert_eq!(kind, ObjectSourceKind::Synonym);
assert_eq!(serde_json::to_string(&kind).unwrap(), "\"SYNONYM\"");
}
#[test]
fn object_source_kind_accepts_job_wire_value() {
let kind: ObjectSourceKind = serde_json::from_str("\"JOB\"").unwrap();
assert_eq!(kind, ObjectSourceKind::Job);
assert_eq!(serde_json::to_string(&kind).unwrap(), "\"JOB\"");
}
#[test]
fn object_source_accepts_legacy_payload_without_routine_parameters() {
let source: ObjectSource = serde_json::from_value(serde_json::json!({
"name": "legacy_proc",
"object_type": "PROCEDURE",
"schema": "APP",
"source": "CREATE PROCEDURE legacy_proc() BEGIN END"
}))
.unwrap();
assert!(source.routine_parameters.is_none());
assert!(serde_json::to_value(source).unwrap().get("routine_parameters").is_none());
}
#[test]
fn object_source_preserves_optional_jdbc_routine_parameters() {
let source: ObjectSource = serde_json::from_value(serde_json::json!({
"name": "calculate_total",
"object_type": "FUNCTION",
"schema": "APP",
"source": "",
"editable": false,
"routine_parameters": [{
"name": "RETURN",
"mode": "RETURN",
"jdbc_type": 3,
"type_name": "DECIMAL",
"precision": 12,
"scale": 2,
"ordinal": 0
}]
}))
.unwrap();
let parameters = source.routine_parameters.as_ref().unwrap();
assert_eq!(parameters[0].mode, RoutineParameterMode::Return);
assert_eq!(parameters[0].precision, Some(12));
assert_eq!(serde_json::to_value(source).unwrap()["routine_parameters"][0]["mode"], "RETURN");
}
#[test]
fn completion_candidate_kind_accepts_uppercase_agent_wire_values() {
for (wire_value, expected) in [
("DATABASE", CompletionAssistantCandidateKind::Database),
("SCHEMA", CompletionAssistantCandidateKind::Schema),
("TABLE", CompletionAssistantCandidateKind::Table),
("VIEW", CompletionAssistantCandidateKind::View),
("PROCEDURE", CompletionAssistantCandidateKind::Procedure),
("FUNCTION", CompletionAssistantCandidateKind::Function),
("COLUMN", CompletionAssistantCandidateKind::Column),
("SEQUENCE", CompletionAssistantCandidateKind::Sequence),
("OBJECT", CompletionAssistantCandidateKind::Object),
] {
let payload = serde_json::json!({
"name": "id",
"kind": wire_value,
"database": null,
"schema": "public",
"parent_schema": "public",
"parent_name": "users",
"comment": null,
"data_type": "integer",
"signature": null,
});
let candidate: CompletionAssistantCandidate = serde_json::from_value(payload).unwrap();
assert_eq!(candidate.kind, expected);
assert_eq!(serde_json::to_value(candidate.kind).unwrap(), wire_value.to_ascii_lowercase());
}
}
#[test]
fn query_result_receives_deferred_cells_without_serializing_a_second_metadata_field() {
for original_bytes in [0, 67108864] {
let mut wire = serde_json::to_value(bigint_result_sample()).unwrap();
wire["large_value_cells"] = serde_json::json!([{
"row_index": 0, "column_index": 0, "original_bytes": original_bytes, "value_ref": "original-lob"
}]);
let result: super::QueryResult = serde_json::from_value(wire).unwrap();
assert_eq!(result.deferred_large_value_cells.len(), 1);
assert_eq!(result.deferred_large_value_cells[0].value_ref.as_deref(), Some("original-lob"));
assert_eq!(result.deferred_large_value_cells[0].original_bytes, original_bytes);
let serialized = serde_json::to_value(&result).unwrap();
assert!(serialized.get("large_value_cells").is_none());
assert!(serialized.get("deferred_large_value_cells").is_none());
}
}
fn bigint_result_sample() -> super::QueryResult {
super::QueryResult {
columns: vec!["id".to_string()],
column_types: vec!["bigint".to_string()],
deferred_large_value_cells: Vec::new(),
column_sortables: Vec::new(),
spatial_columns: Vec::new(),
raw_key_cells: Vec::new(),
spatial_values: Vec::new(),
rows: vec![vec![
serde_json::json!(1391198305898897409i64),
serde_json::json!(9007199254740991i64),
serde_json::json!(42),
serde_json::json!(-9007199254740992i64),
serde_json::json!(18446744073709551615u64),
serde_json::json!("1391198305898897409"),
serde_json::Value::Null,
]],
affected_rows: 0,
execution_time_ms: 0,
server_execute_time_us: None,
query_timings_ms: None,
truncated: false,
session_id: None,
has_more: false,
elasticsearch_raw_body: None,
messages: Vec::new(),
}
}
#[test]
fn raw_key_cells_are_optional_and_preserve_javascript_integer_fidelity() {
let mut result = bigint_result_sample();
assert!(serde_json::to_value(&result).unwrap().get("raw_key_cells").is_none());
result.raw_key_cells = vec![super::OriginalKeyCell {
row_index: 0,
column_index: 0,
value: serde_json::json!(1391198305898897409i64),
}];
let wire = serde_json::to_value(&result).unwrap();
assert_eq!(wire["raw_key_cells"][0]["value"], "1391198305898897409");
let restored: super::QueryResult = serde_json::from_value(wire).unwrap();
assert_eq!(restored.raw_key_cells[0].value, "1391198305898897409");
let mut old_wire = serde_json::to_value(bigint_result_sample()).unwrap();
old_wire.as_object_mut().unwrap().remove("raw_key_cells");
assert!(serde_json::from_value::<super::QueryResult>(old_wire).unwrap().raw_key_cells.is_empty());
}
/// #7832: integers beyond JavaScript's ±(2^53 - 1) safe range must cross
/// the transport boundary as decimal strings, while safe integers keep
/// their JSON number form so ordinary grids stay unchanged.
#[test]
fn query_result_serializes_unsafe_integers_as_strings() {
let serialized = serde_json::to_value(bigint_result_sample()).unwrap();
let row = &serialized["rows"][0];
assert_eq!(row[0], serde_json::json!("1391198305898897409"), "big i64 becomes a string");
assert_eq!(row[1], serde_json::json!(9007199254740991i64), "max safe i64 stays a number");
assert_eq!(row[2], serde_json::json!(42), "small integers stay numbers");
assert_eq!(row[3], serde_json::json!("-9007199254740992"), "min unsafe i64 becomes a string");
assert_eq!(row[4], serde_json::json!("18446744073709551615"), "big u64 becomes a string");
assert_eq!(row[5], serde_json::json!("1391198305898897409"), "existing strings pass through");
assert_eq!(row[6], serde_json::Value::Null, "null passes through");
}
#[test]
fn query_result_serializes_integers_beyond_64_bits_as_strings() {
let integers = [
"18446744073709551616",
"18446744073709551617",
"-9223372036854775809",
"2026081810175800100000000000",
"2026081810175800100000000001",
"-2026081810175800100000000000",
"99999999999999999999999999999999999999",
];
let mut result = bigint_result_sample();
result.rows = integers.iter().map(|integer| vec![serde_json::from_str(integer).unwrap()]).collect();
let expected = serde_json::json!(integers.iter().map(|integer| vec![*integer]).collect::<Vec<_>>());
assert_eq!(serde_json::to_value(&result).unwrap()["rows"], expected);
let wire = serde_json::to_string(&result).unwrap();
let deserialized: super::QueryResult = serde_json::from_str(&wire).unwrap();
assert_eq!(serde_json::to_value(&deserialized.rows).unwrap(), expected);
}
#[test]
fn query_result_preserves_precision_sensitive_exact_numeric_cells_for_js() {
for value in [
"9007199254740993.123456789012",
"-9007199254740993.123456789012",
"0.1234567890123456789012345",
"1.234567890123456789e30",
"12345678901234567",
"1e400",
"1e-400",
] {
let mut result = bigint_result_sample();
result.columns = vec!["AMOUNT".to_string()];
result.column_types = vec!["NUMBER(38,12)".to_string()];
result.rows = vec![vec![serde_json::from_str(value).unwrap()]];
let rows_before = result.rows.clone();
let number_token = result.rows[0][0].as_number().unwrap().as_str();
let wire = serde_json::to_string(&result).unwrap();
let serialized: serde_json::Value = serde_json::from_str(&wire).unwrap();
assert_eq!(serialized["rows"][0][0], number_token, "{value}");
assert_eq!(result.rows, rows_before, "serialization must not mutate in-memory rows");
let decoded: super::QueryResult = serde_json::from_str(&wire).unwrap();
assert_eq!(serde_json::to_value(&decoded).unwrap()["rows"][0][0], serialized["rows"][0][0]);
}
}
#[test]
fn query_result_precision_wire_matches_shared_javascript_fixture() {
let mut result = bigint_result_sample();
result.columns = vec!["AMOUNT".to_string()];
result.column_types = vec!["NUMBER(38,12)".to_string()];
result.column_sortables.clear();
result.rows = vec![vec![serde_json::from_str("9007199254740993.123456789012").unwrap()]];
let serialized = serde_json::to_string(&result).unwrap();
let expected: serde_json::Value = serde_json::from_str(include_str!(
"../../../apps/desktop/src/lib/__tests__/dataGrid/fixtures/exactDecimalQueryResult.json"
))
.unwrap();
assert_eq!(serde_json::from_str::<serde_json::Value>(&serialized).unwrap(), expected);
}
#[test]
fn query_result_keeps_exact_decimals_as_numbers_when_binary64_decimal_roundtrip_is_safe() {
for value in [
"0.1",
"123.45",
"1.25e-7",
"1234567890123456.5",
"1234567890123456",
"123.4500",
"1.2345e2",
"1234567890123456.0",
"0e-400",
] {
let mut result = bigint_result_sample();
result.columns = vec!["AMOUNT".to_string()];
result.column_types = vec!["DECIMAL(38,12)".to_string()];
result.rows = vec![vec![serde_json::from_str(value).unwrap()]];
let serialized = serde_json::to_value(&result).unwrap();
assert!(serialized["rows"][0][0].is_number(), "{value}: {serialized}");
}
let mut result = bigint_result_sample();
result.column_types = vec!["DECIMAL".to_string()];
result.rows = vec![vec![serde_json::from_str("10000000000000000").unwrap()]];
assert_eq!(serde_json::to_value(result).unwrap()["rows"][0][0], "10000000000000000");
}
#[test]
fn query_result_exact_decimal_guard_is_type_scoped_and_tolerates_missing_metadata() {
let original = "9007199254740993.123456789012";
for column_type in [
"decimal",
"numeric(38,12)",
"number (38, 12)",
"dec",
"fixed",
"money",
"smallmoney",
"bigdecimal",
"bignumeric",
"big_numeric",
"decimal(38,12) unsigned",
] {
let mut result = bigint_result_sample();
result.column_types = vec![column_type.to_string()];
result.rows = vec![vec![serde_json::from_str(original).unwrap()]];
assert_eq!(serde_json::to_value(&result).unwrap()["rows"][0][0], original, "{column_type}");
}
for column_type in [
"FLOAT",
"DOUBLE PRECISION",
"REAL",
"BINARY_FLOAT",
"BINARY_DOUBLE",
"NUMBER[]",
"JSON",
"my_numeric_domain",
] {
let mut result = bigint_result_sample();
result.column_types = vec![column_type.to_string()];
result.rows = vec![vec![serde_json::from_str(original).unwrap()]];
let serialized = serde_json::to_value(&result).unwrap();
assert!(serialized["rows"][0][0].is_number(), "{column_type}");
}
for column_types in [Vec::new(), vec!["NUMBER".to_string()]] {
let mut result = bigint_result_sample();
result.columns = vec!["AMOUNT".into(), "NOTE".into()];
result.column_types = column_types;
result.rows = vec![
vec![serde_json::from_str(original).unwrap(), serde_json::json!("text")],
vec![serde_json::Value::Null, serde_json::json!("unchanged")],
];
let serialized = serde_json::to_value(&result).unwrap();
let exact_cell_expected = if result.column_types.is_empty() {
serde_json::from_str::<serde_json::Value>(original).unwrap()
} else {
serde_json::json!(original)
};
assert_eq!(serialized["rows"][0][0], exact_cell_expected);
assert_eq!(serialized["rows"][0][1], "text");
assert_eq!(serialized["rows"][1][0], serde_json::Value::Null);
}
let mut result = bigint_result_sample();
result.column_types = vec!["NUMBER".to_string()];
result.rows = vec![vec![serde_json::json!(original)]];
assert_eq!(serde_json::to_value(result).unwrap()["rows"][0][0], original);
}
#[test]
fn query_result_uses_column_type_only_for_top_level_cells() {
let mut result = bigint_result_sample();
result.column_types = vec!["NUMBER".to_string()];
result.rows = vec![vec![serde_json::from_str(
r#"{"decimal":9007199254740993.123456789012,"id":2026081810175800100000000000}"#,
)
.unwrap()]];
let serialized = serde_json::to_value(&result).unwrap();
assert!(serialized["rows"][0][0]["decimal"].is_number());
assert_eq!(serialized["rows"][0][0]["id"], "2026081810175800100000000000");
}
#[test]
fn query_result_serialization_matches_js_normalization_for_nested_numbers() {
let cell: serde_json::Value = serde_json::from_str(
r#"{"ids":[2026081810175800100000000000,2026081810175800100000000001],"nested":{"id":-2026081810175800100000000000},"safe":42,"decimal":123.45,"exponent":1.25e-7,"null":null,"text":"2026081810175800100000000000"}"#,
)
.unwrap();
let mut result = bigint_result_sample();
result.rows = vec![vec![cell.clone()]];
let wire = serde_json::to_string(&result).unwrap();
let serialized: serde_json::Value = serde_json::from_str(&wire).unwrap();
let expected = crate::json::json_value_for_js(cell);
assert_eq!(serialized["rows"][0][0], expected);
assert_eq!(serialized["rows"][0][0]["ids"][0], "2026081810175800100000000000");
assert_eq!(serialized["rows"][0][0]["ids"][1], "2026081810175800100000000001");
assert_eq!(serialized["rows"][0][0]["nested"]["id"], "-2026081810175800100000000000");
}
#[test]
fn query_result_serialization_keeps_wire_shape_and_other_fields() {
let mut result = bigint_result_sample();
result.rows = vec![vec![serde_json::json!(7)]];
result.session_id = Some("session".to_string());
result.messages = vec![super::QueryMessage {
severity: "Note".to_string(),
message: "ok".to_string(),
code: None,
detail: None,
hint: None,
}];
let serialized = serde_json::to_value(&result).unwrap();
assert_eq!(
serialized,
serde_json::json!({
"columns": ["id"],
"column_types": ["bigint"],
"column_sortables": [],
"rows": [[7]],
"affected_rows": 0,
"execution_time_ms": 0,
"truncated": false,
"session_id": "session",
"has_more": false,
"messages": [{ "severity": "Note", "message": "ok" }],
})
);
// Optional collections stay omitted exactly like the previous derive.
let minimal = bigint_result_sample();
let serialized = serde_json::to_value(&minimal).unwrap();
assert!(serialized.get("spatial_columns").is_none());
assert!(serialized.get("spatial_values").is_none());
assert!(serialized.get("elasticsearch_raw_body").is_none());
assert!(serialized.get("messages").is_none());
assert_eq!(serialized["session_id"], serde_json::Value::Null);
}
#[test]
fn constraint_states_preserve_unknown_and_known_values_on_the_agent_ui_wire() {
for states in [
serde_json::json!({}),
serde_json::json!({ "enabled": null, "valid": null, "deferrable": null, "initially_deferred": null }),
serde_json::json!({ "enabled": true, "valid": false, "deferrable": false, "initially_deferred": true }),
] {
let mut payload = serde_json::json!({
"name": "O01_UK", "constraint_type": "UNIQUE",
"definition": "UNIQUE (\"B\", \"A\")", "columns": ["B", "A"]
});
payload.as_object_mut().unwrap().extend(states.as_object().unwrap().clone());
let constraint: super::ConstraintInfo = serde_json::from_value(payload).unwrap();
let wire = serde_json::to_value(constraint).unwrap();
for field in ["enabled", "valid", "deferrable", "initially_deferred"] {
assert_eq!(wire[field], states[field], "{field}");
}
assert_eq!(wire["columns"], serde_json::json!(["B", "A"]));
assert_eq!(wire["definition"], "UNIQUE (\"B\", \"A\")");
}
}
#[test]
fn query_result_server_execution_microseconds_survive_agent_and_ui_wire() {
let mut result = bigint_result_sample();
let without_audit = serde_json::to_value(&result).unwrap();
assert!(without_audit.get("server_execute_time_us").is_none());
assert_eq!(serde_json::from_value::<super::QueryResult>(without_audit).unwrap().server_execute_time_us, None);
result.server_execute_time_us = Some(370);
let audited = serde_json::to_value(&result).unwrap();
assert_eq!(audited["server_execute_time_us"], 370);
assert_eq!(serde_json::from_value::<super::QueryResult>(audited).unwrap().server_execute_time_us, Some(370));
}
/// Numeric cells nested inside JSON-typed columns must not lose precision
/// either, matching `db::json_value_for_js` recursion.
#[test]
fn query_result_stringifies_unsafe_integers_nested_in_json_cells() {
let mut result = bigint_result_sample();
result.rows = vec![vec![
serde_json::json!({ "snowflake": 1391198305898897409i64, "safe": 42, "text": "1391198305898897409" }),
]];
let serialized = serde_json::to_value(&result).unwrap();
assert_eq!(
serialized["rows"][0][0],
serde_json::json!({ "snowflake": "1391198305898897409", "safe": 42, "text": "1391198305898897409" })
);
}
/// The string form must round-trip: consumers deserialize `QueryResult`
/// from cached/relayed JSON, and cell values are untyped `Value`s.
#[test]
fn query_result_deserializes_stringified_integer_cells() {
let deserialized: super::QueryResult =
serde_json::from_value(serde_json::to_value(bigint_result_sample()).unwrap()).unwrap();
assert_eq!(deserialized.rows[0][0], serde_json::json!("1391198305898897409"));
}
/// Agent drivers may serialize empty native slices as JSON `null` (seen on
/// Vastbase `UPDATE ... FROM`, #11668). A present null must mean "empty",
/// not a contract violation.
#[test]
fn query_result_treats_null_vectors_from_agents_as_empty() {
let deserialized: super::QueryResult = serde_json::from_value(serde_json::json!({
"columns": null,
"column_types": null,
"column_sortables": null,
"spatial_columns": null,
"spatial_values": null,
"rows": null,
"affected_rows": 3,
"execution_time_ms": 7,
"messages": null
}))
.expect("null vectors should deserialize as empty");
assert!(deserialized.columns.is_empty());
assert!(deserialized.column_types.is_empty());
assert!(deserialized.column_sortables.is_empty());
assert!(deserialized.spatial_columns.is_empty());
assert!(deserialized.spatial_values.is_empty());
assert!(deserialized.rows.is_empty());
assert!(deserialized.messages.is_empty());
assert_eq!(deserialized.affected_rows, 3);
assert_eq!(deserialized.execution_time_ms, 7);
}
#[test]
fn query_result_still_deserializes_real_columns_and_rows() {
let deserialized: super::QueryResult = serde_json::from_value(serde_json::json!({
"columns": ["id", "name"],
"column_types": ["int4", "text"],
"column_sortables": [true, true],
"rows": [[1, "a"]],
"affected_rows": 1,
"execution_time_ms": 2
}))
.unwrap();
assert_eq!(deserialized.columns, ["id", "name"]);
assert_eq!(deserialized.rows.len(), 1);
assert_eq!(deserialized.rows[0][1], serde_json::json!("a"));
}
}