Mike Bayer <[email protected]> writes:
> On 6/30/15 6:56 PM, Lele Gaifax wrote:
>> With the approach above custom column types used by the "new_table" are not
>> playing their "magic", and I currently must repeat it within the "adapt()"
>> function.
>
> I assume you mean the data you're getting back from old_table isn't being
> handled because your
> TypeDecorators aren't part of old_table.
No, I actually meant the ones on the destination table, but I've been tricked
by an unnoticed error in my table declaration that made custom types not being
used at all! For some reason, I thought that the syntax
conn.execute(table.insert(), dict(f1='foo', f2='bar'))
was at a lower level and that it wouldn't trigger custom types defined on the
table... The following script asserts I was wrong indeed:
import uuid
import sqlalchemy as sa
import sqlalchemy.types as types
import sqlalchemy.dialects.postgresql as sapg
class GUID(sa.TypeDecorator):
"""Platform-independent GUID type.
Uses Postgresql's UUID type, otherwise uses CHAR(32), storing as
stringified hex value.
"""
impl = types.CHAR
def load_dialect_impl(self, dialect, _PGUUID=sapg.UUID,
_CHAR=types.CHAR):
if dialect.name == 'postgresql':
return dialect.type_descriptor(_PGUUID())
else:
return dialect.type_descriptor(_CHAR(32))
def process_bind_param(self, value, dialect,
_UUID=uuid.UUID, _uuid3=uuid.uuid3,
_ns=uuid.NAMESPACE_OID):
if value is None:
return value
else:
if isinstance(value, _UUID):
return value.hex
else:
try:
return _UUID(value).hex
except (ValueError, AttributeError):
if not isinstance(value, str):
value = str(value)
return _uuid3(_ns, value).hex
def process_result_value(self, value, dialect, _UUID=uuid.UUID):
return value if value is None else _UUID(value)
metadata = sa.MetaData()
users = sa.Table('users', metadata,
sa.Column('id', GUID, primary_key=True),
sa.Column('name', sa.String),
sa.Column('fullname', sa.String))
engine = sa.create_engine('sqlite:///:memory:', echo=True)
metadata.create_all(engine)
conn = engine.connect()
conn.execute(users.insert().values(id='foo', name='Foo', fullname='Foo
Bar'))
conn.execute(users.insert(), dict(id='bar', name='Bar',
fullname='Barbecue'))
Sorry for the noise and as usual many thanks for your awesome work and
attitude!
ciao, lele.
--
nickname: Lele Gaifax | Quando vivrò di quello che ho pensato ieri
real: Emanuele Gaifas | comincerò ad aver paura di chi mi copia.
[email protected] | -- Fortunato Depero, 1929.
--
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.