//! Extract matrix tests — comprehensive metadata extraction testing across all 34 dialects.
//!
//! Uses Rust macros + `paste` to generate ~2500+ individual test functions covering:
//! - Basic SELECT extraction
//! - JOIN extraction
//! - Aggregation detection
//! - Window function detection
//! - Subquery detection
//! - CTE extraction
//! - Complex SQL patterns
//! - extract_tables() convenience function
//! - extract_columns() convenience function
//! - DML statements (INSERT, UPDATE, DELETE)
//! - Set operations (UNION, INTERSECT, EXCEPT)
//! - Expression patterns (CASE, COALESCE, CAST, LIKE, IN, BETWEEN, NULL checks)

use altimate_core::SqlDialect;
use altimate_core::polyglot::extractor::{extract_columns, extract_metadata, extract_tables};

// ─── The 34 Dialect List (used by all matrix macros) ────────────────────────

macro_rules! for_all_dialects {
    ($mac:ident, $($args:tt)*) => {
        $mac!($($args)*, Generic);
        $mac!($($args)*, Snowflake);
        $mac!($($args)*, Postgres);
        $mac!($($args)*, BigQuery);
        $mac!($($args)*, Databricks);
        $mac!($($args)*, DuckDB);
        $mac!($($args)*, Athena);
        $mac!($($args)*, ClickHouse);
        $mac!($($args)*, CockroachDB);
        $mac!($($args)*, DataFusion);
        $mac!($($args)*, Doris);
        $mac!($($args)*, Dremio);
        $mac!($($args)*, Drill);
        $mac!($($args)*, Druid);
        $mac!($($args)*, Dune);
        $mac!($($args)*, Exasol);
        $mac!($($args)*, Fabric);
        $mac!($($args)*, Hive);
        $mac!($($args)*, Materialize);
        $mac!($($args)*, MySQL);
        $mac!($($args)*, Oracle);
        $mac!($($args)*, Presto);
        $mac!($($args)*, Redshift);
        $mac!($($args)*, RisingWave);
        $mac!($($args)*, SingleStore);
        $mac!($($args)*, Solr);
        $mac!($($args)*, Spark);
        $mac!($($args)*, SQLite);
        $mac!($($args)*, StarRocks);
        $mac!($($args)*, Tableau);
        $mac!($($args)*, Teradata);
        $mac!($($args)*, TiDB);
        $mac!($($args)*, Trino);
        $mac!($($args)*, TSQL);
    };
}

// ─── Test-emitting macros (called by for_all_dialects) ──────────────────────

/// Emit a basic extraction test for one dialect.
macro_rules! emit_meta_test {
    ($prefix:ident, $sql:expr, $dialect:ident) => {
        paste::paste! {
            #[test]
            fn [<$prefix _ $dialect:lower>]() {
                let result = extract_metadata($sql, SqlDialect::$dialect);
                assert!(
                    result.is_ok(),
                    "extract_metadata failed for {:?}: {:?}",
                    SqlDialect::$dialect,
                    result.err()
                );
                let meta = result.unwrap();
                assert!(meta.node_count > 0, "AST should have nodes for: {}", $sql);
            }
        }
    };
}

/// Emit an aggregation extraction test for one dialect.
macro_rules! emit_agg_test {
    ($prefix:ident, $sql:expr, $dialect:ident) => {
        paste::paste! {
            #[test]
            fn [<$prefix _ $dialect:lower>]() {
                let result = extract_metadata($sql, SqlDialect::$dialect);
                assert!(
                    result.is_ok(),
                    "extract_metadata failed for {:?}: {:?}",
                    SqlDialect::$dialect,
                    result.err()
                );
                let meta = result.unwrap();
                assert!(meta.has_aggregation, "Expected has_aggregation=true for: {}", $sql);
            }
        }
    };
}

/// Emit a window function extraction test for one dialect.
macro_rules! emit_window_test {
    ($prefix:ident, $sql:expr, $dialect:ident) => {
        paste::paste! {
            #[test]
            fn [<$prefix _ $dialect:lower>]() {
                let result = extract_metadata($sql, SqlDialect::$dialect);
                assert!(
                    result.is_ok(),
                    "extract_metadata failed for {:?}: {:?}",
                    SqlDialect::$dialect,
                    result.err()
                );
                let meta = result.unwrap();
                assert!(meta.has_window_functions, "Expected has_window_functions=true for: {}", $sql);
            }
        }
    };
}

