dbcli 0.1.0

Convert SQL query results to JSON without struct mapping, supporting MySQL/PostgreSQL/SQLite/Odbc
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! # to_json Module
//!
//! Provides the core logic for converting database rows into [`serde_json::Value`],
//! including the unified customization interface [`ToJsonCustomizer`], the global
//! registration function [`set_to_json_customizer`], and per-database driver submodules.

#[cfg(feature = "mysql")]
pub mod mysql;
#[cfg(feature = "postgres")]
pub mod postgres;
#[cfg(feature = "sqlite")]
pub mod sqlite;

#[cfg(feature = "odbc")]
pub mod odbc;


use base64::Engine;
use serde_json::Value as JsonValue;
use std::sync::OnceLock;

// ========================================
// ToJsonCustomizer trait (unified customization trait)
// ========================================

/// Unified customization trait for SQL → JSON type conversion.
///
/// Implement this trait and register it globally once via [`set_to_json_customizer`]
/// to override the default parsing logic for specific column types.
///
/// Three methods correspond to MySQL, PostgreSQL, and SQLite drivers respectively.
/// All have default implementations (returning `None`, meaning built-in behavior is used);
/// override only the methods you need.
///
/// # `type_name` Reference Table per Database
///
/// The value of the `type_name` parameter in each method is determined by the driver.
/// **All `type_name` values are uppercase strings.**
///
/// ## MySQL (uppercase strings)
///
/// | DB Type | `type_name` | Default Rust extraction type |
/// |---------|-------------|-----------------------------|
/// | VARCHAR / CHAR / TEXT series | `"VARCHAR"` / `"CHAR"` / `"TEXT"` etc. | `String` |
/// | INT / BIGINT / SMALLINT etc. | `"INT"` / `"BIGINT"` etc. | `i64` |
/// | FLOAT / DOUBLE / REAL | `"FLOAT"` / `"DOUBLE"` / `"REAL"` | `f64` |
/// | DATETIME | `"DATETIME"` | `NaiveDateTime` → `"%Y-%m-%d %H:%M:%S"` |
/// | DATE | `"DATE"` | `NaiveDate` → `"%Y-%m-%d"` |
/// | TIME | `"TIME"` | `NaiveDateTime` → `"%H:%M:%S"` |
/// | TIMESTAMP | `"TIMESTAMP"` | `i64` → `DateTime<Local>` |
/// | DECIMAL / NUMERIC | `"DECIMAL"` / `"NUMERIC"` | `Decimal` → String |
/// | BLOB / TINYBLOB | `"BLOB"` / `"TINYBLOB"` | Auto-detect: text → String, binary → Base64 |
/// | MEDIUMBLOB / LONGBLOB / BINARY | `"MEDIUMBLOB"` etc. | Base64 String |
/// | JSON | `"JSON"` | `serde_json::Value` |
/// | BOOLEAN / BOOL | `"BOOLEAN"` / `"BOOL"` | `bool` |
/// | ENUM / SET | `"ENUM"` / `"SET"` | `String` |
///
/// ## PostgreSQL (normalized to uppercase via `detect_pg_type`)
///
/// | Raw PG Type | `type_name` | Default Rust extraction type |
/// |-------------|-------------|-----------------------------|
/// | text / varchar / char / bpchar / citext | `"TEXT"` | `String` |
/// | int2 / int4 / int8 / smallint / bigint | `"INT"` | `i64` |
/// | float4 / float8 / real | `"FLOAT"` | `f64` (via `parse_float_value`) |
/// | numeric / decimal | `"NUMERIC"` | `Decimal` → String |
/// | bool / boolean | `"BOOL"` | `bool` |
/// | date | `"DATE"` | `NaiveDate` → `"%Y-%m-%d"` |
/// | timestamp / timestamp without time zone | `"TIMESTAMP"` | `NaiveDateTime` |
/// | timestamptz / timestamp with time zone | `"TIMESTAMPTZ"` | `DateTime<Utc>` → RFC3339 |
/// | time / timetz / time without time zone | `"TIME"` | `NaiveTime` → `"%H:%M:%S"` |
/// | jsonb / json | `"JSON"` | `serde_json::Value` |
/// | bytea | `"BYTEA"` | Auto-detect: text → String, binary → Base64 |
/// | uuid | `"UUID"` | `String` |
/// | array types | `"ARRAY"` | JSON Array |
/// | interval / money / inet / cidr / macaddr / xml | `"TEXT"` | `String` |
/// | vector / halfvec (pgvector) | `"VECTOR"` | JSON Array (f64 values) |
/// | sparsevec (pgvector) | `"SPARSEVEC"` | JSON Object {dimensions, indices, values} |
/// | bit / varbit | `"BIT"` | JSON String (binary string) |
/// | geometry / geography | `"GEOMETRY"` | `String` |
/// | hstore | `"HSTORE"` | `String` |
/// | other unrecognized types | `"TEXT"` | `String` |
///
/// ## SQLite (uppercase strings)
///
/// | SQLite Type | `type_name` | Default Rust extraction type |
/// |-------------|-------------|-----------------------------|
/// | TEXT / DATETIME / DATE / TIME | `"TEXT"` | `String` (auto-parses JSON if starts with `{`/`[`) |
/// | INTEGER / BOOLEAN | `"INTEGER"` | `i64` |
/// | REAL | `"REAL"` | `f64` |
/// | BLOB | `"BLOB"` | Base64 String |
/// | NUMERIC | `"NUMERIC"` | Auto-infer i64 / f64 / String |
/// | NULL | `"NULL"` | Dynamic inference |
///
/// # 示例
///
/// ```rust,no_run
/// use dbcli::to_json::{ToJsonCustomizer, set_to_json_customizer};
///
/// struct MyCustomizer;
///
/// impl ToJsonCustomizer for MyCustomizer {
///     #[cfg(feature = "mysql")]
///     fn customize_mysql(
///         &self,
///         type_name: &str,
///     ) -> Option<fn(&sqlx::mysql::MySqlRow, usize) -> serde_json::Value> {
///         match type_name {
///             // Format DATETIME as ISO 8601
///             "DATETIME" => Some(|row, idx| {
///                 use sqlx::Row;
///                 use chrono::NaiveDateTime;
///                 match row.try_get::<Option<NaiveDateTime>, _>(idx) {
///                     Ok(Some(dt)) => serde_json::Value::String(
///                         dt.format("%Y-%m-%dT%H:%M:%S").to_string()
///                     ),
///                     _ => serde_json::Value::Null,
///                 }
///             }),
///             // Format DATE with slash separator
///             "DATE" => Some(|row, idx| {
///                 use sqlx::Row;
///                 use chrono::NaiveDate;
///                 match row.try_get::<Option<NaiveDate>, _>(idx) {
///                     Ok(Some(d)) => serde_json::Value::String(
///                         d.format("%Y/%m/%d").to_string()
///                     ),
///                     _ => serde_json::Value::Null,
///                 }
///             }),
///             _ => None,
///         }
///     }
/// }
///
/// fn init() {
///     set_to_json_customizer(Box::new(MyCustomizer));
/// }
/// ```
pub trait ToJsonCustomizer: Send + Sync {
    /// Returns a custom parse function pointer for a MySQL column type.
    ///
    /// Called once per column in `determine_parsing_methods`.
    /// Return `Some(fn)` to override the default parsing, or `None` to use the built-in logic.
    ///
    /// `type_name` is an uppercase string; see the reference table in [`ToJsonCustomizer`].
    #[cfg(feature = "mysql")]
    fn customize_mysql(
        &self,
        type_name: &str,
    ) -> Option<fn(&sqlx::mysql::MySqlRow, usize) -> serde_json::Value> {
        let _ = type_name;
        None
    }

