use sqlglot_rust::{Dialect, generate, parse, transpile};
fn validate_identity(sql: &str, dialect: Dialect) {
let ast =
parse(sql, dialect).unwrap_or_else(|e| panic!("Parse failed for '{}': {}", sql, e));
let output = generate(&ast, dialect);
assert_eq!(output, sql, "\n Identity roundtrip failed");
}
fn validate(sql: &str, expected: &str, dialect: Dialect) {
let ast =
parse(sql, dialect).unwrap_or_else(|e| panic!("Parse failed for '{}': {}", sql, e));
let output = generate(&ast, dialect);
assert_eq!(output, expected, "\n Input: {}", sql);
}
#[test]
fn test_double_quoted_select_alias_roundtrip() {
validate_identity(
r#"SELECT 7 AS "Mixed""#,
Dialect::Postgres,
);
}
#[test]
fn test_double_quoted_alias_in_subquery() {
validate_identity(
r#"SELECT "Mixed" FROM (SELECT 7 AS "Mixed") AS t"#,
Dialect::Postgres,
);
}
#[test]
fn test_double_quoted_alias_case_sensitive() {
validate(
r#"SELECT "Mixed" FROM (SELECT 7 AS "Mixed") t"#,
r#"SELECT "Mixed" FROM (SELECT 7 AS "Mixed") AS t"#,
Dialect::Postgres,
);
}
#[test]
fn test_cte_quoted_name_roundtrip() {
validate_identity(
r#"WITH "MyCte" AS (SELECT 1 AS "Val") SELECT "Val" FROM "MyCte""#,
Dialect::Postgres,
);
}
#[test]
fn test_reserved_word_quoted_alias() {
validate(
r#"SELECT count(*) AS "order" FROM orders"#,
r#"SELECT COUNT(*) AS "order" FROM orders"#,
Dialect::Postgres,
);
}
#[test]
fn test_mixed_quoted_and_unquoted_aliases() {
validate_identity(
r#"SELECT a AS "First", b AS second FROM t"#,
Dialect::Postgres,
);
}
#[test]
fn test_table_alias_quoted_roundtrip() {
validate_identity(
r#"SELECT "t"."Col" FROM my_table AS "t""#,
Dialect::Postgres,
);
}
#[test]
fn test_subquery_alias_quoted_roundtrip() {
validate_identity(
r#"SELECT * FROM (SELECT 1) AS "sub query""#,
Dialect::Postgres,
);
}
#[test]
fn test_cross_dialect_pg_to_mysql_alias() {
let result = transpile(
r#"SELECT 7 AS "Mixed""#,
Dialect::Postgres,
Dialect::Mysql,
)
.unwrap();
assert_eq!(result, "SELECT 7 AS `Mixed`");
}
#[test]
fn test_cross_dialect_pg_to_tsql_alias() {
let result = transpile(
r#"SELECT 7 AS "Mixed""#,
Dialect::Postgres,
Dialect::Tsql,
)
.unwrap();
assert_eq!(result, "SELECT 7 AS [Mixed]");
}
#[test]
fn test_unquoted_aliases_unchanged() {
validate_identity(
"SELECT 1 AS foo, 2 AS bar FROM t AS x",
Dialect::Ansi,
);
}
#[test]
fn test_backtick_alias_roundtrip_mysql() {
validate_identity(
"SELECT 1 AS `Mixed`",
Dialect::Mysql,
);
}
#[test]
fn test_backtick_to_doublequote_mysql_to_pg() {
let result = transpile(
"SELECT 1 AS `Mixed`",
Dialect::Mysql,
Dialect::Postgres,
)
.unwrap();
assert_eq!(result, r#"SELECT 1 AS "Mixed""#);
}
#[test]
fn test_implicit_quoted_alias() {
validate(
r#"SELECT 1 "MyAlias""#,
r#"SELECT 1 AS "MyAlias""#,
Dialect::Postgres,
);
}