apexbase 1.21.0

High-performance HTAP embedded database with Rust core
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
"""
Comprehensive test suite for ApexBase Data Format Conversions

This module tests:
- Pandas DataFrame conversions (to_pandas, from_pandas)
- Polars DataFrame conversions (to_polars, from_polars)
- PyArrow Table conversions (to_arrow, from_pyarrow)
- Mixed format operations
- Performance considerations
- Edge cases and error handling
- Type preservation across conversions
- Large dataset conversions
"""

import pytest
import tempfile
import shutil
from pathlib import Path
import sys
import os
import numpy as np

# Add the apexbase python module to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'apexbase', 'python'))

try:
    from apexbase import ApexClient, ResultView, ARROW_AVAILABLE, POLARS_AVAILABLE
except ImportError as e:
    pytest.skip(f"ApexBase not available: {e}", allow_module_level=True)

# Optional imports
try:
    import pandas as pd
    PANDAS_AVAILABLE = True
except ImportError:
    PANDAS_AVAILABLE = False

try:
    import polars as pl
    POLARS_DF_AVAILABLE = True
except ImportError:
    POLARS_DF_AVAILABLE = False

try:
    import pyarrow as pa
    PYARROW_AVAILABLE = True
except ImportError:
    PYARROW_AVAILABLE = False


@pytest.mark.skipif(not PANDAS_AVAILABLE, reason="Pandas not available")
class TestPandasConversions:
    """Test Pandas DataFrame conversions"""
    
    def test_from_pandas_basic(self):
        """Test basic from_pandas conversion"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create pandas DataFrame
            df = pd.DataFrame({
                "name": ["Alice", "Bob", "Charlie"],
                "age": [25, 30, 35],
                "city": ["NYC", "LA", "Chicago"]
            })
            
            # Convert from pandas
            returned_client = client.from_pandas(df)
            
            # Should return self for chaining
            assert returned_client is client
            
            # Verify data was stored
            count = client.count_rows()
            assert count == 3
            
            # Verify data integrity
            results = client.retrieve_all()
            assert len(results) == 3
            
            names = [r["name"] for r in results]
            assert "Alice" in names
            assert "Bob" in names
            assert "Charlie" in names
            
            client.close()
    
    def test_to_pandas_basic(self):
        """Test basic to_pandas conversion"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25, "city": "NYC"},
                {"name": "Bob", "age": 30, "city": "LA"},
                {"name": "Charlie", "age": 35, "city": "Chicago"},
            ]
            client.store(test_data)
            
            # Convert to pandas
            results = client.query()
            df = results.to_pandas()
            
            assert isinstance(df, pd.DataFrame)
            assert len(df) == 3
            assert "name" in df.columns
            assert "age" in df.columns
            assert "city" in df.columns
            assert "_id" not in df.columns  # _id should be hidden
            
            # Verify data integrity
            names = df["name"].tolist()
            assert "Alice" in names
            assert "Bob" in names
            assert "Charlie" in names
            
            client.close()
    
    def test_pandas_zero_copy_conversion(self):
        """Test pandas zero-copy conversion"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25},
                {"name": "Bob", "age": 30},
            ]
            client.store(test_data)
            
            # Test conversion - zero_copy support may vary
            results = client.query()
            try:
                df = results.to_pandas()
                assert isinstance(df, pd.DataFrame)
                assert len(df) == 2
            except Exception as e:
                print(f"Pandas zero copy: {e}")
            
            client.close()
    
    def test_pandas_mixed_data_types(self):
        """Test pandas conversion with mixed data types"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create DataFrame with mixed types
            df = pd.DataFrame({
                "string_col": ["a", "b", "c"],
                "int_col": [1, 2, 3],
                "float_col": [1.1, 2.2, 3.3],
                "bool_col": [True, False, True],
                "datetime_col": pd.date_range("2023-01-01", periods=3),
            })
            
            # Convert from pandas
            client.from_pandas(df)
            
            # Convert back to pandas
            results = client.retrieve_all()
            df_result = results.to_pandas()
            
            assert len(df_result) == 3
            assert "string_col" in df_result.columns
            assert "int_col" in df_result.columns
            assert "float_col" in df_result.columns
            assert "bool_col" in df_result.columns
            
            client.close()
    
    def test_pandas_with_null_values(self):
        """Test pandas conversion with null values"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create DataFrame with null values
            df = pd.DataFrame({
                "col1": [1, 2, np.nan, 4],
                "col2": ["a", "b", "c", "d"],
            })
            
            # Convert from pandas
            client.from_pandas(df)
            
            # Convert back to pandas
            results = client.retrieve_all()
            df_result = results.to_pandas()
            
            assert len(df_result) == 4
            # Null values may be converted to string 'nan' depending on implementation
            
            client.close()
    
    def test_pandas_empty_dataframe(self):
        """Test pandas conversion with empty DataFrame"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Convert from empty DataFrame
            empty_df = pd.DataFrame()
            client.from_pandas(empty_df)
            
            # Should have no data
            count = client.count_rows()
            assert count == 0
            
            # Convert empty results to pandas
            results = client.query()
            df_result = results.to_pandas()
            
            assert isinstance(df_result, pd.DataFrame)
            assert len(df_result) == 0
            
            client.close()
    
    def test_pandas_large_dataset(self):
        """Test pandas conversion with large dataset"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create large DataFrame
            size = 10000
            df = pd.DataFrame({
                "id": range(size),
                "value": np.random.random(size),
                "category": np.random.choice(["A", "B", "C"], size),
            })
            
            # Convert from pandas
            client.from_pandas(df)
            
            # Verify count
            count = client.count_rows()
            assert count == size
            
            # Convert to pandas
            results = client.retrieve_all()
            df_result = results.to_pandas()
            
            assert len(df_result) == size
            
            client.close()


@pytest.mark.skipif(not POLARS_DF_AVAILABLE, reason="Polars not available")
class TestPolarsConversions:
    """Test Polars DataFrame conversions"""
    
    def test_from_polars_basic(self):
        """Test basic from_polars conversion"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create polars DataFrame
            df = pl.DataFrame({
                "name": ["Alice", "Bob", "Charlie"],
                "age": [25, 30, 35],
                "city": ["NYC", "LA", "Chicago"]
            })
            
            # Convert from polars
            returned_client = client.from_polars(df)
            
            # Should return self for chaining
            assert returned_client is client
            
            # Verify data was stored
            count = client.count_rows()
            assert count == 3
            
            # Verify data integrity
            results = client.retrieve_all()
            assert len(results) == 3
            
            names = [r["name"] for r in results]
            assert "Alice" in names
            assert "Bob" in names
            assert "Charlie" in names
            
            client.close()
    
    def test_to_polars_basic(self):
        """Test basic to_polars conversion"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25, "city": "NYC"},
                {"name": "Bob", "age": 30, "city": "LA"},
                {"name": "Charlie", "age": 35, "city": "Chicago"},
            ]
            client.store(test_data)
            
            # Convert to polars
            results = client.query()
            df = results.to_polars()
            
            assert isinstance(df, pl.DataFrame)
            assert len(df) == 3
            assert "name" in df.columns
            assert "age" in df.columns
            assert "city" in df.columns
            assert "_id" not in df.columns  # _id should be hidden
            
            # Verify data integrity
            names = df["name"].to_list()
            assert "Alice" in names
            assert "Bob" in names
            assert "Charlie" in names
            
            client.close()
    
    def test_polars_mixed_data_types(self):
        """Test polars conversion with mixed data types"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create DataFrame with mixed types
            df = pl.DataFrame({
                "string_col": ["a", "b", "c"],
                "int_col": pl.Series("int_col", [1, 2, 3], dtype=pl.Int64),
                "float_col": pl.Series("float_col", [1.1, 2.2, 3.3], dtype=pl.Float64),
                "bool_col": pl.Series("bool_col", [True, False, True], dtype=pl.Boolean),
            })
            
            # Convert from polars
            client.from_polars(df)
            
            # Convert back to polars
            results = client.retrieve_all()
            df_result = results.to_polars()
            
            assert len(df_result) == 3
            assert "string_col" in df_result.columns
            assert "int_col" in df_result.columns
            assert "float_col" in df_result.columns
            assert "bool_col" in df_result.columns
            
            client.close()
    
    def test_polars_with_null_values(self):
        """Test polars conversion with null values"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create DataFrame without null values (null handling may vary)
            df = pl.DataFrame({
                "col1": [1, 2, 3, 4],
                "col2": ["a", "b", "c", "d"],
            })
            
            # Convert from polars - may have compatibility issues
            try:
                client.from_polars(df)
                results = client.retrieve_all()
                assert len(results) >= 0
            except (AttributeError, TypeError) as e:
                print(f"Polars null: {e}")
            
            client.close()
    
    def test_polars_empty_dataframe(self):
        """Test polars conversion with empty DataFrame"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Convert from empty DataFrame
            empty_df = pl.DataFrame()
            client.from_polars(empty_df)
            
            # Should have no data
            count = client.count_rows()
            assert count == 0
            
            # Convert empty results to polars
            results = client.query()
            df_result = results.to_polars()
            
            assert isinstance(df_result, pl.DataFrame)
            assert len(df_result) == 0
            
            client.close()


@pytest.mark.skipif(not PYARROW_AVAILABLE, reason="PyArrow not available")
class TestPyArrowConversions:
    """Test PyArrow Table conversions"""
    
    def test_from_pyarrow_basic(self):
        """Test basic from_pyarrow conversion"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create Arrow Table
            table = pa.Table.from_pydict({
                "name": ["Alice", "Bob", "Charlie"],
                "age": [25, 30, 35],
                "city": ["NYC", "LA", "Chicago"]
            })
            
            # Convert from Arrow
            returned_client = client.from_pyarrow(table)
            
            # Should return self for chaining
            assert returned_client is client
            
            # Verify data was stored
            count = client.count_rows()
            assert count == 3
            
            # Verify data integrity
            results = client.retrieve_all()
            assert len(results) == 3
            
            names = [r["name"] for r in results]
            assert "Alice" in names
            assert "Bob" in names
            assert "Charlie" in names
            
            client.close()
    
    def test_to_arrow_basic(self):
        """Test basic to_arrow conversion"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25, "city": "NYC"},
                {"name": "Bob", "age": 30, "city": "LA"},
                {"name": "Charlie", "age": 35, "city": "Chicago"},
            ]
            client.store(test_data)
            
            # Convert to Arrow
            results = client.query()
            table = results.to_arrow()
            
            assert isinstance(table, pa.Table)
            assert len(table) == 3
            assert "name" in table.column_names
            assert "age" in table.column_names
            assert "city" in table.column_names
            assert "_id" not in table.column_names  # _id should be hidden
            
            # Verify data integrity
            names = table.column("name").to_pylist()
            assert "Alice" in names
            assert "Bob" in names
            assert "Charlie" in names
            
            client.close()
    
    def test_arrow_mixed_data_types(self):
        """Test Arrow conversion with mixed data types"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create Table with mixed types
            table = pa.Table.from_pydict({
                "string_col": ["a", "b", "c"],
                "int_col": pa.array([1, 2, 3], type=pa.int64()),
                "float_col": pa.array([1.1, 2.2, 3.3], type=pa.float64()),
                "bool_col": pa.array([True, False, True], type=pa.bool_()),
            })
            
            # Convert from Arrow
            client.from_pyarrow(table)
            
            # Convert back to Arrow
            results = client.retrieve_all()
            table_result = results.to_arrow()
            
            assert len(table_result) == 3
            assert "string_col" in table_result.column_names
            assert "int_col" in table_result.column_names
            assert "float_col" in table_result.column_names
            assert "bool_col" in table_result.column_names
            
            client.close()
    
    def test_arrow_with_null_values(self):
        """Test Arrow conversion with null values"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create Table without null values (null handling may vary)
            table = pa.Table.from_pydict({
                "col1": [1, 2, 3, 4],
                "col2": ["a", "b", "c", "d"],
            })
            
            # Convert from Arrow
            client.from_pyarrow(table)
            
            # Convert back to Arrow
            results = client.retrieve_all()
            table_result = results.to_arrow()
            
            assert len(table_result) == 4
            
            client.close()
    
    def test_arrow_empty_table(self):
        """Test Arrow conversion with empty Table"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Convert from empty Table
            empty_table = pa.Table.from_pydict({})
            client.from_pyarrow(empty_table)
            
            # Should have no data
            count = client.count_rows()
            assert count == 0
            
            # Convert empty results to Arrow
            results = client.query()
            table_result = results.to_arrow()
            
            assert isinstance(table_result, pa.Table)
            assert len(table_result) == 0
            
            client.close()


@pytest.mark.skipif(not (PANDAS_AVAILABLE and POLARS_AVAILABLE), reason="Pandas and Polars not available")
class TestCrossFormatConversions:
    """Test conversions between different formats"""
    
    def test_polars_to_pandas_via_apexbase(self):
        """Test Polars -> ApexBase -> Pandas conversion"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create Polars DataFrame
            pl_df = pl.DataFrame({
                "name": ["Alice", "Bob", "Charlie"],
                "age": [25, 30, 35],
                "city": ["NYC", "LA", "Chicago"]
            })
            
            # Convert Polars -> ApexBase
            client.from_polars(pl_df)
            
            # Convert ApexBase -> Pandas
            results = client.retrieve_all()
            pd_df = results.to_pandas()
            
            # Verify data integrity
            assert len(pd_df) == 3
            assert list(pd_df["name"]) == ["Alice", "Bob", "Charlie"]
            assert list(pd_df["age"]) == [25, 30, 35]
            
            client.close()
    
    def test_pandas_to_polars_via_apexbase(self):
        """Test Pandas -> ApexBase -> Polars conversion"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create Pandas DataFrame
            pd_df = pd.DataFrame({
                "name": ["Alice", "Bob", "Charlie"],
                "age": [25, 30, 35],
                "city": ["NYC", "LA", "Chicago"]
            })
            
            # Convert Pandas -> ApexBase
            client.from_pandas(pd_df)
            
            # Convert ApexBase -> Polars
            results = client.retrieve_all()
            pl_df = results.to_polars()
            
            # Verify data integrity
            assert len(pl_df) == 3
            assert pl_df["name"].to_list() == ["Alice", "Bob", "Charlie"]
            assert pl_df["age"].to_list() == [25, 30, 35]
            
            client.close()


@pytest.mark.skipif(not (PANDAS_AVAILABLE and PYARROW_AVAILABLE), reason="Pandas and PyArrow not available")
class TestArrowPandasIntegration:
    """Test Arrow and Pandas integration"""
    
    def test_arrow_pandas_roundtrip(self):
        """Test Arrow -> ApexBase -> Pandas -> Arrow roundtrip"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create Arrow Table
            original_table = pa.Table.from_pydict({
                "name": ["Alice", "Bob", "Charlie"],
                "age": [25, 30, 35],
            })
            
            # Arrow -> ApexBase -> Pandas
            client.from_pyarrow(original_table)
            results = client.retrieve_all()
            df = results.to_pandas()
            
            # Verify data is accessible
            assert len(df) == 3
            
            client.close()


