Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
42 changes: 42 additions & 0 deletions prqlc/prqlc/src/sql/dialect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
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)]
Expand Down
148 changes: 147 additions & 1 deletion prqlc/prqlc/src/sql/gen_expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<BigQueryDialect>() {
// BigQuery: DATE_TRUNC(col, DAY) — unit is an unquoted uppercase keyword
Expand Down Expand Up @@ -276,6 +276,46 @@ fn process_date_trunc(
parameters: sql_ast::FunctionArguments::None,
uses_odbc_syntax: false,
}));
} else if ctx.dialect.is::<OracleDialect>() {
// 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
Expand Down Expand Up @@ -531,6 +571,18 @@ pub(super) fn translate_literal(l: Literal, ctx: &Context) -> Result<sql_ast::Ex
Literal::Float(f) => 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::<crate::sql::dialect::OracleDialect>() => {
return Err(Error::new_simple(
"time literals are not supported on Oracle, which has no TIME type",
))
}
Literal::Timestamp(value) if ctx.dialect.is::<crate::sql::dialect::OracleDialect>() => {
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,
Expand All @@ -541,6 +593,9 @@ pub(super) fn translate_literal(l: Literal, ctx: &Context) -> Result<sql_ast::Ex
value,
ctx,
),
Literal::ValueAndUnit(vau) if ctx.dialect.is::<crate::sql::dialect::OracleDialect>() => {
translate_oracle_interval(vau.n, &vau.unit)?
}
Literal::ValueAndUnit(vau) => {
let sql_parser_datetime = match vau.unit.as_str() {
"years" => DateTimeField::Year,
Expand Down Expand Up @@ -604,6 +659,86 @@ pub(super) fn translate_literal(l: Literal, ctx: &Context) -> Result<sql_ast::Ex
})
}

/// Oracle's TIMESTAMP literal: `YYYY-MM-DD HH24:MI:SS[.FF][ ±HH:MM]` — a space
/// rather than `T`, seconds required, and an offset with a colon (no `Z`).
fn oracle_timestamp(value: &str) -> 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})?$",
)
Comment thread
prql-bot marked this conversation as resolved.
Resolved
.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)`.
/// <https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Literals.html#GUID-DC8D1DAD-7D04-45EA-9546-82810CD09A9D>
fn translate_oracle_interval(n: i64, unit: &str) -> Result<sql_ast::Expr> {
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,
Expand Down Expand Up @@ -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<i64>, end: Option<i64>) -> Range<rq::Expr> {
Expand Down
8 changes: 8 additions & 0 deletions prqlc/prqlc/src/sql/std.sql.prql
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading