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.
use Engine;
use Value as JsonValue;
use 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));
/// }
/// ```
/// Default implementation (all methods use built-in behavior).
;
static TO_JSON_CUSTOMIZER: = 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
/// }
/// ```
/// Returns the current customizer (internal use only).
pub
/// 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
/// 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
/// 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.
/// 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.
use MySqlRow;
use PgRow;
use SqliteRow;
use crateColumnBaseInfo;
/// MySQL row parse result, containing per-column parse function pointers and column metadata.
/// PostgreSQL row parse result, containing per-column parse function pointers and column metadata.
/// SQLite row parse result, containing per-column parse function pointers and column metadata.