prax-query 0.8.2

Type-safe query builder for the Prax ORM
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
//! Concurrent database introspection utilities.
//!
//! This module provides high-performance introspection by fetching
//! table metadata (columns, indexes, foreign keys) concurrently.
//!
//! # Performance
//!
//! For a database with 50 tables, concurrent introspection can reduce
//! total time from ~5 seconds (sequential) to ~1.5 seconds (concurrent)
//! - approximately a 60% improvement.
//!
//! # Example
//!
//! ```rust,ignore
//! use prax_query::async_optimize::introspect::{
//!     ConcurrentIntrospector, IntrospectionConfig,
//! };
//!
//! let introspector = ConcurrentIntrospector::new(IntrospectionConfig::default());
//!
//! // Fetch metadata for all tables concurrently
//! let results = introspector
//!     .introspect_tables(table_names, |name| async move {
//!         let columns = fetch_columns(&name).await?;
//!         let indexes = fetch_indexes(&name).await?;
//!         let foreign_keys = fetch_foreign_keys(&name).await?;
//!         Ok(TableMetadata { name, columns, indexes, foreign_keys })
//!     })
//!     .await;
//! ```

use std::future::Future;
use std::time::{Duration, Instant};

use super::concurrent::{ConcurrencyConfig, ConcurrentExecutor, TaskResult};

/// Configuration for concurrent introspection.
#[derive(Debug, Clone)]
pub struct IntrospectionConfig {
    /// Maximum concurrent table introspections.
    pub max_concurrency: usize,
    /// Timeout per table.
    pub table_timeout: Duration,
    /// Whether to continue on individual table errors.
    pub continue_on_error: bool,
    /// Batch size for multi-table queries (0 = no batching).
    pub batch_size: usize,
}

impl Default for IntrospectionConfig {
    fn default() -> Self {
        Self {
            max_concurrency: 8,
            table_timeout: Duration::from_secs(30),
            continue_on_error: true,
            batch_size: 0, // No batching by default
        }
    }
}

impl IntrospectionConfig {
    /// Create a config optimized for large databases.
    #[must_use]
    pub fn for_large_database() -> Self {
        Self {
            max_concurrency: 16,
            table_timeout: Duration::from_secs(60),
            continue_on_error: true,
            batch_size: 50,
        }
    }

    /// Create a config optimized for small databases.
    #[must_use]
    pub fn for_small_database() -> Self {
        Self {
            max_concurrency: 4,
            table_timeout: Duration::from_secs(15),
            continue_on_error: true,
            batch_size: 0,
        }
    }

    /// Set maximum concurrency.
    #[must_use]
    pub fn with_max_concurrency(mut self, max: usize) -> Self {
        self.max_concurrency = max.max(1);
        self
    }

    /// Set table timeout.
    #[must_use]
    pub fn with_table_timeout(mut self, timeout: Duration) -> Self {
        self.table_timeout = timeout;
        self
    }

    /// Set batch size for multi-table queries.
    #[must_use]
    pub fn with_batch_size(mut self, size: usize) -> Self {
        self.batch_size = size;
        self
    }
}

/// Metadata for a single table.
#[derive(Debug, Clone)]
pub struct TableMetadata {
    /// Table name.
    pub name: String,
    /// Column information.
    pub columns: Vec<ColumnMetadata>,
    /// Index information.
    pub indexes: Vec<IndexMetadata>,
    /// Foreign key information.
    pub foreign_keys: Vec<ForeignKeyMetadata>,
    /// Primary key columns.
    pub primary_key: Vec<String>,
    /// Table comment.
    pub comment: Option<String>,
}

impl TableMetadata {
    /// Create empty metadata for a table.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            columns: Vec::new(),
            indexes: Vec::new(),
            foreign_keys: Vec::new(),
            primary_key: Vec::new(),
            comment: None,
        }
    }
}