    /// Returns a custom parse function pointer for a PostgreSQL column type.
    ///
    /// Called once per column in `determine_parsing_methods`.
    /// Return `Some(fn)` to override the default parsing, or `None` to use the built-in logic.
    ///
    /// `type_name` is an uppercase string normalized by [`postgres::detect_pg_type`];
    /// see the reference table in [`ToJsonCustomizer`].
    #[cfg(feature = "postgres")]
    fn customize_pg(
        &self,
        type_name: &str,
    ) -> Option<fn(&sqlx::postgres::PgRow, usize) -> serde_json::Value> {
        let _ = type_name;
        None
    }

    /// Returns a custom parse function pointer for a SQLite column type.
    ///
    /// Called once per column in `determine_parsing_methods`.
    /// Return `Some(fn)` to override the default parsing, or `None` to use the built-in logic.
    ///
    /// `type_name` is an uppercase string; see the reference table in [`ToJsonCustomizer`].
    #[cfg(feature = "sqlite")]
    fn customize_sqlite(
        &self,
        type_name: &str,
    ) -> Option<fn(&sqlx::sqlite::SqliteRow, usize) -> serde_json::Value> {
        let _ = type_name;
        None
    }
}

/// Default implementation (all methods use built-in behavior).
pub struct DefaultToJsonCustomizer;
impl ToJsonCustomizer for DefaultToJsonCustomizer {}

