mockforge-plugin-core 0.3.116

Core plugin interfaces and types for MockForge extensible architecture
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
//! Data source plugin interface
//!
//! This module defines the DataSourcePlugin trait and related types for implementing
//! external data source integrations in MockForge. Data source plugins enable
//! connecting to databases, APIs, files, and other data sources for enhanced mocking.

use crate::{PluginCapabilities, PluginContext, PluginResult, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

/// Data source plugin trait
///
/// Implement this trait to create custom data source integrations.
/// Data source plugins enable MockForge to connect to external data sources
/// like databases, REST APIs, files, and other systems for dynamic mocking.
#[async_trait::async_trait]
pub trait DataSourcePlugin: Send + Sync {
    /// Get plugin capabilities (permissions and limits)
    fn capabilities(&self) -> PluginCapabilities;

    /// Initialize the plugin with configuration
    async fn initialize(&self, config: &DataSourcePluginConfig) -> Result<()>;

    /// Connect to the data source
    ///
    /// This method establishes a connection to the data source using
    /// the provided configuration.
    ///
    /// # Arguments
    /// * `context` - Plugin execution context
    /// * `config` - Data source configuration
    ///
    /// # Returns
    /// Connection handle
    async fn connect(
        &self,
        context: &PluginContext,
        config: &DataSourcePluginConfig,
    ) -> Result<PluginResult<DataConnection>>;

    /// Execute a query against the data source
    ///
    /// This method executes a query using the provided connection.
    ///
    /// # Arguments
    /// * `context` - Plugin execution context
    /// * `connection` - Active connection
    /// * `query` - Query to execute
    /// * `config` - Data source configuration
    ///
    /// # Returns
    /// Query results
    async fn query(
        &self,
        context: &PluginContext,
        connection: &DataConnection,
        query: &DataQuery,
        config: &DataSourcePluginConfig,
    ) -> Result<PluginResult<DataResult>>;

    /// Get data source schema information
    ///
    /// This method retrieves schema information about the data source,
    /// such as available tables, columns, and relationships.
    ///
    /// # Arguments
    /// * `context` - Plugin execution context
    /// * `connection` - Active connection
    /// * `config` - Data source configuration
    ///
    /// # Returns
    /// Schema information
    async fn get_schema(
        &self,
        context: &PluginContext,
        connection: &DataConnection,
        config: &DataSourcePluginConfig,
    ) -> Result<PluginResult<Schema>>;

    /// Test the data source connection
    ///
    /// This method tests whether the data source is accessible and
    /// the configuration is correct.
    ///
    /// # Arguments
    /// * `context` - Plugin execution context
    /// * `config` - Data source configuration
    ///
    /// # Returns
    /// Connection test result
    async fn test_connection(
        &self,
        context: &PluginContext,
        config: &DataSourcePluginConfig,
    ) -> Result<PluginResult<ConnectionTestResult>>;

    /// Validate plugin configuration
    fn validate_config(&self, config: &DataSourcePluginConfig) -> Result<()>;

    /// Get supported data source types
    fn supported_types(&self) -> Vec<String>;

    /// Cleanup plugin resources
    async fn cleanup(&self) -> Result<()>;
}

/// Data source plugin configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataSourcePluginConfig {
    /// Plugin-specific configuration
    pub config: HashMap<String, Value>,
    /// Enable/disable the plugin
    pub enabled: bool,
    /// Data source type (e.g., "postgresql", "mysql", "api", "file")
    pub data_source_type: String,
    /// Connection string or endpoint URL
    pub connection_string: Option<String>,
    /// Connection timeout in seconds
    pub connection_timeout_secs: u64,
    /// Query timeout in seconds
    pub query_timeout_secs: u64,
    /// Maximum connections
    pub max_connections: u32,
    /// Authentication credentials
    pub credentials: Option<DataSourceCredentials>,
    /// SSL/TLS configuration
    pub ssl_config: Option<SslConfig>,
    /// Custom settings
    pub settings: HashMap<String, Value>,
}

impl Default for DataSourcePluginConfig {
    fn default() -> Self {
        Self {
            config: HashMap::new(),
            enabled: true,
            data_source_type: "unknown".to_string(),
            connection_string: None,
            connection_timeout_secs: 30,
            query_timeout_secs: 30,
            max_connections: 10,
            credentials: None,
            ssl_config: None,
            settings: HashMap::new(),
        }
    }
}

/// Data source credentials
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataSourceCredentials {
    /// Username
    pub username: Option<String>,
    /// Password
    pub password: Option<String>,
    /// API key
    pub api_key: Option<String>,
    /// Bearer token
    pub bearer_token: Option<String>,
    /// Custom authentication fields
    pub custom: HashMap<String, String>,
}

impl DataSourceCredentials {
    /// Create with username/password
    pub fn user_pass<S: Into<String>>(username: S, password: S) -> Self {
        Self {
            username: Some(username.into()),
            password: Some(password.into()),
            api_key: None,
            bearer_token: None,
            custom: HashMap::new(),
        }
    }

    /// Create with API key
    pub fn api_key<S: Into<String>>(api_key: S) -> Self {
        Self {
            username: None,
            password: None,
            api_key: Some(api_key.into()),
            bearer_token: None,
            custom: HashMap::new(),
        }
    }

    /// Create with bearer token
    pub fn bearer_token<S: Into<String>>(token: S) -> Self {
        Self {
            username: None,
            password: None,
            api_key: None,
            bearer_token: Some(token.into()),
            custom: HashMap::new(),
        }
    }
}

