elefant-client 0.1.0

A pure rust implementation of a postgres client that is independent of the executor runtime
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
use crate::protocol::FieldDescription;
use crate::types::PostgresType;
use crate::types::{FromSqlBase, FromSqlBinary, FromSqlText, ToSql};
use serde_json::Value;
use std::error::Error;

/// Wrapper type for PostgreSQL JSON values
/// Use this when binding parameters to JSON columns specifically.
/// Note: `serde_json::Value` now defaults to JSONB format for best performance.
#[derive(Debug, Clone, PartialEq)]
pub struct Json(pub Value);

/// Wrapper type for PostgreSQL JSONB values  
/// Use this when you want to be explicit about JSONB format.
/// Note: `serde_json::Value` now defaults to JSONB format for best performance.
#[derive(Debug, Clone, PartialEq)]
pub struct Jsonb(pub Value);

// PostgreSQL JSON type - stored as text and parsed/serialized as JSON
impl<'a> FromSqlBase<'a> for Value {
    fn accepts_postgres_type(oid: i32) -> bool {
        oid == PostgresType::JSON.oid || oid == PostgresType::JSONB.oid
    }
}

impl<'a> FromSqlBinary<'a> for Value {
    fn from_sql_binary(
        raw: &'a [u8],
        field: &FieldDescription,
    ) -> Result<Self, Box<dyn Error + Sync + Send>> {
        if field.data_type_oid == PostgresType::JSONB.oid {
            // JSONB binary format: version byte (0x01) + UTF-8 JSON text
            if raw.is_empty() {
                return Err("JSONB data cannot be empty".into());
            }

            let version = raw[0];
            if version != 1 {
                return Err(format!("Unsupported JSONB version number: {version}").into());
            }

            let json_text = &raw[1..];
            serde_json::from_slice(json_text).map_err(|e| {
                format!(
                    "Failed to parse JSONB from binary data: {e}. Error occurred when parsing field {field:?}"
                )
                .into()
            })
        } else {
            // JSON in binary format is stored as UTF-8 text - parse directly from bytes
            serde_json::from_slice(raw).map_err(|e| {
                format!(
                    "Failed to parse JSON from binary data: {e}. Error occurred when parsing field {field:?}"
                )
                .into()
            })
        }
    }
}

impl<'a> FromSqlText<'a> for Value {
    fn from_sql_text(
        raw: &'a str,
        field: &FieldDescription,
    ) -> Result<Self, Box<dyn Error + Sync + Send>> {
        // Both JSON and JSONB text format is direct JSON string
        serde_json::from_str(raw).map_err(|e| {
            format!(
                "Failed to parse JSON/JSONB from text '{raw}': {e}. Error occurred when parsing field {field:?}"
            )
            .into()
        })
    }
}

// Default implementation uses JSONB format (recommended best practice)
impl ToSql for Value {
    fn to_sql_binary(
        &self,
        target_buffer: &mut Vec<u8>,
    ) -> Result<(), Box<dyn Error + Sync + Send>> {
        // Default to JSONB format (version byte + JSON text) as it's more efficient
        // Use explicit Json wrapper for JSON columns if needed
        target_buffer.push(1); // JSONB version byte
        serde_json::to_writer(target_buffer, self)
            .map_err(|e| format!("Failed to serialize JSON/JSONB to binary: {e}").into())
    }
}

// Specific implementation for JSON columns
impl ToSql for Json {
    fn to_sql_binary(
        &self,
        target_buffer: &mut Vec<u8>,
    ) -> Result<(), Box<dyn Error + Sync + Send>> {
        // JSON columns expect plain UTF-8 JSON text
        serde_json::to_writer(target_buffer, &self.0)
            .map_err(|e| format!("Failed to serialize JSON to binary: {e}").into())
    }
}

// Specific implementation for JSONB columns
impl ToSql for Jsonb {
    fn to_sql_binary(
        &self,
        target_buffer: &mut Vec<u8>,
    ) -> Result<(), Box<dyn Error + Sync + Send>> {
        // JSONB columns expect version byte (0x01) + UTF-8 JSON text
        target_buffer.push(1); // JSONB version byte
        serde_json::to_writer(target_buffer, &self.0)
            .map_err(|e| format!("Failed to serialize JSONB to binary: {e}").into())
    }
}

// FromSql implementations for wrapper types
impl<'a> FromSqlBase<'a> for Json {
    fn accepts_postgres_type(oid: i32) -> bool {
        oid == PostgresType::JSON.oid
    }
}