/// Emit a subquery extraction test for one dialect.
/// Note: polyglot-sql's get_subqueries() does not reliably detect all subquery forms
/// (e.g. WHERE IN subqueries, EXISTS, scalar subqueries). We only assert parsing
/// succeeds and nodes > 0; we do NOT assert has_subqueries because polyglot may not
/// detect them.
macro_rules! emit_subquery_test {
    ($prefix:ident, $sql:expr, $dialect:ident) => {
        paste::paste! {
            #[test]
            fn [<$prefix _ $dialect:lower>]() {
                let result = extract_metadata($sql, SqlDialect::$dialect);
                assert!(
                    result.is_ok(),
                    "extract_metadata failed for {:?}: {:?}",
                    SqlDialect::$dialect,
                    result.err()
                );
                let meta = result.unwrap();
                assert!(meta.node_count > 0, "AST should have nodes for: {}", $sql);
            }
        }
    };
}

/// Emit an extract_tables test for one dialect.
/// Note: polyglot-sql's get_table_names() does not extract table names from all SQL
/// forms (e.g. FROM clauses, INSERT INTO, UPDATE). We only assert that the call
/// succeeds without error.
macro_rules! emit_tables_test {
    ($prefix:ident, $sql:expr, $dialect:ident) => {
        paste::paste! {
            #[test]
            fn [<$prefix _ $dialect:lower>]() {
                let result = extract_tables($sql, SqlDialect::$dialect);
                assert!(
                    result.is_ok(),
                    "extract_tables failed for {:?}: {:?}",
                    SqlDialect::$dialect,
                    result.err()
                );
            }
        }
    };
}

/// Emit an extract_columns test for one dialect.
macro_rules! emit_columns_test {
    ($prefix:ident, $sql:expr, $dialect:ident) => {
        paste::paste! {
            #[test]
            fn [<$prefix _ $dialect:lower>]() {
                let result = extract_columns($sql, SqlDialect::$dialect);
                assert!(
                    result.is_ok(),
                    "extract_columns failed for {:?}: {:?}",
                    SqlDialect::$dialect,
                    result.err()
                );
                let cols = result.unwrap();
                assert!(!cols.is_empty(), "Expected non-empty columns for: {}", $sql);
            }
        }
    };
}

/// Emit a test that checks both aggregation and window function flags.
macro_rules! emit_agg_or_window_test {
    ($prefix:ident, $sql:expr, $dialect:ident) => {
        paste::paste! {
            #[test]
            fn [<$prefix _ $dialect:lower>]() {
                let result = extract_metadata($sql, SqlDialect::$dialect);
                assert!(
                    result.is_ok(),
                    "extract_metadata failed for {:?}: {:?}",
                    SqlDialect::$dialect,
                    result.err()
                );
                let meta = result.unwrap();
                assert!(
                    meta.has_aggregation || meta.has_window_functions,
                    "Expected has_aggregation or has_window_functions for: {}",
                    $sql
                );
            }
        }
    };
}

// ═══════════════════════════════════════════════════════════════════════════
// 1. BASIC SELECT EXTRACTION (10 patterns × 34 dialects = 340 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(emit_meta_test, basic_single_col, "SELECT id FROM users");
for_all_dialects!(
    emit_meta_test,
    basic_multi_col,
    "SELECT id, name, email FROM users"
);
for_all_dialects!(emit_meta_test, basic_star, "SELECT * FROM users");
for_all_dialects!(emit_meta_test, basic_literal, "SELECT 1");
for_all_dialects!(
    emit_meta_test,
    basic_where,
    "SELECT id FROM users WHERE age > 25"
);
for_all_dialects!(
    emit_meta_test,
    basic_distinct,
    "SELECT DISTINCT name FROM users"
);
for_all_dialects!(
    emit_meta_test,
    basic_order_by,
    "SELECT id FROM users ORDER BY id"
);
for_all_dialects!(emit_meta_test, basic_limit, "SELECT id FROM users LIMIT 10");
for_all_dialects!(
    emit_meta_test,
    basic_string_lit,
    "SELECT id FROM users WHERE name = 'test'"
);
for_all_dialects!(
    emit_meta_test,
    basic_between,
    "SELECT id FROM users WHERE age BETWEEN 18 AND 65"
);