/// SSL/TLS configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SslConfig {
    /// Enable SSL/TLS
    pub enabled: bool,
    /// CA certificate path
    pub ca_cert_path: Option<String>,
    /// Client certificate path
    pub client_cert_path: Option<String>,
    /// Client key path
    pub client_key_path: Option<String>,
    /// Skip certificate verification (for development)
    pub skip_verify: bool,
    /// Custom SSL settings
    pub custom: HashMap<String, Value>,
}

/// Data connection handle
#[derive(Debug, Clone)]
pub struct DataConnection {
    /// Connection ID
    pub id: String,
    /// Connection type
    pub connection_type: String,
    /// Connection metadata
    pub metadata: HashMap<String, Value>,
    /// Connection creation time
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// Last used time
    pub last_used: chrono::DateTime<chrono::Utc>,
    /// Internal connection handle (plugin-specific)
    pub handle: Value,
}

impl DataConnection {
    /// Create a new connection
    pub fn new<S: Into<String>>(connection_type: S, handle: Value) -> Self {
        let now = chrono::Utc::now();
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            connection_type: connection_type.into(),
            metadata: HashMap::new(),
            created_at: now,
            last_used: now,
            handle,
        }
    }

    /// Update last used timestamp
    pub fn mark_used(&mut self) {
        self.last_used = chrono::Utc::now();
    }

    /// Add metadata
    pub fn with_metadata<S: Into<String>>(mut self, key: S, value: Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }

    /// Get metadata value
    pub fn metadata(&self, key: &str) -> Option<&Value> {
        self.metadata.get(key)
    }

    /// Check if connection is stale (older than specified duration)
    pub fn is_stale(&self, max_age: chrono::Duration) -> bool {
        chrono::Utc::now().signed_duration_since(self.last_used) > max_age
    }
}

/// Data query specification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataQuery {
    /// Query type
    pub query_type: QueryType,
    /// Query string or specification
    pub query: String,
    /// Query parameters
    pub parameters: HashMap<String, Value>,
    /// Result limit
    pub limit: Option<usize>,
    /// Result offset
    pub offset: Option<usize>,
    /// Sort specification
    pub sort: Option<Vec<SortField>>,
    /// Filter conditions
    pub filters: Vec<QueryFilter>,
    /// Custom query options
    pub options: HashMap<String, Value>,
}

impl DataQuery {
    /// Create a simple SELECT query
    pub fn select<S: Into<String>>(query: S) -> Self {
        Self {
            query_type: QueryType::Select,
            query: query.into(),
            parameters: HashMap::new(),
            limit: None,
            offset: None,
            sort: None,
            filters: Vec::new(),
            options: HashMap::new(),
        }
    }

    /// Create an INSERT query
    pub fn insert<S: Into<String>>(query: S) -> Self {
        Self {
            query_type: QueryType::Insert,
            query: query.into(),
            parameters: HashMap::new(),
            limit: None,
            offset: None,
            sort: None,
            filters: Vec::new(),
            options: HashMap::new(),
        }
    }

    /// Create an UPDATE query
    pub fn update<S: Into<String>>(query: S) -> Self {
        Self {
            query_type: QueryType::Update,
            query: query.into(),
            parameters: HashMap::new(),
            limit: None,
            offset: None,
            sort: None,
            filters: Vec::new(),
            options: HashMap::new(),
        }
    }

    /// Create a DELETE query
    pub fn delete<S: Into<String>>(query: S) -> Self {
        Self {
            query_type: QueryType::Delete,
            query: query.into(),
            parameters: HashMap::new(),
            limit: None,
            offset: None,
            sort: None,
            filters: Vec::new(),
            options: HashMap::new(),
        }
    }

    /// Add a parameter
    pub fn with_parameter<S: Into<String>>(mut self, key: S, value: Value) -> Self {
        self.parameters.insert(key.into(), value);
        self
    }

    /// Set limit
    pub fn with_limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Set offset
    pub fn with_offset(mut self, offset: usize) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Add sort field
    pub fn with_sort(mut self, field: SortField) -> Self {
        self.sort.get_or_insert_with(Vec::new).push(field);
        self
    }

    /// Add filter
    pub fn with_filter(mut self, filter: QueryFilter) -> Self {
        self.filters.push(filter);
        self
    }

    /// Add option
    pub fn with_option<S: Into<String>>(mut self, key: S, value: Value) -> Self {
        self.options.insert(key.into(), value);
        self
    }
}

/// Query type enumeration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum QueryType {
    /// SELECT query
    Select,
    /// INSERT query
    Insert,
    /// UPDATE query
    Update,
    /// DELETE query
    Delete,
    /// Custom query type
    Custom(String),
}

impl fmt::Display for QueryType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            QueryType::Select => write!(f, "SELECT"),
            QueryType::Insert => write!(f, "INSERT"),
            QueryType::Update => write!(f, "UPDATE"),
            QueryType::Delete => write!(f, "DELETE"),
            QueryType::Custom(custom) => write!(f, "{}", custom),
        }
    }
}

use std::fmt;

/// Sort field specification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SortField {
    /// Field name
    pub field: String,
    /// Sort direction
    pub direction: SortDirection,
}

impl SortField {
    /// Create ascending sort
    pub fn asc<S: Into<String>>(field: S) -> Self {
        Self {
            field: field.into(),
            direction: SortDirection::Ascending,
        }
    }

    /// Create descending sort
    pub fn desc<S: Into<String>>(field: S) -> Self {
        Self {
            field: field.into(),
            direction: SortDirection::Descending,
        }
    }
}

/// Sort direction
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SortDirection {
    /// Ascending order
    Ascending,
    /// Descending order
    Descending,
}