/// Column metadata.
#[derive(Debug, Clone)]
pub struct ColumnMetadata {
    /// Column name.
    pub name: String,
    /// Database type.
    pub db_type: String,
    /// Whether nullable.
    pub nullable: bool,
    /// Default value.
    pub default: Option<String>,
    /// Whether auto-increment.
    pub auto_increment: bool,
    /// Whether part of primary key.
    pub is_primary_key: bool,
}

/// Index metadata.
#[derive(Debug, Clone)]
pub struct IndexMetadata {
    /// Index name.
    pub name: String,
    /// Indexed columns.
    pub columns: Vec<String>,
    /// Whether unique.
    pub is_unique: bool,
    /// Whether primary key index.
    pub is_primary: bool,
    /// Index type (btree, hash, etc).
    pub index_type: Option<String>,
}

/// Foreign key metadata.
#[derive(Debug, Clone)]
pub struct ForeignKeyMetadata {
    /// Constraint name.
    pub name: String,
    /// Columns in this table.
    pub columns: Vec<String>,
    /// Referenced table.
    pub referenced_table: String,
    /// Referenced columns.
    pub referenced_columns: Vec<String>,
    /// On delete action.
    pub on_delete: String,
    /// On update action.
    pub on_update: String,
}

/// Result of concurrent introspection.
#[derive(Debug)]
pub struct IntrospectionResult {
    /// Successfully introspected tables.
    pub tables: Vec<TableMetadata>,
    /// Tables that failed to introspect.
    pub errors: Vec<IntrospectionError>,
    /// Total introspection time.
    pub duration: Duration,
    /// Maximum concurrent operations observed.
    pub max_concurrency: usize,
}

impl IntrospectionResult {
    /// Check if all tables were introspected successfully.
    pub fn is_complete(&self) -> bool {
        self.errors.is_empty()
    }

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

/// Error during table introspection.
#[derive(Debug, Clone)]
pub struct IntrospectionError {
    /// Table name.
    pub table: String,
    /// Error message.
    pub message: String,
    /// Whether this was a timeout.
    pub is_timeout: bool,
}

impl std::fmt::Display for IntrospectionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.is_timeout {
            write!(
                f,
                "Timeout introspecting table '{}': {}",
                self.table, self.message
            )
        } else {
            write!(
                f,
                "Error introspecting table '{}': {}",
                self.table, self.message
            )
        }
    }
}

/// Concurrent database introspector.
pub struct ConcurrentIntrospector {
    config: IntrospectionConfig,
    executor: ConcurrentExecutor,
}

impl ConcurrentIntrospector {
    /// Create a new concurrent introspector.
    pub fn new(config: IntrospectionConfig) -> Self {
        let executor_config = ConcurrencyConfig::default()
            .with_max_concurrency(config.max_concurrency)
            .with_timeout(config.table_timeout)
            .with_continue_on_error(config.continue_on_error);

        Self {
            config,
            executor: ConcurrentExecutor::new(executor_config),
        }
    }

    /// Introspect tables concurrently using a custom operation.
    ///
    /// The `operation` function is called for each table name and should
    /// return the table metadata.
    pub async fn introspect_tables<F, Fut>(
        &self,
        table_names: Vec<String>,
        operation: F,
    ) -> IntrospectionResult
    where
        F: Fn(String) -> Fut + Clone + Send + 'static,
        Fut: Future<Output = Result<TableMetadata, String>> + Send + 'static,
    {
        let start = Instant::now();

        // Create tasks for each table
        let tasks: Vec<_> = table_names
            .into_iter()
            .map(|name| {
                let op = operation.clone();
                move || op(name)
            })
            .collect();

        let (results, stats) = self.executor.execute_all(tasks).await;

        // Separate successes and failures
        let mut tables = Vec::new();
        let mut errors = Vec::new();

        for result in results {
            match result {
                TaskResult::Success { value, .. } => {
                    tables.push(value);
                }
                TaskResult::Error(e) => {
                    errors.push(IntrospectionError {
                        table: format!("task_{}", e.task_id),
                        message: e.message,
                        is_timeout: e.is_timeout,
                    });
                }
            }
        }

        IntrospectionResult {
            tables,
            errors,
            duration: start.elapsed(),
            max_concurrency: stats.max_concurrent,
        }
    }