static TO_JSON_CUSTOMIZER: OnceLock<Box<dyn ToJsonCustomizer>> = OnceLock::new();

/// Registers a global custom JSON converter.
///
/// Should be called **once** at application startup. Internally backed by [`OnceLock`];
/// subsequent calls are silently ignored (no panic, no overwrite).
///
/// If this function is never called, the library uses [`DefaultToJsonCustomizer`]
/// (all columns follow built-in default logic).
///
/// # Example
///
/// ```rust,no_run
/// use dbcli::to_json::{ToJsonCustomizer, set_to_json_customizer};
///
/// struct MyCustomizer;
/// impl ToJsonCustomizer for MyCustomizer {}
///
/// fn main() {
///     set_to_json_customizer(Box::new(MyCustomizer));
///     // All subsequent to_json calls will go through MyCustomizer
/// }
/// ```
pub fn set_to_json_customizer(customizer: Box<dyn ToJsonCustomizer>) {
    let _ = TO_JSON_CUSTOMIZER.set(customizer);
}

/// Returns the current customizer (internal use only).
pub(crate) fn get_customizer() -> &'static dyn ToJsonCustomizer {
    TO_JSON_CUSTOMIZER
        .get()
        .map(|b| b.as_ref())
        .unwrap_or({
            static DEFAULT: DefaultToJsonCustomizer = DefaultToJsonCustomizer;
            &DEFAULT
        })
}

/// Safely converts an `f64` value into a [`serde_json::Value`].
///
/// `serde_json` does not support NaN or Infinity; serializing them directly would panic.
/// This function converts these special values to JSON strings to ensure safe serialization:
///
/// | Input | JSON output |
/// |-------|-------------|
/// | Normal float | `Number(f)` |
/// | `f64::NAN` | `String("NaN")` |
/// | `f64::INFINITY` | `String("Infinity")` |
/// | `f64::NEG_INFINITY` | `String("-Infinity")` |
/// Parse a vector text representation into a JSON array of floating-point numbers.
///
/// Supports formats:
/// - `[0.1,0.2,0.3]` (pgvector / JSON-like)
/// - `{0.1,0.2,0.3}` (PostgreSQL array literal format)
/// - bare comma-separated values without brackets
pub(crate) fn parse_vector_string(s: &str) -> JsonValue {
    let trimmed = s.trim();
    // Remove surrounding brackets or braces
    let inner = if (trimmed.starts_with('[') && trimmed.ends_with(']'))
        || (trimmed.starts_with('{') && trimmed.ends_with('}'))
    {
        &trimmed[1..trimmed.len() - 1]
    } else {
        trimmed
    };

    if inner.is_empty() {
        return JsonValue::Array(vec![]);
    }

    let values: Vec<JsonValue> = inner
        .split(',')
        .map(|v| {
            let v = v.trim();
            if let Ok(f) = v.parse::<f64>() {
                f64_to_json_safe(f)
            } else {
                JsonValue::String(v.to_string())
            }
        })
        .collect();

    JsonValue::Array(values)
}

/// Parse binary vector data (packed f32 little-endian) into a JSON array of floating-point numbers.
///
/// Falls back to text parsing if the byte length is not a multiple of 4,
/// and finally falls back to Base64 encoding if the bytes are not valid UTF-8.
pub(crate) fn parse_vector_bytes(bytes: &[u8]) -> JsonValue {
    // Interpret as packed f32 array (little-endian) when length is a non-zero multiple of 4
    if bytes.len() % 4 == 0 && !bytes.is_empty() {
        let values: Vec<JsonValue> = bytes
            .chunks_exact(4)
            .map(|chunk| {
                let f = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
                f64_to_json_safe(f as f64)
            })
            .collect();
        return JsonValue::Array(values);
    }
    // Fallback: try as UTF-8 text
    if let Ok(s) = std::str::from_utf8(bytes) {
        return parse_vector_string(s);
    }
    // Last resort: Base64 encoding
    JsonValue::String(
        base64::engine::general_purpose::STANDARD.encode(bytes)
    )
}

pub fn f64_to_json_safe(f: f64) -> JsonValue {
    if f.is_nan() {
        JsonValue::String("NaN".to_string())
    } else if f.is_infinite() {
        if f.is_sign_positive() {
            JsonValue::String("Infinity".to_string())
        } else {
            JsonValue::String("-Infinity".to_string())
        }
    } else {
        serde_json::Number::from_f64(f)
            .map(JsonValue::Number)
            .unwrap_or(JsonValue::Null)
    }
}