/// Query filter specification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryFilter {
    /// Field name
    pub field: String,
    /// Filter operator
    pub operator: FilterOperator,
    /// Filter value
    pub value: Value,
    /// Logical AND/OR with next filter
    pub logical_op: Option<LogicalOperator>,
}

impl QueryFilter {
    /// Create equality filter
    pub fn equals<S: Into<String>>(field: S, value: Value) -> Self {
        Self {
            field: field.into(),
            operator: FilterOperator::Equals,
            value,
            logical_op: None,
        }
    }

    /// Create greater than filter
    pub fn greater_than<S: Into<String>>(field: S, value: Value) -> Self {
        Self {
            field: field.into(),
            operator: FilterOperator::GreaterThan,
            value,
            logical_op: None,
        }
    }

    /// Create less than filter
    pub fn less_than<S: Into<String>>(field: S, value: Value) -> Self {
        Self {
            field: field.into(),
            operator: FilterOperator::LessThan,
            value,
            logical_op: None,
        }
    }

    /// Create contains filter
    pub fn contains<S: Into<String>>(field: S, value: Value) -> Self {
        Self {
            field: field.into(),
            operator: FilterOperator::Contains,
            value,
            logical_op: None,
        }
    }

    /// Add logical AND
    pub fn and(mut self) -> Self {
        self.logical_op = Some(LogicalOperator::And);
        self
    }

    /// Add logical OR
    pub fn or(mut self) -> Self {
        self.logical_op = Some(LogicalOperator::Or);
        self
    }
}

/// Filter operator
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FilterOperator {
    /// Equal to
    Equals,
    /// Not equal to
    NotEquals,
    /// Greater than
    GreaterThan,
    /// Greater than or equal
    GreaterThanOrEqual,
    /// Less than
    LessThan,
    /// Less than or equal
    LessThanOrEqual,
    /// Contains (for strings/arrays)
    Contains,
    /// Starts with (for strings)
    StartsWith,
    /// Ends with (for strings)
    EndsWith,
    /// In array
    In,
    /// Not in array
    NotIn,
    /// Is null
    IsNull,
    /// Is not null
    IsNotNull,
}

/// Logical operator for combining filters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum LogicalOperator {
    /// Logical AND
    And,
    /// Logical OR
    Or,
}

/// Query result data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataResult {
    /// Result rows
    pub rows: Vec<DataRow>,
    /// Column metadata
    pub columns: Vec<ColumnInfo>,
    /// Total number of rows (for pagination)
    pub total_count: Option<usize>,
    /// Query execution time
    pub execution_time_ms: u64,
    /// Custom result metadata
    pub metadata: HashMap<String, Value>,
}

impl DataResult {
    /// Create empty result
    pub fn empty() -> Self {
        Self {
            rows: Vec::new(),
            columns: Vec::new(),
            total_count: Some(0),
            execution_time_ms: 0,
            metadata: HashMap::new(),
        }
    }

    /// Create result with rows
    pub fn with_rows(rows: Vec<DataRow>, columns: Vec<ColumnInfo>) -> Self {
        let row_count = rows.len();
        Self {
            rows,
            columns,
            total_count: Some(row_count),
            execution_time_ms: 0,
            metadata: HashMap::new(),
        }
    }

    /// Add metadata
    pub fn with_metadata<S: Into<String>>(mut self, key: S, value: Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }

    /// Set execution time
    pub fn with_execution_time(mut self, time_ms: u64) -> Self {
        self.execution_time_ms = time_ms;
        self
    }

    /// Get row count
    pub fn row_count(&self) -> usize {
        self.rows.len()
    }

    /// Get column count
    pub fn column_count(&self) -> usize {
        self.columns.len()
    }

    /// Convert to JSON array
    pub fn to_json_array(&self) -> Result<Value> {
        let mut json_rows = Vec::new();
        for row in &self.rows {
            json_rows.push(row.to_json(&self.columns)?);
        }
        Ok(Value::Array(json_rows))
    }
}

/// Data row
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataRow {
    /// Row values (indexed by column position)
    pub values: Vec<Value>,
    /// Row metadata
    pub metadata: HashMap<String, Value>,
}

impl DataRow {
    /// Create new row
    pub fn new(values: Vec<Value>) -> Self {
        Self {
            values,
            metadata: HashMap::new(),
        }
    }

    /// Get value by column index
    pub fn get(&self, index: usize) -> Option<&Value> {
        self.values.get(index)
    }

    /// Get value by column name
    pub fn get_by_name(&self, name: &str, columns: &[ColumnInfo]) -> Option<&Value> {
        columns
            .iter()
            .position(|col| col.name == name)
            .and_then(|index| self.get(index))
    }

    /// Convert row to JSON object
    pub fn to_json(&self, columns: &[ColumnInfo]) -> Result<Value> {
        let mut obj = serde_json::Map::new();
        for (i, value) in self.values.iter().enumerate() {
            if let Some(column) = columns.get(i) {
                obj.insert(column.name.clone(), value.clone());
            }
        }
        Ok(Value::Object(obj))
    }
}

/// Column information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColumnInfo {
    /// Column name
    pub name: String,
    /// Column data type
    pub data_type: DataType,
    /// Whether column is nullable
    pub nullable: bool,
    /// Column description
    pub description: Option<String>,
    /// Column metadata
    pub metadata: HashMap<String, Value>,
}

impl ColumnInfo {
    /// Create new column info
    pub fn new<S: Into<String>>(name: S, data_type: DataType) -> Self {
        Self {
            name: name.into(),
            data_type,
            nullable: true,
            description: None,
            metadata: HashMap::new(),
        }
    }

