Skip to content

Instantly share code, notes, and snippets.

@jmatthias
Created February 27, 2014 23:48
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmatthias/9262225 to your computer and use it in GitHub Desktop.
Save jmatthias/9262225 to your computer and use it in GitHub Desktop.
Database-agnostic SQLAlchemy UUID column type
import psycopg2.extras
import sqlalchemy.dialects.postgresql
from sqlalchemy.types import TypeEngine
from sqlalchemy.types import String
from sqlalchemy.types import TypeDecorator
import uuid
# Required for PostgreSQL to accept UUID type.
psycopg2.extras.register_uuid()
class UUID(TypeDecorator):
""" Converts UUID to string before storing to database.
Converts string to UUID when retrieving from database. """
impl = TypeEngine
def load_dialect_impl(self, dialect):
""" When using Postgres database, use the Postgres UUID column type.
Otherwise, use String column type. """
if dialect.name == 'postgresql':
return dialect.type_descriptor(sqlalchemy.dialects.postgresql.UUID)
return dialect.type_descriptor(String)
def process_bind_param(self, value, dialect):
""" When using Postgres database, no conversion.
Otherwise, convert to string before storing to database. """
if dialect.name == 'postgres':
return value
if value is None:
return value
return str(value)
def process_result_value(self, value, dialect):
""" When using Postgres database, no conversion.
Otherwise, convert to UUID when retrieving from database. """
if dialect.name == 'postgresql':
return value
if value is None:
return value
return uuid.UUID(value)
@jmatthias
Copy link
Author

This is useful to me because we're running tests locally on an in-memory SQLite database for speed, and we're running tests in our Travis CI builds on a PostgreSQL database so we can be sure everything will work in production.

@Lewiscowles1986
Copy link

what about server defaults though? We use Alembic at work and all the migrations are cluttered with uuid_generate_v4() in the server default column. I Fear it may be too F'd to pick through

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