Created
February 27, 2014 23:48
-
-
Save jmatthias/9262225 to your computer and use it in GitHub Desktop.
Database-agnostic SQLAlchemy UUID column type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
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
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.