/// Performs adaptive sampling on binary data to determine whether it is human-readable text.
///
/// Uses an adaptive sampling strategy:
/// - Sample at least 256 bytes, at most 8192 bytes
/// - In between, sample size is 1% of the total data length
///
/// If the proportion of non-printable characters (excluding ASCII visible and whitespace)
/// exceeds 20%, the data is considered binary and `false` is returned; otherwise `true`.
///
/// Primarily used for auto-detecting BLOB / BYTEA columns to decide between
/// outputting a UTF-8 string or a Base64-encoded string.
#[cfg(any(feature = "mysql", feature = "postgres"))]
pub fn blob_is_text(data: &[u8]) -> bool {
    const NON_TEXT_THRESHOLD: f32 = 0.2;
    const MIN_SAMPLE: usize = 256;
    const MAX_SAMPLE: usize = 8192;

    let total_len = data.len();
    if total_len == 0 {
        return false;
    }

    let sample_size = MIN_SAMPLE.max(total_len / 100).min(MAX_SAMPLE);
    let step = if total_len > sample_size {
        total_len / sample_size
    } else {
        1
    };

    let mut non_printables = 0usize;
    let mut checked_count = 0usize;

    for &byte in data.iter().step_by(step) {
        checked_count += 1;
        if !byte.is_ascii_graphic() && !byte.is_ascii_whitespace() {
            non_printables += 1;
        }
        let ratio = (non_printables as f32) / (checked_count as f32);
        if ratio >= NON_TEXT_THRESHOLD {
            return false;
        }
    }
    true
}

/// Generic row-to-JSON macro that eliminates duplicated `to_json` boilerplate across all three driver files.
///
/// # Usage
///
/// ```ignore
/// impl_to_json!(RowType, ParseStruct)
/// ```
///
/// Expands to a `to_json` function in the current module with the signature:
///
/// ```ignore
/// pub fn to_json(
///     results: Vec<RowType>,
/// ) -> anyhow::Result<(Vec<serde_json::Value>, Vec<crate::column_info::ColumnBaseInfo>)>
/// ```
///
/// The caller must define `determine_parsing_methods` in the same module.
///
/// > This macro is an internal implementation detail; direct use outside this crate is discouraged.
#[macro_export]
macro_rules! impl_to_json {
    ($row_type:ty, $parse_struct:ty) => {
        pub fn to_json(
            results: Vec<$row_type>,
        ) -> anyhow::Result<(Vec<serde_json::Value>, Vec<crate::column_info::ColumnBaseInfo>)> {
            use sqlx::{Column, Row};
            if results.is_empty() {
                return Ok((vec![], vec![]));
            }
            let first_row = &results[0];
            let parse = determine_parsing_methods(first_row)?;
            let methods = parse.methods;
            let columns = parse.columns;

            let mut data = Vec::with_capacity(results.len());
            for row in &results {
                let mut map =
                    serde_json::Map::with_capacity(columns.len());
                for col in row.columns() {
                    let col_index = col.ordinal();
                    let col_name = col.name().to_owned();
                    let value = methods[col_index](&row, col_index);
                    map.insert(col_name, value);
                }
                data.push(serde_json::Value::Object(map));
            }
            Ok((data, columns))
        }
    };
}

#[cfg(feature = "mysql")]
use sqlx::mysql::MySqlRow;
#[cfg(feature = "postgres")]
use sqlx::postgres::PgRow;
#[cfg(feature = "sqlite")]
use sqlx::sqlite::SqliteRow;

#[cfg(any(feature = "postgres", feature = "mysql", feature = "sqlite"))]
use crate::column_info::ColumnBaseInfo;

/// MySQL row parse result, containing per-column parse function pointers and column metadata.
#[cfg(feature = "mysql")]
pub struct MySqlRowParse {
    pub methods: Vec<fn(&MySqlRow, usize) -> JsonValue>,
    pub columns: Vec<ColumnBaseInfo>,
}

/// PostgreSQL row parse result, containing per-column parse function pointers and column metadata.
#[cfg(feature = "postgres")]
pub struct PgRowParse {
    pub methods: Vec<fn(&PgRow, usize) -> JsonValue>,
    pub columns: Vec<ColumnBaseInfo>,
}

/// SQLite row parse result, containing per-column parse function pointers and column metadata.
#[cfg(feature = "sqlite")]
pub struct SqliteRowParse {
    pub methods: Vec<fn(&SqliteRow, usize) -> JsonValue>,
    pub columns: Vec<ColumnBaseInfo>,
}