    /// Set nullable
    pub fn nullable(mut self, nullable: bool) -> Self {
        self.nullable = nullable;
        self
    }

    /// Set description
    pub fn description<S: Into<String>>(mut self, description: S) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Add metadata
    pub fn with_metadata<S: Into<String>>(mut self, key: S, value: Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }
}

/// Data type enumeration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DataType {
    /// Text/string data
    Text,
    /// Integer number
    Integer,
    /// Floating point number
    Float,
    /// Boolean value
    Boolean,
    /// Date/time value
    DateTime,
    /// Binary data
    Binary,
    /// JSON data
    Json,
    /// UUID
    Uuid,
    /// Custom data type
    Custom(String),
}

impl fmt::Display for DataType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DataType::Text => write!(f, "TEXT"),
            DataType::Integer => write!(f, "INTEGER"),
            DataType::Float => write!(f, "FLOAT"),
            DataType::Boolean => write!(f, "BOOLEAN"),
            DataType::DateTime => write!(f, "DATETIME"),
            DataType::Binary => write!(f, "BINARY"),
            DataType::Json => write!(f, "JSON"),
            DataType::Uuid => write!(f, "UUID"),
            DataType::Custom(custom) => write!(f, "{}", custom),
        }
    }
}

/// Data source schema information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Schema {
    /// Schema name
    pub name: Option<String>,
    /// Tables in the schema
    pub tables: Vec<TableInfo>,
    /// Custom schema metadata
    pub metadata: HashMap<String, Value>,
}

impl Default for Schema {
    fn default() -> Self {
        Self::new()
    }
}

impl Schema {
    /// Create new schema
    pub fn new() -> Self {
        Self {
            name: None,
            tables: Vec::new(),
            metadata: HashMap::new(),
        }
    }

    /// Add table
    pub fn with_table(mut self, table: TableInfo) -> Self {
        self.tables.push(table);
        self
    }

    /// Get table by name
    pub fn get_table(&self, name: &str) -> Option<&TableInfo> {
        self.tables.iter().find(|t| t.name == name)
    }

    /// Get all table names
    pub fn table_names(&self) -> Vec<&str> {
        self.tables.iter().map(|t| t.name.as_str()).collect()
    }
}

/// Table information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableInfo {
    /// Table name
    pub name: String,
    /// Columns in the table
    pub columns: Vec<ColumnInfo>,
    /// Primary key columns
    pub primary_keys: Vec<String>,
    /// Foreign key relationships
    pub foreign_keys: Vec<ForeignKey>,
    /// Table description
    pub description: Option<String>,
    /// Row count (if available)
    pub row_count: Option<usize>,
    /// Custom table metadata
    pub metadata: HashMap<String, Value>,
}

impl TableInfo {
    /// Create new table info
    pub fn new<S: Into<String>>(name: S) -> Self {
        Self {
            name: name.into(),
            columns: Vec::new(),
            primary_keys: Vec::new(),
            foreign_keys: Vec::new(),
            description: None,
            row_count: None,
            metadata: HashMap::new(),
        }
    }

    /// Add column
    pub fn with_column(mut self, column: ColumnInfo) -> Self {
        self.columns.push(column);
        self
    }

    /// Add primary key
    pub fn with_primary_key<S: Into<String>>(mut self, column: S) -> Self {
        self.primary_keys.push(column.into());
        self
    }

    /// Add foreign key
    pub fn with_foreign_key(mut self, fk: ForeignKey) -> Self {
        self.foreign_keys.push(fk);
        self
    }

    /// Set description
    pub fn description<S: Into<String>>(mut self, description: S) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set row count
    pub fn row_count(mut self, count: usize) -> Self {
        self.row_count = Some(count);
        self
    }

    /// Get column by name
    pub fn get_column(&self, name: &str) -> Option<&ColumnInfo> {
        self.columns.iter().find(|c| c.name == name)
    }

    /// Check if column is primary key
    pub fn is_primary_key(&self, column: &str) -> bool {
        self.primary_keys.contains(&column.to_string())
    }
}

/// Foreign key relationship
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForeignKey {
    /// Local column name
    pub column: String,
    /// Referenced table name
    pub referenced_table: String,
    /// Referenced column name
    pub referenced_column: String,
    /// Relationship name
    pub name: Option<String>,
}

/// Connection test result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectionTestResult {
    /// Test successful
    pub success: bool,
    /// Test message
    pub message: String,
    /// Connection latency in milliseconds
    pub latency_ms: Option<u64>,
    /// Test metadata
    pub metadata: HashMap<String, Value>,
}

impl ConnectionTestResult {
    /// Create successful test result
    pub fn success<S: Into<String>>(message: S) -> Self {
        Self {
            success: true,
            message: message.into(),
            latency_ms: None,
            metadata: HashMap::new(),
        }
    }

    /// Create failed test result
    pub fn failure<S: Into<String>>(message: S) -> Self {
        Self {
            success: false,
            message: message.into(),
            latency_ms: None,
            metadata: HashMap::new(),
        }
    }

    /// Set latency
    pub fn with_latency(mut self, latency_ms: u64) -> Self {
        self.latency_ms = Some(latency_ms);
        self
    }

    /// Add metadata
    pub fn with_metadata<S: Into<String>>(mut self, key: S, value: Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }
}

/// Data source plugin registry entry
pub struct DataSourcePluginEntry {
    /// Plugin ID
    pub plugin_id: crate::PluginId,
    /// Plugin instance
    pub plugin: std::sync::Arc<dyn DataSourcePlugin>,
    /// Plugin configuration
    pub config: DataSourcePluginConfig,
    /// Plugin capabilities
    pub capabilities: PluginCapabilities,
}