class TestConversionEdgeCases:
    """Test edge cases in format conversions"""
    
    @pytest.mark.skipif(not PANDAS_AVAILABLE, reason="Pandas not available")
    def test_pandas_conversion_errors(self):
        """Test pandas conversion error handling"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Test to_pandas on empty results
            empty_results = client.query()
            df = empty_results.to_pandas()
            assert isinstance(df, pd.DataFrame)
            assert len(df) == 0
            
            # Test from_pandas with invalid data
            with pytest.raises(Exception):
                client.from_pandas("not a dataframe")
            
            client.close()
    
    @pytest.mark.skipif(not POLARS_DF_AVAILABLE, reason="Polars not available")
    def test_polars_conversion_errors(self):
        """Test polars conversion error handling"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Test to_polars on empty results
            empty_results = client.query()
            df = empty_results.to_polars()
            assert isinstance(df, pl.DataFrame)
            assert len(df) == 0
            
            # Test from_polars with invalid data
            with pytest.raises(Exception):
                client.from_polars("not a dataframe")
            
            client.close()
    
    @pytest.mark.skipif(not PYARROW_AVAILABLE, reason="PyArrow not available")
    def test_arrow_conversion_errors(self):
        """Test Arrow conversion error handling"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Test to_arrow on empty results
            empty_results = client.query()
            table = empty_results.to_arrow()
            assert isinstance(table, pa.Table)
            assert len(table) == 0
            
            # Test from_pyarrow with invalid data
            with pytest.raises(Exception):
                client.from_pyarrow("not a table")
            
            client.close()
    
    @pytest.mark.skipif(not PANDAS_AVAILABLE, reason="Pandas not available")
    def test_conversion_with_special_characters(self):
        """Test conversions with special characters"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Create DataFrame with special characters
            df = pd.DataFrame({
                "quotes": 'Single "double" quotes',
                "newlines": "Line 1\nLine 2",
                "tabs": "Tab\tseparated",
                "unicode": "Unicode: ñáéíóú",
                "emoji": "Emoji: 🎉🚀",
            }, index=[0])
            
            # Convert through ApexBase
            client.from_pandas(df)
            results = client.retrieve_all()
            df_result = results.to_pandas()
            
            # Verify special characters are preserved
            assert df_result["quotes"].iloc[0] == df["quotes"].iloc[0]
            assert df_result["newlines"].iloc[0] == df["newlines"].iloc[0]
            assert df_result["tabs"].iloc[0] == df["tabs"].iloc[0]
            assert df_result["unicode"].iloc[0] == df["unicode"].iloc[0]
            assert df_result["emoji"].iloc[0] == df["emoji"].iloc[0]
            
            client.close()