    /// Introspect tables with associated names for error tracking.
    pub async fn introspect_named<F, Fut>(
        &self,
        table_names: Vec<String>,
        operation: F,
    ) -> IntrospectionResult
    where
        F: Fn(String) -> Fut + Clone + Send + 'static,
        Fut: Future<Output = Result<TableMetadata, String>> + Send + 'static,
    {
        let start = Instant::now();
        let names_for_errors: Vec<_> = table_names.clone();

        // Create tasks for each table
        let tasks: Vec<_> = table_names
            .into_iter()
            .map(|name| {
                let op = operation.clone();
                move || op(name)
            })
            .collect();

        let (results, stats) = self.executor.execute_all(tasks).await;

        // Separate successes and failures
        let mut tables = Vec::new();
        let mut errors = Vec::new();

        for (idx, result) in results.into_iter().enumerate() {
            match result {
                TaskResult::Success { value, .. } => {
                    tables.push(value);
                }
                TaskResult::Error(e) => {
                    let table_name = names_for_errors
                        .get(idx)
                        .cloned()
                        .unwrap_or_else(|| format!("unknown_{}", idx));
                    errors.push(IntrospectionError {
                        table: table_name,
                        message: e.message,
                        is_timeout: e.is_timeout,
                    });
                }
            }
        }

        IntrospectionResult {
            tables,
            errors,
            duration: start.elapsed(),
            max_concurrency: stats.max_concurrent,
        }
    }

    /// Get the configuration.
    pub fn config(&self) -> &IntrospectionConfig {
        &self.config
    }
}

/// Helper to batch introspection queries.
///
/// Some databases allow fetching metadata for multiple tables in a single query.
/// This helper creates batches of table names for such queries.
pub struct BatchIntrospector {
    batch_size: usize,
}

impl BatchIntrospector {
    /// Create a new batch introspector.
    pub fn new(batch_size: usize) -> Self {
        Self {
            batch_size: batch_size.max(1),
        }
    }

    /// Create batches of table names.
    pub fn create_batches(&self, tables: Vec<String>) -> Vec<Vec<String>> {
        tables.chunks(self.batch_size).map(|c| c.to_vec()).collect()
    }

    /// Execute batched introspection.
    pub async fn introspect_batched<F, Fut>(
        &self,
        tables: Vec<String>,
        max_concurrency: usize,
        operation: F,
    ) -> IntrospectionResult
    where
        F: Fn(Vec<String>) -> Fut + Clone + Send + 'static,
        Fut: Future<Output = Result<Vec<TableMetadata>, String>> + Send + 'static,
    {
        let start = Instant::now();
        let batches = self.create_batches(tables);

        let config = IntrospectionConfig::default().with_max_concurrency(max_concurrency);
        let executor = ConcurrentExecutor::new(
            ConcurrencyConfig::default()
                .with_max_concurrency(config.max_concurrency)
                .with_continue_on_error(true),
        );

        let tasks: Vec<_> = batches
            .into_iter()
            .map(|batch| {
                let op = operation.clone();
                move || op(batch)
            })
            .collect();

        let (results, stats) = executor.execute_all(tasks).await;

        // Flatten results
        let mut tables = Vec::new();
        let mut errors = Vec::new();

        for result in results {
            match result {
                TaskResult::Success { value, .. } => {
                    tables.extend(value);
                }
                TaskResult::Error(e) => {
                    errors.push(IntrospectionError {
                        table: format!("batch_{}", e.task_id),
                        message: e.message,
                        is_timeout: e.is_timeout,
                    });
                }
            }
        }

        IntrospectionResult {
            tables,
            errors,
            duration: start.elapsed(),
            max_concurrency: stats.max_concurrent,
        }
    }
}

