Search code examples
pythonoracle-databasesqlalchemysqldatatypesvarchar2

Set Oracle VARCHAR2 length i Byte using SQLALCHEMY


I'm currently moving some data around using python and pandas.

Here I am getting a bit stuck on the data types i can read in the existing database being in Byte and SQL Alchemy definition being in Char

For example

from sqlalchemy.dialects.oracle import VARCHAR2

dtyp = {'COLUMN': VARCHAR2(12)}

df.to_sql(<tableName>, engine.connect(), schema=<schema>, if_exists='replace', index=False, chunksize=1000, dtype=table['dtyp'])

This will create a column on my target db with type VARCHAR2(12 Char)

How can I tell sqlalchemy to create the column with type VARCHAR(12 Byte)?

Looking through the documentation I see no obvious arguments on VARCHAR2 that I can set


EDIT I figured out how to create my own custom type

class BYTE_VARCHAR2(types.UserDefinedType):
def __init__(self, precision = 8):
    self.precision = precision

def get_col_spec(self, **kw):
    return "VARCHAR2(%s Byte)" % self.precision

def bind_processor(self, dialect):
    def process(value):
        return value
    return process

def result_processor(self, dialect, coltype):
    def process(value):
        return value
    return process

Solution

  • I don't know tools you use, but - as far as Oracle is concerned - you'd specify CHAR or BYTE while creating a table, e.g.

    SQL> create table test
      2    (col_1    varchar2  (12 char),
      3     col_2    varchar2  (12 byte)
      4    );
    
    Table created.
    

    See if you can do the same.