среда, 16 декабря 2015 г.

SQLAlchemy Custom Types

http://docs.sqlalchemy.org/en/latest/core/custom_types.html
http://docs.sqlalchemy.org/en/latest/orm/composites.html

Допустим, есть у нас задача - на лету переводить столбец uuid в unhex-представление.
class HashColumn(VARBINARY):
  def bind_expression(self, bindvalue):
  #bindvalue = type_coerce(bindvalue, Binary)
  return func.unhex(func.replace(bindvalue, '-', ''))

  def column_expression(self, col):
    return func.lower(func.hex(col))

def select(table_name):
  table = Table(table_name, self.metadata, Column("uuid", HashColumn(20)), autoload=True, extend_existing=True)
  select = table.select()
  ...
Казалось бы, тут был бы логичнее TypeDecorator, но..

<Elmer> oh yeah that TypeDecorator doesn't work because the process_bind_param and process_result_value methods should be Python code, func.hex/func.unhex create SQL function calls

Правильно создаём table и получаем автоматом преобразование.

http://stackoverflow.com/questions/33923914/python-sqlalchemy-binary-column-type-hex-and-unhex/33925980#33925980
http://stackoverflow.com/questions/34039039/python-sqlalchemy-binary-column-type-hex-and-unhex-with-autoloaded-table

Комментариев нет:

Отправить комментарий