Translates PRQL date truncation to dialect-specific SQL. BigQuery uses unquoted uppercase date_part after the column: DATE_TRUNC(col, DAY) MSSQL uses unquoted lowercase datepart before the column: DATETRUNC(day, col) All other dialects use: DATE_TRUNC('unit', col)
(
expr: &rq::Expr,
op_name: &str,
args: &[rq::Expr],
ctx: &mut Context,
)
| 214 | /// MSSQL uses unquoted lowercase datepart before the column: DATETRUNC(day, col) |
| 215 | /// All other dialects use: DATE_TRUNC('unit', col) |
| 216 | fn process_date_trunc( |
| 217 | expr: &rq::Expr, |
| 218 | op_name: &str, |
| 219 | args: &[rq::Expr], |
| 220 | ctx: &mut Context, |
| 221 | ) -> Result<sql_ast::Expr> { |
| 222 | if let [unit_expr @ rq::Expr { |
| 223 | kind: rq::ExprKind::Literal(Literal::String(unit)), |
| 224 | .. |
| 225 | }, col_expr] = args |
| 226 | { |
| 227 | use crate::sql::dialect::{BigQueryDialect, MsSqlDialect}; |
| 228 | |
| 229 | if ctx.dialect.is::<BigQueryDialect>() { |
| 230 | // BigQuery: DATE_TRUNC(col, DAY) — unit is an unquoted uppercase keyword |
| 231 | let col = translate_expr(col_expr.clone(), ctx)?.into_ast(); |
| 232 | let unit_upper = unit.to_uppercase(); |
| 233 | return Ok(sql_ast::Expr::Function(Function { |
| 234 | name: ObjectName(vec![sqlparser::ast::ObjectNamePart::Identifier( |
| 235 | sql_ast::Ident::new("DATE_TRUNC"), |
| 236 | )]), |
| 237 | args: sql_ast::FunctionArguments::List(FunctionArgumentList { |
| 238 | args: vec![ |
| 239 | FunctionArg::Unnamed(FunctionArgExpr::Expr(col)), |
| 240 | FunctionArg::Unnamed(FunctionArgExpr::Expr(sql_ast::Expr::Identifier( |
| 241 | sql_ast::Ident::new(unit_upper), |
| 242 | ))), |
| 243 | ], |
| 244 | clauses: vec![], |
| 245 | duplicate_treatment: None, |
| 246 | }), |
| 247 | over: None, |
| 248 | filter: None, |
| 249 | null_treatment: None, |
| 250 | within_group: vec![], |
| 251 | parameters: sql_ast::FunctionArguments::None, |
| 252 | uses_odbc_syntax: false, |
| 253 | })); |
| 254 | } else if ctx.dialect.is::<MsSqlDialect>() { |
| 255 | // MSSQL: DATETRUNC(day, col) — unit is an unquoted lowercase keyword (SQL Server 2022+) |
| 256 | let col = translate_expr(col_expr.clone(), ctx)?.into_ast(); |
| 257 | let unit_lower = unit.to_lowercase(); |
| 258 | return Ok(sql_ast::Expr::Function(Function { |
| 259 | name: ObjectName(vec![sqlparser::ast::ObjectNamePart::Identifier( |
| 260 | sql_ast::Ident::new("DATETRUNC"), |
| 261 | )]), |
| 262 | args: sql_ast::FunctionArguments::List(FunctionArgumentList { |
| 263 | args: vec![ |
| 264 | FunctionArg::Unnamed(FunctionArgExpr::Expr(sql_ast::Expr::Identifier( |
| 265 | sql_ast::Ident::new(unit_lower), |
| 266 | ))), |
| 267 | FunctionArg::Unnamed(FunctionArgExpr::Expr(col)), |
| 268 | ], |
| 269 | clauses: vec![], |
| 270 | duplicate_treatment: None, |
| 271 | }), |
| 272 | over: None, |
| 273 | filter: None, |
no test coverage detected