prql icon indicating copy to clipboard operation
prql copied to clipboard

Column renaming for the duration of a function call

Open aljazerzen opened this issue 7 months ago • 9 comments

@snth has recently raised an issue that I remember we have already talked about, but cannot find now. I do think is a pain point and something we should do do better.

While on the topic of functions, one thing that I think is really needed is a way to alias columns in a relation passed to functions. I've thought a bit about this and I don't really know of an elegant way to do that.

Take for example a simple take_smallest function I use in my presentations:

let take_smallest = func n tbl -> (
  from tbl
  sort bytes
  take n
)

from tracks
group {album_id} (
  take_smallest 3
)

This works but bytes is hardcoded and you would really want that to be a parameter of take_smallest.

One workaround would be the following

let take_smallest = func n tbl -> (
  # Requires a _sort_by column to be set
  from tbl
  sort _sort_by
  take n
)

from tracks
group {album_id} (
  derive _sort_by=milliseconds
  take_smallest 3
  select !{_sort_by}
)

That works but you kinda want that derive _sort_by= ... select !{_sort_by} to happen implicitly inside the function definition.

aljazerzen avatar Jul 10 '24 15:07 aljazerzen