/// Introspection phase for tracking progress.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IntrospectionPhase {
    /// Fetching table list.
    Tables,
    /// Fetching columns.
    Columns,
    /// Fetching primary keys.
    PrimaryKeys,
    /// Fetching foreign keys.
    ForeignKeys,
    /// Fetching indexes.
    Indexes,
    /// Fetching enums.
    Enums,
    /// Fetching views.
    Views,
    /// Complete.
    Complete,
}

impl IntrospectionPhase {
    /// Get the next phase.
    pub fn next(self) -> Self {
        match self {
            Self::Tables => Self::Columns,
            Self::Columns => Self::PrimaryKeys,
            Self::PrimaryKeys => Self::ForeignKeys,
            Self::ForeignKeys => Self::Indexes,
            Self::Indexes => Self::Enums,
            Self::Enums => Self::Views,
            Self::Views => Self::Complete,
            Self::Complete => Self::Complete,
        }
    }

    /// Get human-readable name.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Tables => "tables",
            Self::Columns => "columns",
            Self::PrimaryKeys => "primary keys",
            Self::ForeignKeys => "foreign keys",
            Self::Indexes => "indexes",
            Self::Enums => "enums",
            Self::Views => "views",
            Self::Complete => "complete",
        }
    }
}

/// Progress callback for introspection.
pub type ProgressCallback = Box<dyn Fn(IntrospectionPhase, usize, usize) + Send + Sync>;

/// Builder for creating concurrent introspection with progress reporting.
pub struct IntrospectorBuilder {
    config: IntrospectionConfig,
    progress_callback: Option<ProgressCallback>,
}

impl IntrospectorBuilder {
    /// Create a new builder.
    pub fn new() -> Self {
        Self {
            config: IntrospectionConfig::default(),
            progress_callback: None,
        }
    }

    /// Set the configuration.
    pub fn config(mut self, config: IntrospectionConfig) -> Self {
        self.config = config;
        self
    }

    /// Set progress callback.
    pub fn on_progress<F>(mut self, callback: F) -> Self
    where
        F: Fn(IntrospectionPhase, usize, usize) + Send + Sync + 'static,
    {
        self.progress_callback = Some(Box::new(callback));
        self
    }

    /// Build the introspector.
    pub fn build(self) -> ConcurrentIntrospector {
        ConcurrentIntrospector::new(self.config)
    }
}

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

/// SQL query templates for concurrent introspection.
pub mod queries {
    use crate::sql::DatabaseType;

    /// Generate SQL to fetch all columns for multiple tables at once.
    pub fn batch_columns_query(
        db_type: DatabaseType,
        tables: &[&str],
        schema: Option<&str>,
    ) -> String {
        let schema_name = schema.unwrap_or("public");
        let table_list = tables
            .iter()
            .map(|t| format!("'{}'", t))
            .collect::<Vec<_>>()
            .join(", ");

        match db_type {
            DatabaseType::PostgreSQL => {
                format!(
                    r#"
                    SELECT
                        c.table_name,
                        c.column_name,
                        c.data_type,
                        c.udt_name,
                        c.is_nullable = 'YES' as nullable,
                        c.column_default,
                        c.character_maximum_length,
                        c.numeric_precision,
                        c.numeric_scale,
                        col_description(
                            (c.table_schema || '.' || c.table_name)::regclass,
                            c.ordinal_position
                        ) as comment,
                        CASE
                            WHEN c.column_default LIKE 'nextval%' THEN true
                            WHEN c.is_identity = 'YES' THEN true
                            ELSE false
                        END as auto_increment
                    FROM information_schema.columns c
                    WHERE c.table_schema = '{}'
                    AND c.table_name IN ({})
                    ORDER BY c.table_name, c.ordinal_position
                    "#,
                    schema_name, table_list
                )
            }
            DatabaseType::MySQL => {
                format!(
                    r#"
                    SELECT
                        c.TABLE_NAME,
                        c.COLUMN_NAME,
                        c.DATA_TYPE,
                        c.COLUMN_TYPE,
                        c.IS_NULLABLE = 'YES' as nullable,
                        c.COLUMN_DEFAULT,
                        c.CHARACTER_MAXIMUM_LENGTH,
                        c.NUMERIC_PRECISION,
                        c.NUMERIC_SCALE,
                        c.COLUMN_COMMENT,
                        c.EXTRA LIKE '%auto_increment%' as auto_increment
                    FROM information_schema.COLUMNS c
                    WHERE c.TABLE_SCHEMA = DATABASE()
                    AND c.TABLE_NAME IN ({})
                    ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION
                    "#,
                    table_list
                )
            }
            _ => String::new(),
        }
    }