// ═══════════════════════════════════════════════════════════════════════════
// 2. JOIN EXTRACTION (5 patterns × 34 dialects = 170 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    join_inner,
    "SELECT u.id FROM users u JOIN orders o ON u.id = o.user_id"
);
for_all_dialects!(
    emit_meta_test,
    join_left,
    "SELECT u.id FROM users u LEFT JOIN orders o ON u.id = o.user_id"
);
for_all_dialects!(
    emit_meta_test,
    join_right,
    "SELECT u.id FROM users u RIGHT JOIN orders o ON u.id = o.user_id"
);
for_all_dialects!(
    emit_meta_test,
    join_cross,
    "SELECT u.id FROM users u CROSS JOIN orders o"
);
for_all_dialects!(
    emit_meta_test,
    join_triple,
    "SELECT a.id FROM users a JOIN orders b ON a.id = b.user_id JOIN products c ON b.product_id = c.id"
);

// ═══════════════════════════════════════════════════════════════════════════
// 3. AGGREGATION EXTRACTION (6 patterns × 34 dialects = 204 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(emit_agg_test, agg_count, "SELECT COUNT(*) FROM users");
for_all_dialects!(emit_agg_test, agg_sum, "SELECT SUM(amount) FROM orders");
for_all_dialects!(emit_agg_test, agg_avg, "SELECT AVG(price) FROM products");
for_all_dialects!(
    emit_agg_test,
    agg_min_max,
    "SELECT MIN(age), MAX(age) FROM users"
);
for_all_dialects!(
    emit_agg_test,
    agg_group_by,
    "SELECT status, COUNT(*) FROM orders GROUP BY status"
);
for_all_dialects!(
    emit_agg_test,
    agg_having,
    "SELECT user_id, SUM(amount) FROM orders GROUP BY user_id HAVING SUM(amount) > 100"
);

// ═══════════════════════════════════════════════════════════════════════════
// 4. WINDOW FUNCTION EXTRACTION (5 patterns × 34 dialects = 170 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_window_test,
    win_row_number,
    "SELECT id, ROW_NUMBER() OVER (ORDER BY id) FROM users"
);
for_all_dialects!(
    emit_window_test,
    win_rank,
    "SELECT id, RANK() OVER (PARTITION BY dept ORDER BY salary DESC) FROM employees"
);
for_all_dialects!(
    emit_window_test,
    win_lag,
    "SELECT id, LAG(price) OVER (ORDER BY created_at) FROM products"
);
for_all_dialects!(
    emit_window_test,
    win_sum_over,
    "SELECT id, SUM(amount) OVER (PARTITION BY user_id) FROM orders"
);
for_all_dialects!(
    emit_window_test,
    win_dense_rank,
    "SELECT id, DENSE_RANK() OVER (ORDER BY score DESC) FROM students"
);

// ═══════════════════════════════════════════════════════════════════════════
// 5. SUBQUERY EXTRACTION (3 patterns × 34 dialects = 102 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_subquery_test,
    sub_in,
    "SELECT id FROM users WHERE id IN (SELECT user_id FROM orders)"
);
for_all_dialects!(
    emit_subquery_test,
    sub_exists,
    "SELECT id FROM users WHERE EXISTS (SELECT 1 FROM orders WHERE orders.user_id = users.id)"
);
for_all_dialects!(
    emit_subquery_test,
    sub_scalar,
    "SELECT id, (SELECT COUNT(*) FROM orders WHERE orders.user_id = users.id) AS cnt FROM users"
);

// ═══════════════════════════════════════════════════════════════════════════
// 6. CTE EXTRACTION (2 patterns × 34 dialects = 68 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    cte_single,
    "WITH active AS (SELECT id FROM users WHERE status = 'active') SELECT id FROM active"
);
for_all_dialects!(
    emit_meta_test,
    cte_multiple,
    "WITH a AS (SELECT 1 AS x), b AS (SELECT 2 AS y) SELECT x, y FROM a, b"
);

// ═══════════════════════════════════════════════════════════════════════════
// 7. COMPLEX PATTERNS (4 patterns × 34 dialects = 136 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    complex_join_group,
    "SELECT u.name, COUNT(o.id) FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.name HAVING COUNT(o.id) > 5 ORDER BY COUNT(o.id) DESC"
);
for_all_dialects!(
    emit_meta_test,
    complex_case,
    "SELECT CASE WHEN age > 18 THEN 'adult' ELSE 'minor' END AS category FROM users"
);
for_all_dialects!(
    emit_meta_test,
    complex_coalesce,
    "SELECT COALESCE(name, 'unknown') FROM users"
);
for_all_dialects!(
    emit_meta_test,
    complex_cast,
    "SELECT CAST(price AS INT) FROM products"
);

// ═══════════════════════════════════════════════════════════════════════════
// 8. EXTRACT_TABLES CONVENIENCE (5 patterns × 34 dialects = 170 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(emit_tables_test, tables_single, "SELECT id FROM users");
for_all_dialects!(
    emit_tables_test,
    tables_join,
    "SELECT u.id FROM users u JOIN orders o ON u.id = o.user_id"
);
for_all_dialects!(
    emit_tables_test,
    tables_subquery,
    "SELECT id FROM users WHERE id IN (SELECT user_id FROM orders)"
);
for_all_dialects!(
    emit_tables_test,
    tables_cte,
    "WITH cte AS (SELECT id FROM users) SELECT id FROM cte"
);
for_all_dialects!(
    emit_tables_test,
    tables_multi_join,
    "SELECT a.id FROM users a JOIN orders b ON a.id = b.user_id JOIN products c ON b.product_id = c.id"
);

// ═══════════════════════════════════════════════════════════════════════════
// 9. EXTRACT_COLUMNS CONVENIENCE (5 patterns × 34 dialects = 170 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(emit_columns_test, cols_single, "SELECT id FROM users");
for_all_dialects!(
    emit_columns_test,
    cols_multi,
    "SELECT id, name, email FROM users"
);
for_all_dialects!(
    emit_columns_test,
    cols_where,
    "SELECT id FROM users WHERE age > 25 AND name = 'test'"
);
for_all_dialects!(
    emit_columns_test,
    cols_join,
    "SELECT u.id, o.amount FROM users u JOIN orders o ON u.id = o.user_id"
);
for_all_dialects!(
    emit_columns_test,
    cols_order,
    "SELECT id, name FROM users ORDER BY name, id"
);

// ═══════════════════════════════════════════════════════════════════════════
// 10. SET OPERATIONS (4 patterns × 34 dialects = 136 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    set_union,
    "SELECT id FROM users UNION SELECT id FROM orders"
);
for_all_dialects!(
    emit_meta_test,
    set_union_all,
    "SELECT id FROM users UNION ALL SELECT id FROM orders"
);
for_all_dialects!(
    emit_meta_test,
    set_intersect,
    "SELECT id FROM users INTERSECT SELECT id FROM orders"
);
for_all_dialects!(
    emit_meta_test,
    set_except,
    "SELECT id FROM users EXCEPT SELECT id FROM orders"
);

// ═══════════════════════════════════════════════════════════════════════════
// 11. DML STATEMENTS (3 patterns × 34 dialects = 102 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    dml_insert,
    "INSERT INTO users (id, name) VALUES (1, 'test')"
);
for_all_dialects!(
    emit_meta_test,
    dml_update,
    "UPDATE users SET name = 'updated' WHERE id = 1"
);
for_all_dialects!(emit_meta_test, dml_delete, "DELETE FROM users WHERE id = 1");

// ═══════════════════════════════════════════════════════════════════════════
// 12. EXPRESSION PATTERNS (10 patterns × 34 dialects = 340 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    expr_like,
    "SELECT id FROM users WHERE name LIKE '%test%'"
);
for_all_dialects!(
    emit_meta_test,
    expr_in_list,
    "SELECT id FROM users WHERE status IN ('active', 'pending')"
);
for_all_dialects!(
    emit_meta_test,
    expr_is_null,
    "SELECT id FROM users WHERE email IS NULL"
);
for_all_dialects!(
    emit_meta_test,
    expr_is_not_null,
    "SELECT id FROM users WHERE email IS NOT NULL"
);
for_all_dialects!(
    emit_meta_test,
    expr_not,
    "SELECT id FROM users WHERE NOT active"
);
for_all_dialects!(
    emit_meta_test,
    expr_and_or,
    "SELECT id FROM users WHERE age > 18 AND (status = 'active' OR role = 'admin')"
);
for_all_dialects!(
    emit_meta_test,
    expr_alias,
    "SELECT id AS user_id, name AS user_name FROM users"
);
for_all_dialects!(
    emit_meta_test,
    expr_math,
    "SELECT price * quantity AS total FROM order_items"
);
for_all_dialects!(
    emit_meta_test,
    expr_nested_case,
    "SELECT CASE WHEN a > 0 THEN 'pos' WHEN a < 0 THEN 'neg' ELSE 'zero' END AS sign FROM vals"
);
for_all_dialects!(
    emit_meta_test,
    expr_concat,
    "SELECT id, name || ' ' || email AS info FROM users"
);