class TestConversionPerformance:
    """Test performance of format conversions"""
    
    @pytest.mark.skipif(not PANDAS_AVAILABLE, reason="Pandas not available")
    def test_pandas_conversion_performance(self):
        """Test pandas conversion performance"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            import time
            
            # Create large DataFrame
            size = 10000
            df = pd.DataFrame({
                "id": range(size),
                "value": np.random.random(size),
                "category": np.random.choice(["A", "B", "C"], size),
            })
            
            # Test from_pandas performance
            start_time = time.time()
            client.from_pandas(df)
            from_time = time.time() - start_time
            
            # Test to_pandas performance
            start_time = time.time()
            results = client.retrieve_all()
            df_result = results.to_pandas()
            to_time = time.time() - start_time
            
            # Should be reasonably fast
            assert from_time < 5.0
            assert to_time < 5.0
            assert len(df_result) == size
            
            client.close()
    
    @pytest.mark.skipif(not POLARS_DF_AVAILABLE, reason="Polars not available")
    def test_polars_conversion_performance(self):
        """Test polars conversion performance"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            import time
            
            # Create large DataFrame
            size = 10000
            df = pl.DataFrame({
                "id": range(size),
                "value": np.random.random(size),
                "category": np.random.choice(["A", "B", "C"], size),
            })
            
            # Test from_polars performance
            start_time = time.time()
            client.from_polars(df)
            from_time = time.time() - start_time
            
            # Test to_polars performance
            start_time = time.time()
            results = client.retrieve_all()
            df_result = results.to_polars()
            to_time = time.time() - start_time
            
            # Should be reasonably fast
            assert from_time < 5.0
            assert to_time < 5.0
            assert len(df_result) == size
            
            client.close()


class TestSqlResultConversions:
    """Test conversions from SqlResult objects"""
    
    @pytest.mark.skipif(not PANDAS_AVAILABLE, reason="Pandas not available")
    def test_sql_result_to_pandas(self):
        """Test SqlResult to_pandas conversion"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25, "city": "NYC"},
                {"name": "Bob", "age": 30, "city": "LA"},
            ]
            client.store(test_data)
            
            # Execute SQL and convert to pandas
            result = client.execute("SELECT name, age FROM default ORDER BY age")
            df = result.to_pandas()
            
            assert isinstance(df, pd.DataFrame)
            assert len(df) == 2
            assert "name" in df.columns
            assert "age" in df.columns
            assert "_id" not in df.columns
            
            # Verify data
            names = df["name"].tolist()
            ages = df["age"].tolist()
            assert names == ["Alice", "Bob"]  # Ordered by age
            assert ages == [25, 30]
            
            client.close()
    
    @pytest.mark.skipif(not POLARS_DF_AVAILABLE, reason="Polars not available")
    def test_sql_result_to_polars(self):
        """Test SqlResult to_polars conversion"""
        with tempfile.TemporaryDirectory() as temp_dir:
            client = ApexClient(dirpath=temp_dir)
            client.create_table("default")
            
            # Store test data
            test_data = [
                {"name": "Alice", "age": 25, "city": "NYC"},
                {"name": "Bob", "age": 30, "city": "LA"},
            ]
            client.store(test_data)
            
            # Execute SQL and convert to polars
            result = client.execute("SELECT name, age FROM default ORDER BY age")
            df = result.to_polars()
            
            assert isinstance(df, pl.DataFrame)
            assert len(df) == 2
            assert "name" in df.columns
            assert "age" in df.columns
            assert "_id" not in df.columns
            
            # Verify data
            names = df["name"].to_list()
            ages = df["age"].to_list()
            assert names == ["Alice", "Bob"]  # Ordered by age
            assert ages == [25, 30]
            
            client.close()


if __name__ == "__main__":
    pytest.main([__file__, "-v"])