    /// Generate SQL to fetch all indexes for multiple tables at once.
    pub fn batch_indexes_query(
        db_type: DatabaseType,
        tables: &[&str],
        schema: Option<&str>,
    ) -> String {
        let schema_name = schema.unwrap_or("public");
        let table_list = tables
            .iter()
            .map(|t| format!("'{}'", t))
            .collect::<Vec<_>>()
            .join(", ");

        match db_type {
            DatabaseType::PostgreSQL => {
                format!(
                    r#"
                    SELECT
                        t.relname as table_name,
                        i.relname as index_name,
                        a.attname as column_name,
                        ix.indisunique as is_unique,
                        ix.indisprimary as is_primary,
                        am.amname as index_type
                    FROM pg_class t
                    JOIN pg_index ix ON t.oid = ix.indrelid
                    JOIN pg_class i ON i.oid = ix.indexrelid
                    JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)
                    JOIN pg_am am ON i.relam = am.oid
                    JOIN pg_namespace n ON n.oid = t.relnamespace
                    WHERE n.nspname = '{}'
                    AND t.relname IN ({})
                    ORDER BY t.relname, i.relname, a.attnum
                    "#,
                    schema_name, table_list
                )
            }
            DatabaseType::MySQL => {
                format!(
                    r#"
                    SELECT
                        s.TABLE_NAME,
                        s.INDEX_NAME,
                        s.COLUMN_NAME,
                        s.NON_UNIQUE = 0 as is_unique,
                        s.INDEX_NAME = 'PRIMARY' as is_primary,
                        s.INDEX_TYPE
                    FROM information_schema.STATISTICS s
                    WHERE s.TABLE_SCHEMA = DATABASE()
                    AND s.TABLE_NAME IN ({})
                    ORDER BY s.TABLE_NAME, s.INDEX_NAME, s.SEQ_IN_INDEX
                    "#,
                    table_list
                )
            }
            _ => String::new(),
        }
    }

    /// Generate SQL to fetch all foreign keys for multiple tables at once.
    pub fn batch_foreign_keys_query(
        db_type: DatabaseType,
        tables: &[&str],
        schema: Option<&str>,
    ) -> String {
        let schema_name = schema.unwrap_or("public");
        let table_list = tables
            .iter()
            .map(|t| format!("'{}'", t))
            .collect::<Vec<_>>()
            .join(", ");

        match db_type {
            DatabaseType::PostgreSQL => {
                format!(
                    r#"
                    SELECT
                        tc.table_name,
                        tc.constraint_name,
                        kcu.column_name,
                        ccu.table_name AS foreign_table,
                        ccu.table_schema AS foreign_schema,
                        ccu.column_name AS foreign_column,
                        rc.delete_rule,
                        rc.update_rule
                    FROM information_schema.table_constraints tc
                    JOIN information_schema.key_column_usage kcu
                        ON tc.constraint_name = kcu.constraint_name
                        AND tc.table_schema = kcu.table_schema
                    JOIN information_schema.constraint_column_usage ccu
                        ON ccu.constraint_name = tc.constraint_name
                        AND ccu.table_schema = tc.table_schema
                    JOIN information_schema.referential_constraints rc
                        ON tc.constraint_name = rc.constraint_name
                        AND tc.table_schema = rc.constraint_schema
                    WHERE tc.constraint_type = 'FOREIGN KEY'
                    AND tc.table_schema = '{}'
                    AND tc.table_name IN ({})
                    ORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position
                    "#,
                    schema_name, table_list
                )
            }
            DatabaseType::MySQL => {
                format!(
                    r#"
                    SELECT
                        kcu.TABLE_NAME,
                        kcu.CONSTRAINT_NAME,
                        kcu.COLUMN_NAME,
                        kcu.REFERENCED_TABLE_NAME,
                        kcu.REFERENCED_TABLE_SCHEMA,
                        kcu.REFERENCED_COLUMN_NAME,
                        rc.DELETE_RULE,
                        rc.UPDATE_RULE
                    FROM information_schema.KEY_COLUMN_USAGE kcu
                    JOIN information_schema.REFERENTIAL_CONSTRAINTS rc
                        ON kcu.CONSTRAINT_NAME = rc.CONSTRAINT_NAME
                        AND kcu.TABLE_SCHEMA = rc.CONSTRAINT_SCHEMA
                    WHERE kcu.TABLE_SCHEMA = DATABASE()
                    AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
                    AND kcu.TABLE_NAME IN ({})
                    ORDER BY kcu.TABLE_NAME, kcu.CONSTRAINT_NAME, kcu.ORDINAL_POSITION
                    "#,
                    table_list
                )
            }
            _ => String::new(),
        }
    }
}

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

    #[tokio::test]
    async fn test_concurrent_introspector() {
        let config = IntrospectionConfig::default().with_max_concurrency(4);
        let introspector = ConcurrentIntrospector::new(config);

        let tables = vec![
            "users".to_string(),
            "posts".to_string(),
            "comments".to_string(),
        ];

        let result = introspector
            .introspect_tables(tables, |name| async move {
                // Simulate introspection
                tokio::time::sleep(Duration::from_millis(10)).await;
                Ok(TableMetadata::new(name))
            })
            .await;

        assert_eq!(result.tables.len(), 3);
        assert!(result.errors.is_empty());
    }

    #[tokio::test]
    async fn test_batch_introspector() {
        let batch = BatchIntrospector::new(2);

        let tables = vec![
            "t1".to_string(),
            "t2".to_string(),
            "t3".to_string(),
            "t4".to_string(),
            "t5".to_string(),
        ];

        let batches = batch.create_batches(tables);
        assert_eq!(batches.len(), 3);
        assert_eq!(batches[0].len(), 2);
        assert_eq!(batches[1].len(), 2);
        assert_eq!(batches[2].len(), 1);
    }

    #[tokio::test]
    async fn test_introspection_with_errors() {
        let config = IntrospectionConfig::default().with_max_concurrency(2);
        let introspector = ConcurrentIntrospector::new(config);

        let tables = vec!["good1".to_string(), "bad".to_string(), "good2".to_string()];

        let result = introspector
            .introspect_named(tables, |name| async move {
                if name == "bad" {
                    Err("Table not found".to_string())
                } else {
                    Ok(TableMetadata::new(name))
                }
            })
            .await;

        assert_eq!(result.tables.len(), 2);
        assert_eq!(result.errors.len(), 1);
        assert_eq!(result.errors[0].table, "bad");
    }

    #[test]
    fn test_introspection_phase_progression() {
        let mut phase = IntrospectionPhase::Tables;

        assert_eq!(phase.name(), "tables");

        phase = phase.next();
        assert_eq!(phase, IntrospectionPhase::Columns);

        phase = phase.next();
        assert_eq!(phase, IntrospectionPhase::PrimaryKeys);

        // Progress to complete
        while phase != IntrospectionPhase::Complete {
            phase = phase.next();
        }

        // Should stay at complete
        assert_eq!(phase.next(), IntrospectionPhase::Complete);
    }

    #[test]
    fn test_batch_columns_query() {
        let sql = queries::batch_columns_query(
            crate::sql::DatabaseType::PostgreSQL,
            &["users", "posts"],
            Some("public"),
        );

        assert!(sql.contains("information_schema.columns"));
        assert!(sql.contains("'users', 'posts'"));
    }
}