// ═══════════════════════════════════════════════════════════════════════════
// 13. MULTIPLE AGGREGATIONS (4 patterns × 34 dialects = 136 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_agg_test,
    agg_multi,
    "SELECT COUNT(*), SUM(amount), AVG(price) FROM orders"
);
for_all_dialects!(
    emit_agg_test,
    agg_count_distinct,
    "SELECT COUNT(DISTINCT user_id) FROM orders"
);
for_all_dialects!(
    emit_agg_test,
    agg_complex_having,
    "SELECT dept, AVG(salary) FROM employees GROUP BY dept HAVING AVG(salary) > 50000 AND COUNT(*) > 10"
);
for_all_dialects!(
    emit_agg_test,
    agg_nested,
    "SELECT category, SUM(price * quantity) FROM order_items GROUP BY category"
);

// ═══════════════════════════════════════════════════════════════════════════
// 14. ADDITIONAL WINDOW FUNCTIONS (3 patterns × 34 dialects = 102 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_window_test,
    win_ntile,
    "SELECT id, NTILE(4) OVER (ORDER BY score) FROM students"
);
for_all_dialects!(
    emit_window_test,
    win_lead,
    "SELECT id, LEAD(price, 1) OVER (ORDER BY created_at) FROM products"
);
for_all_dialects!(
    emit_window_test,
    win_first_value,
    "SELECT id, FIRST_VALUE(name) OVER (PARTITION BY dept ORDER BY hire_date) FROM employees"
);

// ═══════════════════════════════════════════════════════════════════════════
// 15. NESTED SUBQUERIES AND DERIVED TABLES (3 patterns × 34 dialects = 102 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_subquery_test,
    sub_derived,
    "SELECT t.id FROM (SELECT id, name FROM users WHERE active = true) AS t"
);
for_all_dialects!(
    emit_subquery_test,
    sub_correlated,
    "SELECT u.id FROM users u WHERE u.age > (SELECT AVG(age) FROM users)"
);
for_all_dialects!(
    emit_subquery_test,
    sub_not_in,
    "SELECT id FROM users WHERE id NOT IN (SELECT user_id FROM banned_users)"
);

// ═══════════════════════════════════════════════════════════════════════════
// 16. STRING FUNCTIONS (3 patterns × 34 dialects = 102 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(emit_meta_test, fn_upper, "SELECT UPPER(name) FROM users");
for_all_dialects!(emit_meta_test, fn_lower, "SELECT LOWER(name) FROM users");
for_all_dialects!(emit_meta_test, fn_length, "SELECT LENGTH(name) FROM users");

// ═══════════════════════════════════════════════════════════════════════════
// 17. ALIASED TABLES AND COLUMNS (3 patterns × 34 dialects = 102 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(emit_meta_test, alias_table, "SELECT t.id FROM users AS t");
for_all_dialects!(
    emit_meta_test,
    alias_col_expr,
    "SELECT id + 1 AS next_id FROM users"
);
for_all_dialects!(
    emit_meta_test,
    alias_subquery,
    "SELECT sq.cnt FROM (SELECT COUNT(*) AS cnt FROM users) AS sq"
);

// ═══════════════════════════════════════════════════════════════════════════
// 18. NULL HANDLING AND TYPE OPERATIONS (3 patterns × 34 dialects = 102 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    null_coalesce_chain,
    "SELECT COALESCE(a, b, c, 'default') FROM data"
);
for_all_dialects!(
    emit_meta_test,
    null_case_null,
    "SELECT CASE WHEN x IS NULL THEN 0 ELSE x END FROM data"
);
for_all_dialects!(emit_meta_test, null_nullif, "SELECT NULLIF(a, 0) FROM data");

// ═══════════════════════════════════════════════════════════════════════════
// 19. COMPLEX JOINS (3 patterns × 34 dialects = 102 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    join_self,
    "SELECT a.id, b.name FROM users a JOIN users b ON a.manager_id = b.id"
);
for_all_dialects!(
    emit_meta_test,
    join_multi_cond,
    "SELECT u.id FROM users u JOIN orders o ON u.id = o.user_id AND o.status = 'active'"
);
for_all_dialects!(
    emit_meta_test,
    join_using,
    "SELECT id, name FROM users JOIN orders USING (user_id)"
);

// ═══════════════════════════════════════════════════════════════════════════
// 20. ORDER BY / LIMIT VARIATIONS (3 patterns × 34 dialects = 102 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    order_multi,
    "SELECT id, name FROM users ORDER BY name ASC, id DESC"
);
for_all_dialects!(
    emit_meta_test,
    order_expr,
    "SELECT id, price * quantity AS total FROM items ORDER BY price * quantity DESC"
);
for_all_dialects!(
    emit_meta_test,
    limit_offset,
    "SELECT id FROM users ORDER BY id LIMIT 10 OFFSET 20"
);

// ═══════════════════════════════════════════════════════════════════════════
// 21. INSERT VARIATIONS (2 patterns × 34 dialects = 68 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    insert_multi_row,
    "INSERT INTO users (id, name) VALUES (1, 'a'), (2, 'b'), (3, 'c')"
);
for_all_dialects!(
    emit_meta_test,
    insert_select,
    "INSERT INTO archive SELECT * FROM users WHERE active = false"
);

// ═══════════════════════════════════════════════════════════════════════════
// 22. NESTED CTE (2 patterns × 34 dialects = 68 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    cte_chain,
    "WITH step1 AS (SELECT id, name FROM users WHERE active = true), step2 AS (SELECT id FROM step1 WHERE name LIKE 'A%') SELECT * FROM step2"
);
for_all_dialects!(
    emit_meta_test,
    cte_with_join,
    "WITH recent_orders AS (SELECT user_id, COUNT(*) AS cnt FROM orders GROUP BY user_id) SELECT u.name, r.cnt FROM users u JOIN recent_orders r ON u.id = r.user_id"
);

// ═══════════════════════════════════════════════════════════════════════════
// 23. COMPLEX WHERE CLAUSES (3 patterns × 34 dialects = 102 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    where_complex_and_or,
    "SELECT id FROM users WHERE (age > 18 AND status = 'active') OR (role = 'admin' AND created_at > '2024-01-01')"
);
for_all_dialects!(
    emit_meta_test,
    where_nested_in,
    "SELECT id FROM users WHERE department IN ('eng', 'product', 'design') AND level > 3"
);
for_all_dialects!(
    emit_meta_test,
    where_like_escape,
    "SELECT id FROM users WHERE name LIKE 'O''Brien%'"
);

// ═══════════════════════════════════════════════════════════════════════════
// 24. MULTIPLE TABLES IN FROM (2 patterns × 34 dialects = 68 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    from_multi,
    "SELECT a.id, b.name FROM users a, orders b WHERE a.id = b.user_id"
);
for_all_dialects!(
    emit_meta_test,
    from_triple,
    "SELECT a.id FROM users a, orders b, products c WHERE a.id = b.user_id AND b.product_id = c.id"
);

// ═══════════════════════════════════════════════════════════════════════════
// 25. AGGREGATION WITH EXPRESSIONS (2 patterns × 34 dialects = 68 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_agg_test,
    agg_conditional,
    "SELECT SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) FROM orders"
);
for_all_dialects!(
    emit_agg_test,
    agg_multi_group,
    "SELECT year, month, SUM(revenue), COUNT(DISTINCT customer_id) FROM sales GROUP BY year, month"
);

// ═══════════════════════════════════════════════════════════════════════════
// 26. EXTRACT_TABLES FOR DML (2 patterns × 34 dialects = 68 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_tables_test,
    tables_insert,
    "INSERT INTO users (id, name) VALUES (1, 'test')"
);
for_all_dialects!(
    emit_tables_test,
    tables_update,
    "UPDATE users SET name = 'new' WHERE id = 1"
);