impl DataSourcePluginEntry {
    /// Create new plugin entry
    pub fn new(
        plugin_id: crate::PluginId,
        plugin: std::sync::Arc<dyn DataSourcePlugin>,
        config: DataSourcePluginConfig,
    ) -> Self {
        let capabilities = plugin.capabilities();
        Self {
            plugin_id,
            plugin,
            config,
            capabilities,
        }
    }

    /// Check if plugin is enabled
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Check if plugin supports a data source type
    pub fn supports_type(&self, data_type: &str) -> bool {
        self.config.data_source_type == data_type
    }
}

/// Helper trait for creating data source plugins
pub trait DataSourcePluginFactory: Send + Sync {
    /// Create a new data source plugin instance
    fn create_plugin(&self) -> Result<Box<dyn DataSourcePlugin>>;
}

/// Built-in data source helpers
pub mod helpers {
    use super::*;

    /// Create a simple in-memory data source for testing
    pub fn create_memory_data_source() -> Vec<DataRow> {
        vec![
            DataRow::new(vec![
                Value::String("John".to_string()),
                Value::String("Doe".to_string()),
                Value::Number(30.into()),
            ]),
            DataRow::new(vec![
                Value::String("Jane".to_string()),
                Value::String("Smith".to_string()),
                Value::Number(25.into()),
            ]),
        ]
    }

    /// Create sample column info for testing
    pub fn create_sample_columns() -> Vec<ColumnInfo> {
        vec![
            ColumnInfo::new("first_name", DataType::Text).nullable(false),
            ColumnInfo::new("last_name", DataType::Text).nullable(false),
            ColumnInfo::new("age", DataType::Integer).nullable(false),
        ]
    }

