ai-coding-minesIndexGitHub

`can't adapt type 'UUID'` when passing a uuid parameter through psycopg2

Python and databases

Symptom

psycopg2.ProgrammingError: can't adapt type 'UUID'

An INSERT or SELECT that takes a uuid.UUID value, or a uuid[] list, dies, and the endpoint above it returns 500. The same query runs fine in a SQL client.

Cause

psycopg2 does not adapt uuid.UUID out of the box. Pass a string and it works; pass a UUID object and it fails. Arrays fail per element.

Fix

Register the adapter once, right after import.

import psycopg2.extras
psycopg2.extras.register_uuid()

Once per process is enough. Calling it per connection is harmless but pointless.

Verification

Print the bound query with mogrify before sending it.

cur.mogrify("SELECT %s, %s", (uuid.uuid4(), [uuid.uuid4()]))
# b"SELECT '...'::uuid, ARRAY['...'::uuid]"   <- registered

Register adapters once, in one place, at import time. A 500 that happens from some modules and not others means the registration is scattered.