Skip to content

feat: Value.sql(sql: str | string.Template, *, name: str | None = "{{value}}") #11525

@NickCrews

Description

@NickCrews

Is your feature request related to a problem?

I have to parse a UTC timestamp into AK local time, eg "8/1/2024 21:44:00" into 2024-08-01 13:44:00 (8 hours before UTC).
I can do this in duckdb sql with

SELECT CAST(STRPTIME('8/1/2024 21:44:00', '%m/%d/%Y %H:%M:%S') AT TIME ZONE 'UTC' AT TIME ZONE 'America/Anchorage' AS TIMESTAMP)

The best way I have found to do this (maybe you have a better way, in which case the TODO here is for me to add a how-to or other docs) is with eg

t.alias("t").sql("""
    SELECT *, CAST(my_timestamp AT TIME ZONE 'America/Anchorage' AS TIMESTAMP) AS my_timestamp_ak_local
    FROM t
""")

It's annoying that this is a table method, and it requires the extra SELECT, and aliasing, and hardcodes the column value.

What is the motivation behind your request?

see above

Describe the solution you'd like

I would LOVE to be able to write:

t.mutate(
    my_timestamp_ak_local=_.my_timestamp.sql("CAST({{value}} AT TIME ZONE 'America/Anchorage' AS TIMESTAMP)")
   # or
    my_timestamp_ak_local=_.my_timestamp.sql("CAST({{my_value}} AT TIME ZONE 'America/Anchorage' AS TIMESTAMP)", name="{{my_value}}")
    # or, in python 3.14, t-strings make this really ergonomic (https://realpython.com/python-t-strings/)
    my_timestamp_ak_local=_.sql(t"CAST({_.my_timestamp} AT TIME ZONE 'America/Anchorage' AS TIMESTAMP)")
)

This could also maybe could be spelled not as a Value instance method, but a top-level function that creates a Value expression, eg
ibis.sql_value(sql: str | string.Template, **replacements: Mapping[str, ibis.Value]).

optionally, as a bonus, could also support a dialect kwarg so that you could write the sql in one dialect, and it would then get transpiled to other dialects when executed on other backends.

What version of ibis are you running?

main

What backend(s) are you using, if any?

duckdb and postgres

Code of Conduct

  • I agree to follow this project's Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureFeatures or general enhancements

    Type

    No type

    Projects

    Status

    backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions