Using a row's value within an expression/ordering (CASE/WHEN/THEN/ELSE/END expression) #1346
-
Hello, all! I am persisting records that contain both a UTC datetime and a timezone offset in my database table to be able to communicate in UTC while displaying local times to the user. The timezone offset can be null or have a value represented in minutes. When the timezone is null, I would like to use I have figured out how to do this using raw SQL, using something like the following:
Is it possible to do something like this using the query interface? If not, how can I embed this in a query interface request with other selections/etc? Would Common Table Expressions help me here? How about Thanks in advance :) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hello @dawilliams-gpsw, There is no built-in support for the general func localizedDate(
timeZoneOffset: some SQLExpressible,
date: some SQLExpressible)
-> SQLExpression
{
SQL("""
CASE WHEN \(timeZoneOffset) IS NULL
THEN datetime(\(date), 'localtime')
ELSE datetime(\(date), printf('%d minutes', \(timeZoneOffset)))
END
""").sqlExpression
} Usage: // SELECT *, CASE...END AS localizedDate
// FROM ...
// ORDER BY localizedDate
let localizedDate = localizedDate(
timeZoneOffset: Column("timeZoneOffset"),
date: Column("date"))
let request = try MyRecord
.annotated(with: localizedDate.forKey("localizedDate"))
.order(Column("localizedDate").detached) There are several techniques at play here. To sum up:
|
Beta Was this translation helpful? Give feedback.
Hello @dawilliams-gpsw,
There is no built-in support for the general
CASE WHEN THEN ELSE END
expression in GRDB, but you can build your specific one:Usage: