Matthew Moisen Matthew Moisen -3 years ago 225
Python Question

SQLAlchemy and Oracle - How to get VARCHAR2 columns to use BYTE and not CHAR?

It looks like SQLAlchemy defaults to creating

VARCHAR2
columns as
CHAR
. How can I have it create with
BYTE
instead?


from sqlalchemy import MetaData, Column, String
from sqlalchemy.ext.declarative import declarative_base

metadata = MetaData()
Base = declarative_base(metadata=metadata)

class Foo(Base):
__tablename__ = 'foo'
name = Column(String(10), primary_key=True)

Foo.__table__.create(bind=engine)


This creates the following table:


CREATE TABLE XXMD.FOO
(
NAME VARCHAR2(10 CHAR) NOT NULL
)


Instead, I would like it to create the following:


CREATE TABLE XXMD.FOO
(
NAME VARCHAR2(10 BYTE) NOT NULL
)

Answer Source

Thanks to Mike Bayer:

from sqlalchemy.ext.compiler import compiles


class VARCHAR2Byte(String):
    pass


@compiles(VARCHAR2Byte)
def compile_varchar2_byte(type_, compiler, **kw):
    len = type_.length
    return 'VARCHAR2(%i BYTE)' % len

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download