Skip to content

Instantly share code, notes, and snippets.

@inklesspen
Last active November 12, 2015 19:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inklesspen/0e79ded81ca17c307a54 to your computer and use it in GitHub Desktop.
Save inklesspen/0e79ded81ca17c307a54 to your computer and use it in GitHub Desktop.
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID, array
rec_order = sa.select(
# using the 'WITH ORDINALITY' suffix adds a column named 'ordinality'
# the first row (from the first array value) has ordinality 1, the second has 2, and so on
# this is useful for sorting things by the array value; simply join on the array value
# and order by ordinality
[sa.column('ordinality', sa.Integer),
# The actual column generated by unnest is named 'unnest' by default,
# so I use a lightweight column construct to specify the name and type
# and then apply a label to it
sa.column('unnest', UUID).label('rec_uuid')],
from_obj=sa.func.unnest(array(rec_uuids)))\
.suffix_with('WITH ORDINALITY')\
.alias('rec_order')
@inklesspen
Copy link
Author

With this construct, I can now use rec_order.c.ordinality and rec_order.c.rec_uuid in my queries.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment