diff --git a/CHANGELOG.md b/CHANGELOG.md index 07d2a7e39e0d..a3515a6f589d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,10 @@ **Fixes**: +- On the `sql.oracle` target, `date.trunc` compiles to `TRUNC`, `date.to_text` + to `TO_CHAR`, timestamp literals use a space, and intervals are quoted with a + leading precision where needed; `date.diff` and time literals are reported as + unsupported. (@calin2k, #6455) - `first` and `last` respect the window frame: an explicit `window rows:...` was previously dropped, and `last` inside `group (sort ...)` returned the current row's value rather than the group's last. (@prql-bot, #6435) diff --git a/prqlc/prqlc/src/sql/dialect.rs b/prqlc/prqlc/src/sql/dialect.rs index c0f05be1532c..39113657d886 100644 --- a/prqlc/prqlc/src/sql/dialect.rs +++ b/prqlc/prqlc/src/sql/dialect.rs @@ -781,6 +781,48 @@ impl DialectHandler for OracleDialect { fn table_alias_uses_as(&self) -> bool { false } + + // https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Format-Models.html + // Unlike Postgres's, Oracle's `FM` is a toggle for the rest of the format, + // so it's switched off again after the element it applies to. + fn translate_chrono_item(&self, item: Item) -> Result { + Ok(match item { + Item::Numeric(Numeric::Year, Pad::Zero) => "YYYY".to_string(), + Item::Numeric(Numeric::YearMod100, Pad::Zero) => "YY".to_string(), + Item::Numeric(Numeric::Month, Pad::None) => "FMMMFM".to_string(), + Item::Numeric(Numeric::Month, Pad::Zero) => "MM".to_string(), + Item::Numeric(Numeric::Day, Pad::None) => "FMDDFM".to_string(), + Item::Numeric(Numeric::Day, Pad::Zero) => "DD".to_string(), + Item::Numeric(Numeric::Hour, Pad::None) => "FMHH24FM".to_string(), + Item::Numeric(Numeric::Hour, Pad::Zero) => "HH24".to_string(), + Item::Numeric(Numeric::Hour12, Pad::Zero) => "HH12".to_string(), + Item::Numeric(Numeric::Minute, Pad::Zero) => "MI".to_string(), + Item::Numeric(Numeric::Second, Pad::Zero) => "SS".to_string(), + Item::Numeric(Numeric::Nanosecond, Pad::Zero) => "FF6".to_string(), // Microseconds + Item::Fixed(Fixed::ShortMonthName) => "Mon".to_string(), + // Long names are blank-padded to the longest name without `FM` + Item::Fixed(Fixed::LongMonthName) => "FMMonthFM".to_string(), + Item::Fixed(Fixed::ShortWeekdayName) => "Dy".to_string(), + Item::Fixed(Fixed::LongWeekdayName) => "FMDayFM".to_string(), + Item::Fixed(Fixed::UpperAmPm) => "AM".to_string(), + Item::Fixed(Fixed::RFC3339) => "YYYY-MM-DD\"T\"HH24:MI:SS.FF6\"Z\"".to_string(), + Item::Literal(literal) if literal.contains('"') => { + return Err(Error::new_simple( + "a double quote can't be part of a date format on Oracle", + )) + } + Item::Literal(literal) => { + // Text is quoted, so that it isn't read as format elements + if literal.chars().any(|c| c.is_ascii_alphanumeric()) { + format!("\"{literal}\"") + } else { + literal.replace('\'', "''") + } + } + Item::Space(spaces) => spaces.to_string(), + item => return Err(unsupported_format_specifier(&item, "Oracle")), + }) + } } #[cfg(test)] diff --git a/prqlc/prqlc/src/sql/gen_expr.rs b/prqlc/prqlc/src/sql/gen_expr.rs index 74e80307d5f4..e15e136bf610 100644 --- a/prqlc/prqlc/src/sql/gen_expr.rs +++ b/prqlc/prqlc/src/sql/gen_expr.rs @@ -224,7 +224,7 @@ fn process_date_trunc( .. }, col_expr] = args { - use crate::sql::dialect::{BigQueryDialect, MsSqlDialect}; + use crate::sql::dialect::{BigQueryDialect, MsSqlDialect, OracleDialect}; if ctx.dialect.is::() { // BigQuery: DATE_TRUNC(col, DAY) — unit is an unquoted uppercase keyword @@ -276,6 +276,46 @@ fn process_date_trunc( parameters: sql_ast::FunctionArguments::None, uses_odbc_syntax: false, })); + } else if ctx.dialect.is::() { + // Oracle: TRUNC(col, 'MM') — the unit is a datetime format model + let format = match unit.to_lowercase().as_str() { + "year" => "YYYY", + "quarter" => "Q", + "month" => "MM", + "week" => "IW", + "day" => "DD", + "hour" => "HH24", + "minute" => "MI", + _ => { + return Err(Error::new_simple(format!( + "`date.trunc` to `{unit}` is not supported on Oracle" + )) + .push_hint("supported units: year, quarter, month, week, day, hour, minute") + .with_span(unit_expr.span)) + } + }; + let col = translate_expr(col_expr.clone(), ctx)?.into_ast(); + return Ok(sql_ast::Expr::Function(Function { + name: ObjectName(vec![sqlparser::ast::ObjectNamePart::Identifier( + sql_ast::Ident::new("TRUNC"), + )]), + args: sql_ast::FunctionArguments::List(FunctionArgumentList { + args: vec![ + FunctionArg::Unnamed(FunctionArgExpr::Expr(col)), + FunctionArg::Unnamed(FunctionArgExpr::Expr(sql_ast::Expr::Value( + Value::SingleQuotedString(format.to_string()).into(), + ))), + ], + clauses: vec![], + duplicate_treatment: None, + }), + over: None, + filter: None, + null_treatment: None, + within_group: vec![], + parameters: sql_ast::FunctionArguments::None, + uses_odbc_syntax: false, + })); } // All other dialects: DATE_TRUNC('unit', col) via the s-string in std.sql.prql @@ -531,6 +571,18 @@ pub(super) fn translate_literal(l: Literal, ctx: &Context) -> Result sql_ast::Expr::Value(Value::Number(format!("{f:?}"), false).into()), Literal::Integer(i) => sql_ast::Expr::Value(Value::Number(format!("{i}"), false).into()), Literal::Date(value) => translate_datetime_literal(sql_ast::DataType::Date, value, ctx), + Literal::Time(_) if ctx.dialect.is::() => { + return Err(Error::new_simple( + "time literals are not supported on Oracle, which has no TIME type", + )) + } + Literal::Timestamp(value) if ctx.dialect.is::() => { + translate_datetime_literal( + sql_ast::DataType::Timestamp(None, sql_ast::TimezoneInfo::None), + oracle_timestamp(&value), + ctx, + ) + } Literal::Time(value) => translate_datetime_literal( sql_ast::DataType::Time(None, sql_ast::TimezoneInfo::None), value, @@ -541,6 +593,9 @@ pub(super) fn translate_literal(l: Literal, ctx: &Context) -> Result() => { + translate_oracle_interval(vau.n, &vau.unit)? + } Literal::ValueAndUnit(vau) => { let sql_parser_datetime = match vau.unit.as_str() { "years" => DateTimeField::Year, @@ -604,6 +659,86 @@ pub(super) fn translate_literal(l: Literal, ctx: &Context) -> Result String { + let re = Regex::new( + r"^(\d{4}-\d{2}-\d{2})[T ](\d{2})(:\d{2})?(:\d{2})?(\.\d+)?(Z|[+-]\d{2}:?\d{2})?$", + ) + .unwrap(); + let Some(c) = re.captures(value) else { + return value.replacen('T', " ", 1); + }; + let minutes = c.get(3).map_or(":00", |m| m.as_str()); + let seconds = c.get(4).map_or(":00", |m| m.as_str()); + let fraction = c.get(5).map_or("", |m| m.as_str()); + let offset = match c.get(6).map(|m| m.as_str()) { + None => String::new(), + Some("Z") => " +00:00".to_string(), + Some(o) => { + let o = o.replace(':', ""); + format!(" {}:{}", &o[..3], &o[3..]) + } + }; + format!("{} {}{minutes}{seconds}{fraction}{offset}", &c[1], &c[2]) +} + +/// Oracle's interval literals: `INTERVAL '3' DAY`. There's no week, millisecond +/// or microsecond field, so those become days and fractional seconds, and a +/// value of more than two digits needs a leading precision, `INTERVAL '100' +/// DAY(3)`. +/// +fn translate_oracle_interval(n: i64, unit: &str) -> Result { + let fraction = |n: i64, digits: u32| { + let scale = 10_i64.pow(digits); + let sign = if n < 0 { "-" } else { "" }; + let (whole, part) = (n.abs() / scale, n.abs() % scale); + let part = format!("{part:0width$}", width = digits as usize); + let part = part.trim_end_matches('0'); + if part.is_empty() { + format!("{sign}{whole}") + } else { + format!("{sign}{whole}.{part}") + } + }; + let (value, field) = match unit { + "years" => (n.to_string(), DateTimeField::Year), + "months" => (n.to_string(), DateTimeField::Month), + "weeks" => { + let days = n + .checked_mul(7) + .ok_or_else(|| Error::new_simple(format!("`{n}weeks` is too large an interval")))?; + (days.to_string(), DateTimeField::Day) + } + "days" => (n.to_string(), DateTimeField::Day), + "hours" => (n.to_string(), DateTimeField::Hour), + "minutes" => (n.to_string(), DateTimeField::Minute), + "seconds" => (n.to_string(), DateTimeField::Second), + "milliseconds" => (fraction(n, 3), DateTimeField::Second), + "microseconds" => (fraction(n, 6), DateTimeField::Second), + _ => { + return Err(Error::new_simple(format!( + "Unsupported interval unit: {unit}" + ))) + } + }; + let digits = value + .trim_start_matches('-') + .split('.') + .next() + .map_or(1, |whole| whole.len() as u64); + Ok(sql_ast::Expr::Interval(sqlparser::ast::Interval { + value: Box::new(sql_ast::Expr::Value( + Value::SingleQuotedString(value).into(), + )), + leading_field: Some(field), + // Oracle's default leading precision is 2 digits + leading_precision: (digits > 2).then_some(digits), + last_field: None, + fractional_seconds_precision: None, + })) +} + fn translate_datetime_literal( data_type: sql_ast::DataType, value: String, @@ -1329,6 +1464,17 @@ mod test { use super::*; + #[test] + fn test_oracle_timestamp_unknown_form_only_replaces_the_t() { + // the lexer doesn't produce this, but nothing is dropped if it does + assert_eq!(oracle_timestamp("2025-01-01T08x"), "2025-01-01 08x"); + } + + #[test] + fn test_oracle_interval_unknown_unit() { + assert!(translate_oracle_interval(1, "fortnights").is_err()); + } + #[test] fn test_range_of_ranges() -> Result<()> { fn from_ints(start: Option, end: Option) -> Range { diff --git a/prqlc/prqlc/src/sql/std.sql.prql b/prqlc/prqlc/src/sql/std.sql.prql index ab4e0fead528..748ca0511880 100644 --- a/prqlc/prqlc/src/sql/std.sql.prql +++ b/prqlc/prqlc/src/sql/std.sql.prql @@ -355,6 +355,14 @@ module mysql { } module oracle { + # Date functions + module date { + # https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/TO_CHAR-datetime.html + let to_text = format column -> s"TO_CHAR({column:0}, {format:0})" + # Oracle has no DATEDIFF equivalent + let diff = unit start end -> null + } + # Text functions module text { # Oracle's `CONCAT` takes exactly two arguments before 23ai, so the generic diff --git a/prqlc/prqlc/tests/integration/sql.rs b/prqlc/prqlc/tests/integration/sql.rs index af86336933da..226f0154d02d 100644 --- a/prqlc/prqlc/tests/integration/sql.rs +++ b/prqlc/prqlc/tests/integration/sql.rs @@ -7669,6 +7669,165 @@ fn test_oracle_table_alias_omits_as() { "#); } +#[test] +fn test_oracle_dates() { + // Oracle has no `DATE_TRUNC`: `TRUNC` takes a format model. Its + // `TIMESTAMP` literal separates date and time with a space. + assert_snapshot!(compile_with_sql_dialect(r###" + from t + filter d > @2024-01-31 && ts < @2025-06-01T10:30:00.123456 && ts > @2025-01-01T08:15 + filter ts != @2025-03-01T12:00:00Z && ts != @2020-01-01T13:19:55-0800 + filter ts != @2025-01-01T08 && ts != @2025-01-01T08:15.5 + select { + y = (d | date.trunc "year"), + q = (d | date.trunc "quarter"), + m = (d | date.trunc "month"), + w = (d | date.trunc "week"), + dd = (ts | date.trunc "day"), + h = (ts | date.trunc "hour"), + mi = (ts | date.trunc "minute"), + } + "###, sql::Dialect::Oracle + ).unwrap(), @r#" + SELECT + TRUNC("d", 'YYYY') AS "y", + TRUNC("d", 'Q') AS "q", + TRUNC("d", 'MM') AS "m", + TRUNC("d", 'IW') AS "w", + TRUNC("ts", 'DD') AS "dd", + TRUNC("ts", 'HH24') AS "h", + TRUNC("ts", 'MI') AS "mi" + FROM + "t" + WHERE + "d" > DATE '2024-01-31' + AND "ts" < TIMESTAMP '2025-06-01 10:30:00.123456' + AND "ts" > TIMESTAMP '2025-01-01 08:15:00' + AND "ts" <> TIMESTAMP '2025-03-01 12:00:00 +00:00' + AND "ts" <> TIMESTAMP '2020-01-01 13:19:55 -08:00' + AND "ts" <> TIMESTAMP '2025-01-01 08:00:00' + AND "ts" <> TIMESTAMP '2025-01-01 08:15:00.5' + "#); + + assert_snapshot!(compile_with_sql_dialect(r###" + from t + select {s = (d | date.trunc "second")} + "###, sql::Dialect::Oracle + ).unwrap_err(), @r#" + Error: + ╭─[ :3:33 ] + │ + 3 │ select {s = (d | date.trunc "second")} + │ ────┬─── + │ ╰───── `date.trunc` to `second` is not supported on Oracle + │ + │ Help: supported units: year, quarter, month, week, day, hour, minute + ───╯ + "#); + + assert_snapshot!(compile_with_sql_dialect(r###" + from t + select {x = @10:30:00} + "###, sql::Dialect::Oracle + ).unwrap_err(), @"Error: time literals are not supported on Oracle, which has no TIME type"); +} + +#[test] +fn test_oracle_intervals() { + // `INTERVAL '3' DAY`, with a leading precision above two digits. There's no + // week, millisecond or microsecond field. + assert_snapshot!(compile_with_sql_dialect(r###" + from t + select { + a = d + 1days, + b = d - 2months, + c = d + 100days, + e = d + 2weeks, + f = ts + 1500milliseconds, + g = ts - 250microseconds, + h = d + 1000years, + i = ts + 2000milliseconds, + } + "###, sql::Dialect::Oracle + ).unwrap(), @r#" + SELECT + "d" + INTERVAL '1' DAY AS "a", + "d" - INTERVAL '2' MONTH AS "b", + "d" + INTERVAL '100' DAY (3) AS "c", + "d" + INTERVAL '14' DAY AS "e", + "ts" + INTERVAL '1.5' SECOND AS "f", + "ts" - INTERVAL '0.00025' SECOND AS "g", + "d" + INTERVAL '1000' YEAR (4) AS "h", + "ts" + INTERVAL '2' SECOND AS "i" + FROM + "t" + "#); + + assert_snapshot!(compile_with_sql_dialect(r###" + from t + select {c = ts + 2000000000000000000weeks} + "###, sql::Dialect::Oracle + ).unwrap_err(), @"Error: `2000000000000000000weeks` is too large an interval"); +} + +#[test] +fn test_oracle_date_to_text() { + // Oracle's `FM` is a toggle for the rest of the format model, so it is + // switched off again after each element. + assert_snapshot!(compile_with_sql_dialect(r###" + from t + select { + a = (d | date.to_text "%-d/%-m/%y"), + b = (d | date.to_text "%A %B %-d %Y at %I:%M:%S %p"), + c = (d | date.to_text "%+"), + e = (d | date.to_text "%H:%M:%S.%f, it's %a %b"), + f = (d | date.to_text "%d.%m %-H"), + } + "###, sql::Dialect::Oracle + ).unwrap(), @r#" + SELECT + TO_CHAR("d", 'FMDDFM/FMMMFM/YY') AS "a", + TO_CHAR( + "d", + 'FMDayFM FMMonthFM FMDDFM YYYY "at" HH12:MI:SS AM' + ) AS "b", + TO_CHAR("d", 'YYYY-MM-DD"T"HH24:MI:SS.FF6"Z"') AS "c", + TO_CHAR("d", 'HH24:MI:SS.FF6, "it''s" Dy Mon') AS "e", + TO_CHAR("d", 'DD.MM FMHH24FM') AS "f" + FROM + "t" + "#); + + // Oracle's format model has no way to escape a double quote inside quoted text. + assert_snapshot!(compile_with_sql_dialect(r###" + from t + select {a = (d | date.to_text "%d \"%m\"")} + "###, sql::Dialect::Oracle + ).unwrap_err(), @r#" + Error: + ╭─[ :3:35 ] + │ + 3 │ select {a = (d | date.to_text "%d \"%m\"")} + │ ─────┬───── + │ ╰─────── a double quote can't be part of a date format on Oracle + ───╯ + "#); + + assert_snapshot!(compile_with_sql_dialect(r###" + from t + select {a = (d | date.to_text "%e")} + "###, sql::Dialect::Oracle + ).unwrap_err(), @r#" + Error: + ╭─[ :3:35 ] + │ + 3 │ select {a = (d | date.to_text "%e")} + │ ──┬─ + │ ╰─── format specifier `%_d` is not supported for Oracle + ───╯ + "#); +} + #[test] fn test_sqlite_text_pattern_parenthesizes_compound_argument() { // SQLite ranks `||` above both `*`/`/`/`%` and `+`/`-`, so an