    /// Create sample schema for testing
    pub fn create_sample_schema() -> Schema {
        let table = TableInfo::new("users")
            .with_column(ColumnInfo::new("id", DataType::Integer).nullable(false))
            .with_column(ColumnInfo::new("first_name", DataType::Text).nullable(false))
            .with_column(ColumnInfo::new("last_name", DataType::Text).nullable(false))
            .with_column(ColumnInfo::new("email", DataType::Text).nullable(false))
            .with_primary_key("id");

        Schema::new().with_table(table)
    }
}

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

    // ==================== DataSourcePluginConfig Tests ====================

    #[test]
    fn test_data_source_plugin_config_default() {
        let config = DataSourcePluginConfig::default();

        assert!(config.config.is_empty());
        assert!(config.enabled);
        assert_eq!(config.data_source_type, "unknown");
        assert!(config.connection_string.is_none());
        assert_eq!(config.connection_timeout_secs, 30);
        assert_eq!(config.query_timeout_secs, 30);
        assert_eq!(config.max_connections, 10);
        assert!(config.credentials.is_none());
        assert!(config.ssl_config.is_none());
        assert!(config.settings.is_empty());
    }

    #[test]
    fn test_data_source_plugin_config_custom() {
        let config = DataSourcePluginConfig {
            config: HashMap::from([("key".to_string(), Value::String("value".to_string()))]),
            enabled: false,
            data_source_type: "postgresql".to_string(),
            connection_string: Some("postgres://localhost:5432".to_string()),
            connection_timeout_secs: 60,
            query_timeout_secs: 120,
            max_connections: 20,
            credentials: Some(DataSourceCredentials::user_pass("user", "pass")),
            ssl_config: Some(SslConfig::default()),
            settings: HashMap::new(),
        };

        assert!(!config.config.is_empty());
        assert!(!config.enabled);
        assert_eq!(config.data_source_type, "postgresql");
        assert!(config.connection_string.is_some());
    }

    #[test]
    fn test_data_source_plugin_config_clone() {
        let config = DataSourcePluginConfig::default();
        let cloned = config.clone();

        assert_eq!(cloned.data_source_type, config.data_source_type);
        assert_eq!(cloned.enabled, config.enabled);
    }

    #[test]
    fn test_data_source_plugin_config_serialization() {
        let config = DataSourcePluginConfig::default();
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: DataSourcePluginConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.data_source_type, config.data_source_type);
    }

    // ==================== DataSourceCredentials Tests ====================

    #[test]
    fn test_credentials_user_pass() {
        let creds = DataSourceCredentials::user_pass("admin", "secret123");

        assert_eq!(creds.username.as_deref(), Some("admin"));
        assert_eq!(creds.password.as_deref(), Some("secret123"));
        assert!(creds.api_key.is_none());
        assert!(creds.bearer_token.is_none());
    }

    #[test]
    fn test_credentials_api_key() {
        let creds = DataSourceCredentials::api_key("my-api-key-12345");

        assert!(creds.username.is_none());
        assert!(creds.password.is_none());
        assert_eq!(creds.api_key.as_deref(), Some("my-api-key-12345"));
        assert!(creds.bearer_token.is_none());
    }

    #[test]
    fn test_credentials_bearer_token() {
        let creds = DataSourceCredentials::bearer_token("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9");

        assert!(creds.username.is_none());
        assert!(creds.password.is_none());
        assert!(creds.api_key.is_none());
        assert_eq!(creds.bearer_token.as_deref(), Some("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"));
    }

    #[test]
    fn test_credentials_clone() {
        let creds = DataSourceCredentials::api_key("test");
        let cloned = creds.clone();

        assert_eq!(cloned.api_key, creds.api_key);
    }

    // ==================== SslConfig Tests ====================

    #[test]
    fn test_ssl_config_default() {
        let config = SslConfig::default();

        assert!(!config.enabled);
        assert!(config.ca_cert_path.is_none());
        assert!(config.client_cert_path.is_none());
        assert!(config.client_key_path.is_none());
        assert!(!config.skip_verify);
        assert!(config.custom.is_empty());
    }

    #[test]
    fn test_ssl_config_custom() {
        let config = SslConfig {
            enabled: true,
            ca_cert_path: Some("/certs/ca.pem".to_string()),
            client_cert_path: Some("/certs/client.pem".to_string()),
            client_key_path: Some("/certs/client.key".to_string()),
            skip_verify: false,
            custom: HashMap::new(),
        };

        assert!(config.enabled);
        assert_eq!(config.ca_cert_path.as_deref(), Some("/certs/ca.pem"));
    }

    // ==================== DataConnection Tests ====================

    #[test]
    fn test_data_connection_new() {
        let conn = DataConnection::new("postgresql", Value::Null);

        assert!(!conn.id.is_empty());
        assert_eq!(conn.connection_type, "postgresql");
        assert!(conn.metadata.is_empty());
    }

    #[test]
    fn test_data_connection_mark_used() {
        let mut conn = DataConnection::new("mysql", Value::Null);
        let original_last_used = conn.last_used;

        std::thread::sleep(std::time::Duration::from_millis(10));
        conn.mark_used();

        assert!(conn.last_used >= original_last_used);
    }

    #[test]
    fn test_data_connection_with_metadata() {
        let conn = DataConnection::new("api", Value::Null)
            .with_metadata("version", Value::String("v1".to_string()));

        assert!(conn.metadata("version").is_some());
        assert!(conn.metadata("nonexistent").is_none());
    }

    #[test]
    fn test_data_connection_is_stale() {
        let conn = DataConnection::new("test", Value::Null);

        // Should not be stale with a 1 hour max age
        assert!(!conn.is_stale(chrono::Duration::hours(1)));

        // Should be stale with 0 duration
        assert!(conn.is_stale(chrono::Duration::zero()));
    }

    #[test]
    fn test_data_connection_clone() {
        let conn = DataConnection::new("sqlite", Value::Null);
        let cloned = conn.clone();

        assert_eq!(cloned.id, conn.id);
        assert_eq!(cloned.connection_type, conn.connection_type);
    }

    // ==================== DataQuery Tests ====================

    #[test]
    fn test_data_query_select() {
        let query = DataQuery::select("SELECT * FROM users");

        assert!(matches!(query.query_type, QueryType::Select));
        assert_eq!(query.query, "SELECT * FROM users");
    }

    #[test]
    fn test_data_query_insert() {
        let query = DataQuery::insert("INSERT INTO users VALUES (?)");

        assert!(matches!(query.query_type, QueryType::Insert));
    }

    #[test]
    fn test_data_query_update() {
        let query = DataQuery::update("UPDATE users SET name = ?");

        assert!(matches!(query.query_type, QueryType::Update));
    }

    #[test]
    fn test_data_query_delete() {
        let query = DataQuery::delete("DELETE FROM users WHERE id = ?");

        assert!(matches!(query.query_type, QueryType::Delete));
    }

    #[test]
    fn test_data_query_with_parameter() {
        let query = DataQuery::select("SELECT * FROM users WHERE id = :id")
            .with_parameter("id", Value::Number(42.into()));

        assert!(query.parameters.contains_key("id"));
    }

    #[test]
    fn test_data_query_with_limit() {
        let query = DataQuery::select("SELECT * FROM users").with_limit(10);

        assert_eq!(query.limit, Some(10));
    }

    #[test]
    fn test_data_query_with_offset() {
        let query = DataQuery::select("SELECT * FROM users").with_offset(20);

        assert_eq!(query.offset, Some(20));
    }

    #[test]
    fn test_data_query_with_sort() {
        let query = DataQuery::select("SELECT * FROM users").with_sort(SortField::asc("name"));

        assert!(query.sort.is_some());
        assert_eq!(query.sort.as_ref().unwrap().len(), 1);
    }

    #[test]
    fn test_data_query_with_filter() {
        let query = DataQuery::select("SELECT * FROM users")
            .with_filter(QueryFilter::equals("status", Value::String("active".to_string())));

        assert_eq!(query.filters.len(), 1);
    }

    #[test]
    fn test_data_query_with_option() {
        let query = DataQuery::select("SELECT * FROM users")
            .with_option("timeout", Value::Number(30.into()));

        assert!(query.options.contains_key("timeout"));
    }

    #[test]
    fn test_data_query_chained() {
        let query = DataQuery::select("SELECT * FROM users")
            .with_parameter("status", Value::String("active".to_string()))
            .with_limit(50)
            .with_offset(0)
            .with_sort(SortField::desc("created_at"));

        assert!(!query.parameters.is_empty());
        assert_eq!(query.limit, Some(50));
        assert_eq!(query.offset, Some(0));
        assert!(query.sort.is_some());
    }

    // ==================== QueryType Tests ====================

    #[test]
    fn test_query_type_display_select() {
        assert_eq!(format!("{}", QueryType::Select), "SELECT");
    }

    #[test]
    fn test_query_type_display_insert() {
        assert_eq!(format!("{}", QueryType::Insert), "INSERT");
    }

    #[test]
    fn test_query_type_display_update() {
        assert_eq!(format!("{}", QueryType::Update), "UPDATE");
    }

    #[test]
    fn test_query_type_display_delete() {
        assert_eq!(format!("{}", QueryType::Delete), "DELETE");
    }

    #[test]
    fn test_query_type_display_custom() {
        assert_eq!(format!("{}", QueryType::Custom("MERGE".to_string())), "MERGE");
    }

    // ==================== SortField Tests ====================

    #[test]
    fn test_sort_field_asc() {
        let sort = SortField::asc("name");

        assert_eq!(sort.field, "name");
        assert!(matches!(sort.direction, SortDirection::Ascending));
    }

    #[test]
    fn test_sort_field_desc() {
        let sort = SortField::desc("created_at");

        assert_eq!(sort.field, "created_at");
        assert!(matches!(sort.direction, SortDirection::Descending));
    }

    // ==================== QueryFilter Tests ====================

    #[test]
    fn test_query_filter_equals() {
        let filter = QueryFilter::equals("status", Value::String("active".to_string()));

        assert_eq!(filter.field, "status");
        assert!(matches!(filter.operator, FilterOperator::Equals));
    }

    #[test]
    fn test_query_filter_greater_than() {
        let filter = QueryFilter::greater_than("age", Value::Number(18.into()));

        assert!(matches!(filter.operator, FilterOperator::GreaterThan));
    }

    #[test]
    fn test_query_filter_less_than() {
        let filter = QueryFilter::less_than("price", Value::Number(100.into()));

        assert!(matches!(filter.operator, FilterOperator::LessThan));
    }

    #[test]
    fn test_query_filter_contains() {
        let filter = QueryFilter::contains("name", Value::String("test".to_string()));

        assert!(matches!(filter.operator, FilterOperator::Contains));
    }

    #[test]
    fn test_query_filter_and() {
        let filter = QueryFilter::equals("status", Value::String("active".to_string())).and();

        assert!(matches!(filter.logical_op, Some(LogicalOperator::And)));
    }

    #[test]
    fn test_query_filter_or() {
        let filter = QueryFilter::equals("status", Value::String("pending".to_string())).or();

        assert!(matches!(filter.logical_op, Some(LogicalOperator::Or)));
    }

    // ==================== DataResult Tests ====================

    #[test]
    fn test_data_result_empty() {
        let result = DataResult::empty();

        assert!(result.rows.is_empty());
        assert!(result.columns.is_empty());
        assert_eq!(result.total_count, Some(0));
        assert_eq!(result.execution_time_ms, 0);
    }

    #[test]
    fn test_data_result_with_rows() {
        let rows = vec![
            DataRow::new(vec![Value::String("test".to_string())]),
            DataRow::new(vec![Value::String("test2".to_string())]),
        ];
        let columns = vec![ColumnInfo::new("name", DataType::Text)];

        let result = DataResult::with_rows(rows, columns);

        assert_eq!(result.row_count(), 2);
        assert_eq!(result.column_count(), 1);
    }

    #[test]
    fn test_data_result_with_metadata() {
        let result = DataResult::empty().with_metadata("source", Value::String("test".to_string()));

        assert!(result.metadata.contains_key("source"));
    }

    #[test]
    fn test_data_result_with_execution_time() {
        let result = DataResult::empty().with_execution_time(150);

        assert_eq!(result.execution_time_ms, 150);
    }

    #[test]
    fn test_data_result_to_json_array() {
        let rows = vec![DataRow::new(vec![Value::String("John".to_string())])];
        let columns = vec![ColumnInfo::new("name", DataType::Text)];
        let result = DataResult::with_rows(rows, columns);

        let json = result.to_json_array().unwrap();
        assert!(json.is_array());
    }

    // ==================== DataRow Tests ====================

    #[test]
    fn test_data_row_new() {
        let row = DataRow::new(vec![Value::Number(1.into()), Value::String("test".to_string())]);

        assert_eq!(row.values.len(), 2);
        assert!(row.metadata.is_empty());
    }

    #[test]
    fn test_data_row_get() {
        let row = DataRow::new(vec![Value::Number(42.into())]);

        assert!(row.get(0).is_some());
        assert!(row.get(1).is_none());
    }

    #[test]
    fn test_data_row_get_by_name() {
        let row = DataRow::new(vec![Value::String("John".to_string())]);
        let columns = vec![ColumnInfo::new("name", DataType::Text)];

        assert!(row.get_by_name("name", &columns).is_some());
        assert!(row.get_by_name("nonexistent", &columns).is_none());
    }

    #[test]
    fn test_data_row_to_json() {
        let row = DataRow::new(vec![Value::String("John".to_string()), Value::Number(30.into())]);
        let columns = vec![
            ColumnInfo::new("name", DataType::Text),
            ColumnInfo::new("age", DataType::Integer),
        ];

        let json = row.to_json(&columns).unwrap();
        assert!(json.is_object());
    }

    // ==================== ColumnInfo Tests ====================

    #[test]
    fn test_column_info_new() {
        let col = ColumnInfo::new("id", DataType::Integer);

        assert_eq!(col.name, "id");
        assert!(col.nullable);
        assert!(col.description.is_none());
    }

    #[test]
    fn test_column_info_nullable() {
        let col = ColumnInfo::new("id", DataType::Integer).nullable(false);

        assert!(!col.nullable);
    }

    #[test]
    fn test_column_info_description() {
        let col = ColumnInfo::new("id", DataType::Integer).description("Primary key");

        assert_eq!(col.description.as_deref(), Some("Primary key"));
    }

    #[test]
    fn test_column_info_with_metadata() {
        let col =
            ColumnInfo::new("id", DataType::Integer).with_metadata("index", Value::Bool(true));

        assert!(col.metadata.contains_key("index"));
    }

    // ==================== DataType Tests ====================

    #[test]
    fn test_data_type_display_text() {
        assert_eq!(format!("{}", DataType::Text), "TEXT");
    }

    #[test]
    fn test_data_type_display_integer() {
        assert_eq!(format!("{}", DataType::Integer), "INTEGER");
    }

    #[test]
    fn test_data_type_display_float() {
        assert_eq!(format!("{}", DataType::Float), "FLOAT");
    }

    #[test]
    fn test_data_type_display_boolean() {
        assert_eq!(format!("{}", DataType::Boolean), "BOOLEAN");
    }

    #[test]
    fn test_data_type_display_datetime() {
        assert_eq!(format!("{}", DataType::DateTime), "DATETIME");
    }

    #[test]
    fn test_data_type_display_custom() {
        assert_eq!(format!("{}", DataType::Custom("MONEY".to_string())), "MONEY");
    }

    // ==================== Schema Tests ====================

    #[test]
    fn test_schema_default() {
        let schema = Schema::default();

        assert!(schema.name.is_none());
        assert!(schema.tables.is_empty());
    }

    #[test]
    fn test_schema_new() {
        let schema = Schema::new();

        assert!(schema.tables.is_empty());
    }

    #[test]
    fn test_schema_with_table() {
        let schema = Schema::new().with_table(TableInfo::new("users"));

        assert_eq!(schema.tables.len(), 1);
    }

    #[test]
    fn test_schema_get_table() {
        let schema = Schema::new().with_table(TableInfo::new("users"));

        assert!(schema.get_table("users").is_some());
        assert!(schema.get_table("nonexistent").is_none());
    }

    #[test]
    fn test_schema_table_names() {
        let schema = Schema::new()
            .with_table(TableInfo::new("users"))
            .with_table(TableInfo::new("orders"));

        let names = schema.table_names();
        assert!(names.contains(&"users"));
        assert!(names.contains(&"orders"));
    }

    // ==================== TableInfo Tests ====================

    #[test]
    fn test_table_info_new() {
        let table = TableInfo::new("users");

        assert_eq!(table.name, "users");
        assert!(table.columns.is_empty());
        assert!(table.primary_keys.is_empty());
    }

    #[test]
    fn test_table_info_with_column() {
        let table = TableInfo::new("users").with_column(ColumnInfo::new("id", DataType::Integer));

        assert_eq!(table.columns.len(), 1);
    }

    #[test]
    fn test_table_info_with_primary_key() {
        let table = TableInfo::new("users").with_primary_key("id");

        assert!(table.is_primary_key("id"));
        assert!(!table.is_primary_key("name"));
    }

    #[test]
    fn test_table_info_with_foreign_key() {
        let fk = ForeignKey {
            column: "user_id".to_string(),
            referenced_table: "users".to_string(),
            referenced_column: "id".to_string(),
            name: Some("fk_orders_user".to_string()),
        };

        let table = TableInfo::new("orders").with_foreign_key(fk);

        assert_eq!(table.foreign_keys.len(), 1);
    }

    #[test]
    fn test_table_info_description() {
        let table = TableInfo::new("users").description("Stores user information");

        assert_eq!(table.description.as_deref(), Some("Stores user information"));
    }

    #[test]
    fn test_table_info_row_count() {
        let table = TableInfo::new("users").row_count(1000);

        assert_eq!(table.row_count, Some(1000));
    }

    #[test]
    fn test_table_info_get_column() {
        let table = TableInfo::new("users")
            .with_column(ColumnInfo::new("id", DataType::Integer))
            .with_column(ColumnInfo::new("name", DataType::Text));

        assert!(table.get_column("id").is_some());
        assert!(table.get_column("nonexistent").is_none());
    }

    // ==================== ForeignKey Tests ====================

    #[test]
    fn test_foreign_key_creation() {
        let fk = ForeignKey {
            column: "user_id".to_string(),
            referenced_table: "users".to_string(),
            referenced_column: "id".to_string(),
            name: None,
        };

        assert_eq!(fk.column, "user_id");
        assert_eq!(fk.referenced_table, "users");
    }

    // ==================== ConnectionTestResult Tests ====================

    #[test]
    fn test_connection_test_result_success() {
        let result = ConnectionTestResult::success("Connection successful");

        assert!(result.success);
        assert_eq!(result.message, "Connection successful");
    }

    #[test]
    fn test_connection_test_result_failure() {
        let result = ConnectionTestResult::failure("Connection refused");

        assert!(!result.success);
        assert_eq!(result.message, "Connection refused");
    }

    #[test]
    fn test_connection_test_result_with_latency() {
        let result = ConnectionTestResult::success("OK").with_latency(50);

        assert_eq!(result.latency_ms, Some(50));
    }

    #[test]
    fn test_connection_test_result_with_metadata() {
        let result = ConnectionTestResult::success("OK")
            .with_metadata("version", Value::String("5.7".to_string()));

        assert!(result.metadata.contains_key("version"));
    }

    // ==================== Helper Functions Tests ====================

    #[test]
    fn test_helpers_create_memory_data_source() {
        let rows = helpers::create_memory_data_source();

        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].values.len(), 3);
    }

    #[test]
    fn test_helpers_create_sample_columns() {
        let columns = helpers::create_sample_columns();

        assert_eq!(columns.len(), 3);
        assert_eq!(columns[0].name, "first_name");
    }

    #[test]
    fn test_helpers_create_sample_schema() {
        let schema = helpers::create_sample_schema();

        assert!(schema.get_table("users").is_some());
        let users = schema.get_table("users").unwrap();
        assert!(users.is_primary_key("id"));
    }
}