impl<'a> FromSqlBinary<'a> for Json {
    fn from_sql_binary(
        raw: &'a [u8],
        field: &FieldDescription,
    ) -> Result<Self, Box<dyn Error + Sync + Send>> {
        let value = Value::from_sql_binary(raw, field)?;
        Ok(Json(value))
    }
}

impl<'a> FromSqlText<'a> for Json {
    fn from_sql_text(
        raw: &'a str,
        field: &FieldDescription,
    ) -> Result<Self, Box<dyn Error + Sync + Send>> {
        let value = Value::from_sql_text(raw, field)?;
        Ok(Json(value))
    }
}

impl<'a> FromSqlBase<'a> for Jsonb {
    fn accepts_postgres_type(oid: i32) -> bool {
        oid == PostgresType::JSONB.oid
    }
}

impl<'a> FromSqlBinary<'a> for Jsonb {
    fn from_sql_binary(
        raw: &'a [u8],
        field: &FieldDescription,
    ) -> Result<Self, Box<dyn Error + Sync + Send>> {
        let value = Value::from_sql_binary(raw, field)?;
        Ok(Jsonb(value))
    }
}

impl<'a> FromSqlText<'a> for Jsonb {
    fn from_sql_text(
        raw: &'a str,
        field: &FieldDescription,
    ) -> Result<Self, Box<dyn Error + Sync + Send>> {
        let value = Value::from_sql_text(raw, field)?;
        Ok(Jsonb(value))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[cfg(feature = "tokio")]
    mod tokio_connection {
        use super::*;
        use crate::test_helpers::get_settings;
        use crate::tokio_connection::new_client;
        use tokio::test;

        #[test]
        async fn test_json_type() {
            let mut client = new_client(get_settings()).await.unwrap();

            // Test empty object
            let empty_object = json!({});
            let value: Value = client.read_single_value("select '{}'::json;", &[]).await;
            assert_eq!(value, empty_object);

            // Test empty array
            let empty_array = json!([]);
            let value: Value = client.read_single_value("select '[]'::json;", &[]).await;
            assert_eq!(value, empty_array);

            // Test complex JSON object
            let complex_json = json!({
                "name": "test",
                "age": 30,
                "active": true,
                "tags": ["rust", "postgresql"],
                "metadata": {
                    "created": "2024-01-15",
                    "version": 1
                }
            });
            let value: Value = client.read_single_value(
                r#"select '{"name":"test","age":30,"active":true,"tags":["rust","postgresql"],"metadata":{"created":"2024-01-15","version":1}}'::json;"#, 
                &[]
            ).await;
            assert_eq!(value, complex_json);

            // Test round-trip with parameter binding
            client.execute_non_query_simple("drop table if exists test_json_table; create table test_json_table(value json);").await.unwrap();
            let json_param = Json(complex_json.clone());
            client
                .execute_non_query("insert into test_json_table values ($1);", &[&json_param])
                .await
                .unwrap();
            let retrieved: Value = client
                .read_single_value("select value from test_json_table;", &[])
                .await;
            assert_eq!(retrieved, complex_json);

            // Test NULL handling
            let null_value: Option<Value> =
                client.read_single_value("select null::json;", &[]).await;
            assert_eq!(null_value, None);
        }

        #[test]
        async fn test_json_multiple_values() {
            let mut client = new_client(get_settings()).await.unwrap();

            // Test multiple different JSON types in a table for comprehensive testing
            client.execute_non_query_simple("drop table if exists test_json_multi; create table test_json_multi(id int, value json);").await.unwrap();

            // Insert various JSON types
            let test_values = vec![
                (1, json!({})),
                (2, json!([1, 2, 3])),
                (3, json!({"test": "value", "number": 42})),
                (4, json!(null)),
                (5, json!("simple string")),
                (6, json!(true)),
                (7, json!(123.456)),
            ];

            for (id, json_val) in &test_values {
                let json_param = Json(json_val.clone());
                client
                    .execute_non_query(
                        "insert into test_json_multi values ($1, $2);",
                        &[id, &json_param],
                    )
                    .await
                    .unwrap();
            }

            // Retrieve and verify each value
            for (expected_id, expected_json) in &test_values {
                let retrieved: Value = client
                    .read_single_value(
                        "select value from test_json_multi where id = $1;",
                        &[expected_id],
                    )
                    .await;
                assert_eq!(&retrieved, expected_json, "Failed for ID {expected_id}");
            }
        }

        #[test]
        async fn test_json_escaping_roundtrip() {
            let mut client = new_client(get_settings()).await.unwrap();

            // Test JSON values that require escaping at the JSON level
            client.execute_non_query_simple("drop table if exists test_json_escaping; create table test_json_escaping(id int, value json);").await.unwrap();

            let escaping_test_cases = vec![
                (1, json!({"quote": "He said \"hello\" to me"})),
                (2, json!({"backslash": "C:\\Users\\name\\file.txt"})),
                (3, json!({"newline": "line1\nline2\nline3"})),
                (4, json!({"tab": "col1\tcol2\tcol3"})),
                (5, json!({"unicode": "emoji: 😊 and math: ∑"})),
                (
                    6,
                    json!({"mixed": "Quote: \"text\", Path: C:\\temp\\file\nNext line"}),
                ),
                (
                    7,
                    json!({"nested_object": {"inner_quote": "nested \"value\" here"}}),
                ),
                (8, json!(["array", "with \"quotes\"", "and\nnewlines"])),
                (9, json!({"control_chars": "\u{0001}\u{0002}\u{0003}"})),
                (10, json!({"empty_and_quotes": "", "quotes": "\"\""})),
            ];

            // Insert all test cases using parameter binding (avoids SQL escaping)
            for (id, json_val) in &escaping_test_cases {
                let json_param = Json(json_val.clone());
                client
                    .execute_non_query(
                        "insert into test_json_escaping values ($1, $2);",
                        &[id, &json_param],
                    )
                    .await
                    .unwrap();
            }

            // Retrieve and verify each value maintains proper JSON escaping
            for (expected_id, expected_json) in &escaping_test_cases {
                let retrieved: Value = client
                    .read_single_value(
                        "select value from test_json_escaping where id = $1;",
                        &[expected_id],
                    )
                    .await;
                assert_eq!(
                    &retrieved, expected_json,
                    "JSON escaping failed for test case ID {expected_id}"
                );
            }

            // Additional test: Verify that the JSON is properly serialized/deserialized by checking a specific complex case
            let complex_case = json!({
                "message": "Error: \"file not found\" at C:\\temp\\data.json",
                "details": {
                    "path": "C:\\Users\\john\\Documents\\file with spaces.txt",
                    "error_code": 404,
                    "trace": "line1\nline2\nline3"
                },
                "tags": ["error", "\"critical\"", "needs\tescaping"]
            });

            let complex_json_param = Json(complex_case.clone());
            client
                .execute_non_query(
                    "insert into test_json_escaping values ($1, $2);",
                    &[&99, &complex_json_param],
                )
                .await
                .unwrap();
            let retrieved_complex: Value = client
                .read_single_value(
                    "select value from test_json_escaping where id = $1;",
                    &[&99],
                )
                .await;
            assert_eq!(
                retrieved_complex, complex_case,
                "Complex JSON escaping case failed"
            );
        }

        #[test]
        async fn test_json_error_handling() {
            let mut client = new_client(get_settings()).await.unwrap();

            // Test that PostgreSQL validates JSON syntax - invalid JSON should cause database error
            let result = client
                .try_read_single_value::<Value>("select '{invalid json'::json;", &[])
                .await;
            assert!(
                result.is_err(),
                "Expected PostgreSQL to reject invalid JSON syntax"
            );
        }

        #[test]
        async fn test_jsonb_type() {
            let mut client = new_client(get_settings()).await.unwrap();

            let empty_object = json!({});
            let value: Value = client
                .read_single_value_dual_mode("select '{}'::jsonb")
                .await;
            assert_eq!(value, empty_object);

            let empty_array = json!([]);
            let value: Value = client
                .read_single_value_dual_mode("select '[]'::jsonb")
                .await;
            assert_eq!(value, empty_array);

            let complex_jsonb = json!({
                "name": "test",
                "age": 30,
                "active": true,
                "tags": ["rust", "postgresql"],
                "metadata": {
                    "created": "2024-01-15",
                    "version": 1
                }
            });
            let value: Value = client.read_single_value_dual_mode(
                r#"select '{"name":"test","age":30,"active":true,"tags":["rust","postgresql"],"metadata":{"created":"2024-01-15","version":1}}'::jsonb"#
            ).await;
            assert_eq!(value, complex_jsonb);

            // Test round-trip with parameter binding
            client.execute_non_query_simple("drop table if exists test_jsonb_table; create table test_jsonb_table(value jsonb);").await.unwrap();
            let jsonb_param = Jsonb(complex_jsonb.clone());
            client
                .execute_non_query("insert into test_jsonb_table values ($1);", &[&jsonb_param])
                .await
                .unwrap();
            let retrieved: Value = client
                .read_single_value("select value from test_jsonb_table;", &[])
                .await;
            assert_eq!(retrieved, complex_jsonb);

            let null_value: Option<Value> = client
                .read_single_value_dual_mode("select null::jsonb")
                .await;
            assert_eq!(null_value, None);
        }

        #[test]
        async fn test_jsonb_vs_json_differences() {
            let mut client = new_client(get_settings()).await.unwrap();

            // Test that JSONB normalizes data (removes whitespace, reorders keys)
            client.execute_non_query_simple("drop table if exists test_jsonb_vs_json; create table test_jsonb_vs_json(id int, json_val json, jsonb_val jsonb);").await.unwrap();

            // Insert the same JSON with extra whitespace and different key order
            let json_with_spaces = r#"{ "z_last": 3 , "a_first":   1,  "middle": 2 }"#;
            let json_value: Value = serde_json::from_str(json_with_spaces).unwrap();

            // Use wrapper types for proper parameter binding
            let json_param = Json(json_value.clone());
            let jsonb_param = Jsonb(json_value.clone());

            client
                .execute_non_query(
                    "insert into test_jsonb_vs_json values (1, $1, $2);",
                    &[&json_param, &jsonb_param],
                )
                .await
                .unwrap();

            // Retrieve both values
            let json_val: Value = client
                .read_single_value("select json_val from test_jsonb_vs_json where id = 1;", &[])
                .await;
            let jsonb_val: Value = client
                .read_single_value(
                    "select jsonb_val from test_jsonb_vs_json where id = 1;",
                    &[],
                )
                .await;

            // Both should have the same logical content
            let expected = json!({"z_last": 3, "a_first": 1, "middle": 2});
            assert_eq!(json_val, expected);
            assert_eq!(jsonb_val, expected);
        }

        #[test]
        async fn test_jsonb_array_support() {
            let mut client = new_client(get_settings()).await.unwrap();

            // Test JSONB value that contains an array (not PostgreSQL array of JSONB)
            client.execute_non_query_simple("drop table if exists test_jsonb_arrays; create table test_jsonb_arrays(value jsonb);").await.unwrap();

            let json_array_value = json!([
                {"type": "user", "id": 1},
                {"type": "admin", "id": 2},
                [1, 2, 3],
                "simple string",
                null
            ]);

            let jsonb_param = Jsonb(json_array_value.clone());
            client
                .execute_non_query(
                    "insert into test_jsonb_arrays values ($1);",
                    &[&jsonb_param],
                )
                .await
                .unwrap();

            let retrieved_array: Value = client
                .read_single_value("select value from test_jsonb_arrays;", &[])
                .await;
            assert_eq!(retrieved_array, json_array_value);
        }

        #[test]
        async fn test_jsonb_error_handling() {
            let mut client = new_client(get_settings()).await.unwrap();

            // Test that PostgreSQL validates JSONB syntax - invalid JSON should cause database error
            let result = client
                .try_read_single_value_simple::<Value>("select '{invalid json'::jsonb;")
                .await;
            assert!(
                result.is_err(),
                "Expected PostgreSQL to reject invalid JSONB syntax"
            );
        }

        #[test]
        async fn test_jsonb_version_handling() {
            let mut client = new_client(get_settings()).await.unwrap();

            // Test JSONB with binary format version handling
            // This test verifies our implementation handles the version byte correctly
            client.execute_non_query_simple("drop table if exists test_jsonb_version; create table test_jsonb_version(value jsonb);").await.unwrap();

            let test_json = json!({"version_test": true, "data": [1, 2, 3]});
            let jsonb_param = Jsonb(test_json.clone());
            client
                .execute_non_query(
                    "insert into test_jsonb_version values ($1);",
                    &[&jsonb_param],
                )
                .await
                .unwrap();

            let retrieved: Value = client
                .read_single_value("select value from test_jsonb_version;", &[])
                .await;
            assert_eq!(retrieved, test_json);
        }

        #[test]
        async fn test_jsonb_parameter_binding_types() {
            let mut client = new_client(get_settings()).await.unwrap();

            // Test that parameter binding works correctly for both JSON and JSONB columns
            client.execute_non_query_simple("drop table if exists test_json_jsonb_params; create table test_json_jsonb_params(id int, json_col json, jsonb_col jsonb);").await.unwrap();

            let test_value = json!({
                "test": "parameter binding",
                "numbers": [1, 2, 3],
                "nested": {
                    "key": "value"
                }
            });

            // Use wrapper types for proper parameter binding
            let json_param = Json(test_value.clone());
            let jsonb_param = Jsonb(test_value.clone());

            client
                .execute_non_query(
                    "insert into test_json_jsonb_params values ($1, $2, $3);",
                    &[&1, &json_param, &jsonb_param],
                )
                .await
                .unwrap();

            // Retrieve both and verify they work correctly
            let json_result: Value = client
                .read_single_value(
                    "select json_col from test_json_jsonb_params where id = 1;",
                    &[],
                )
                .await;
            let jsonb_result: Value = client
                .read_single_value(
                    "select jsonb_col from test_json_jsonb_params where id = 1;",
                    &[],
                )
                .await;

            assert_eq!(json_result, test_value);
            assert_eq!(jsonb_result, test_value);
        }

        #[test]
        async fn test_jsonb_escaping_roundtrip() {
            let mut client = new_client(get_settings()).await.unwrap();

            // Test JSONB values that require escaping at the JSON level - same cases as JSON test
            client.execute_non_query_simple("drop table if exists test_jsonb_escaping; create table test_jsonb_escaping(id int, value jsonb);").await.unwrap();

            let escaping_test_cases = vec![
                (1, json!({"quote": "He said \"hello\" to me"})),
                (2, json!({"backslash": "C:\\Users\\name\\file.txt"})),
                (3, json!({"newline": "line1\nline2\nline3"})),
                (4, json!({"tab": "col1\tcol2\tcol3"})),
                (5, json!({"unicode": "emoji: 😊 and math: ∑"})),
                (
                    6,
                    json!({"mixed": "Quote: \"text\", Path: C:\\temp\\file\nNext line"}),
                ),
                (
                    7,
                    json!({"nested_object": {"inner_quote": "nested \"value\" here"}}),
                ),
                (8, json!(["array", "with \"quotes\"", "and\nnewlines"])),
                (9, json!({"control_chars": "\u{0001}\u{0002}\u{0003}"})),
                (10, json!({"empty_and_quotes": "", "quotes": "\"\""})),
            ];

            // Insert all test cases using parameter binding (avoids SQL escaping)
            for (id, json_val) in &escaping_test_cases {
                let jsonb_param = Jsonb(json_val.clone());
                client
                    .execute_non_query(
                        "insert into test_jsonb_escaping values ($1, $2);",
                        &[id, &jsonb_param],
                    )
                    .await
                    .unwrap();
            }

            // Retrieve and verify each value maintains proper JSON escaping
            for (expected_id, expected_json) in &escaping_test_cases {
                let retrieved: Value = client
                    .read_single_value(
                        "select value from test_jsonb_escaping where id = $1;",
                        &[expected_id],
                    )
                    .await;
                assert_eq!(
                    &retrieved, expected_json,
                    "JSONB escaping failed for test case ID {expected_id}"
                );
            }

            // Additional test: Verify that the JSONB is properly serialized/deserialized by checking a specific complex case
            let complex_case = json!({
                "message": "Error: \"file not found\" at C:\\temp\\data.json",
                "details": {
                    "path": "C:\\Users\\john\\Documents\\file with spaces.txt",
                    "error_code": 404,
                    "trace": "line1\nline2\nline3"
                },
                "tags": ["error", "\"critical\"", "needs\tescaping"]
            });

            let complex_jsonb_param = Jsonb(complex_case.clone());
            client
                .execute_non_query(
                    "insert into test_jsonb_escaping values ($1, $2);",
                    &[&99, &complex_jsonb_param],
                )
                .await
                .unwrap();
            let retrieved_complex: Value = client
                .read_single_value(
                    "select value from test_jsonb_escaping where id = $1;",
                    &[&99],
                )
                .await;
            assert_eq!(
                retrieved_complex, complex_case,
                "Complex JSONB escaping case failed"
            );
        }

        #[test]
        async fn test_default_value_behavior() {
            let mut client = new_client(get_settings()).await.unwrap();

            // Test that serde_json::Value now defaults to JSONB format
            client.execute_non_query_simple("drop table if exists test_default_behavior; create table test_default_behavior(id int, jsonb_col jsonb);").await.unwrap();

            let test_value = json!({
                "default_test": true,
                "message": "serde_json::Value should default to JSONB format",
                "data": [1, 2, 3]
            });

            // Use raw serde_json::Value - should work with JSONB columns now
            client
                .execute_non_query(
                    "insert into test_default_behavior values ($1, $2);",
                    &[&1, &test_value],
                )
                .await
                .unwrap();

            let retrieved: Value = client
                .read_single_value(
                    "select jsonb_col from test_default_behavior where id = 1;",
                    &[],
                )
                .await;
            assert_eq!(retrieved, test_value);
        }
    }
}