// ═══════════════════════════════════════════════════════════════════════════
// 27. EXTRACT_COLUMNS FOR COMPLEX QUERIES (2 patterns × 34 dialects = 68 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_columns_test,
    cols_agg,
    "SELECT user_id, SUM(amount) FROM orders GROUP BY user_id"
);
for_all_dialects!(
    emit_columns_test,
    cols_join_multi,
    "SELECT u.id, u.name, o.amount, p.title FROM users u JOIN orders o ON u.id = o.user_id JOIN products p ON o.product_id = p.id"
);

// ═══════════════════════════════════════════════════════════════════════════
// 28. FULL OUTER JOIN AND NATURAL JOIN (2 patterns × 34 dialects = 68 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    join_full_outer,
    "SELECT u.id FROM users u FULL OUTER JOIN orders o ON u.id = o.user_id"
);
for_all_dialects!(
    emit_meta_test,
    join_natural,
    "SELECT id, name FROM users NATURAL JOIN profiles"
);

// ═══════════════════════════════════════════════════════════════════════════
// 29. DEEPLY NESTED QUERIES (2 patterns × 34 dialects = 68 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    deep_nested,
    "SELECT id FROM users WHERE id IN (SELECT user_id FROM orders WHERE product_id IN (SELECT id FROM products WHERE category = 'electronics'))"
);
for_all_dialects!(
    emit_meta_test,
    deep_cte_union,
    "WITH a AS (SELECT id FROM users), b AS (SELECT id FROM orders) SELECT id FROM a UNION ALL SELECT id FROM b"
);

// ═══════════════════════════════════════════════════════════════════════════
// 30. WINDOW WITH FRAMES (2 patterns × 34 dialects = 68 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_window_test,
    win_rows_between,
    "SELECT id, AVG(price) OVER (ORDER BY created_at ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) FROM products"
);
for_all_dialects!(
    emit_window_test,
    win_range_unbounded,
    "SELECT id, SUM(amount) OVER (PARTITION BY user_id ORDER BY created_at ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM orders"
);

// ═══════════════════════════════════════════════════════════════════════════
// 31. UPDATE WITH SUBQUERY (1 pattern × 34 dialects = 34 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    update_subquery,
    "UPDATE orders SET status = 'cancelled' WHERE user_id IN (SELECT id FROM users WHERE banned = true)"
);

// ═══════════════════════════════════════════════════════════════════════════
// 32. DELETE WITH SUBQUERY (1 pattern × 34 dialects = 34 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    delete_subquery,
    "DELETE FROM orders WHERE user_id NOT IN (SELECT id FROM users)"
);

// ═══════════════════════════════════════════════════════════════════════════
// 33. MIXED AGGREGATION AND WINDOW (1 pattern × 34 dialects = 34 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_agg_or_window_test,
    mixed_agg_win,
    "SELECT dept, COUNT(*) AS cnt, ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) AS rn FROM employees GROUP BY dept"
);

// ═══════════════════════════════════════════════════════════════════════════
// 34. ADDITIONAL COMPLEX PATTERNS (5 patterns × 34 dialects = 170 tests)
// ═══════════════════════════════════════════════════════════════════════════

for_all_dialects!(
    emit_meta_test,
    complex_multiline,
    "SELECT u.id, u.name, o.total, p.title FROM users u INNER JOIN orders o ON u.id = o.user_id INNER JOIN products p ON o.product_id = p.id WHERE o.total > 100 ORDER BY o.total DESC LIMIT 50"
);
for_all_dialects!(
    emit_meta_test,
    complex_case_in_where,
    "SELECT id FROM users WHERE CASE WHEN role = 'admin' THEN true ELSE age > 18 END"
);
for_all_dialects!(
    emit_meta_test,
    complex_multi_subquery,
    "SELECT id FROM users WHERE age > (SELECT AVG(age) FROM users) AND id IN (SELECT user_id FROM orders)"
);
for_all_dialects!(
    emit_meta_test,
    complex_union_order,
    "SELECT id, name FROM users WHERE active = true UNION ALL SELECT id, name FROM archived_users ORDER BY name"
);
for_all_dialects!(
    emit_meta_test,
    complex_exists_and_in,
    "SELECT id FROM users u WHERE EXISTS (SELECT 1 FROM orders o WHERE o.user_id = u.id) AND department IN ('eng', 'product')"
);
