This post will show you how to use RAW data types from cx_Oracle dialect in SQLAlchemy to create unique row IDs that are generated by SYS_GUID().
This lets you use Oracle’s SYS_GUID() function to create unique IDs for rows without Sequences. The added advantage is that each ID is unique, even among tables. There are many discussions about system performance regarding this technique, but the general consensus is that this is as fast or faster than Integers and Sequences.
First, the RAW dialect is required from the cx_Oracle package. SQLAlchemy has knowledge of most basic cx_Oracle types, but RAW is not there by default.
In : from sqlalchemy.dialects.oracle import RAW
RAW data in Oracle is Binary data. We will have to convert between binary and ascii-hex so humans can use the values.
In : import binascii
Your SQLAlchemy model object will look like this.
This code sample assumes you already have a declarative base and a Base class. For basics on using SQLAlchemy, see their own documentation: http://www.sqlalchemy.org/
__tablename__ = 'my_table'
__table_args__ = (
Index('my_table_uk1', 'name', 'value', unique=True),
id = Column(RAW, primary_key=True, server_default=text("SYS_GUID()"))
name = Column(Unicode(100), nullable=False)
value = Column(Unicode(100), nullable=False)
That’s all there is to the setup. You have a model that supports RAW with an ‘id’ column that is automatically a call to Oracle’s internal SYS_GUID() function.
You can insert a row by putting a Binary value in to the id column, but why bother? Just leave it out. If you create this object:
You can query it and see that an ID was generated:
In : for value in Session.query(models.MyTable.id).distinct():
It works! However, that value sure is ugly.
Making it Readable
To convert that value to something your users can reference as a unique ID.
In : values = v2_session.read_session.query(models.MyTable).all()
In : values
[<models.MyTable at 0x2b0bbbaaf518>]
In : v = values
In : v
Out: <models.MyTable at 0x2b0bbbaaf438>
In : v.name
In : v.value
In : v.id
In : v.id.hex()
The RAW object has a hex() method that translates nicely in to a string GUID your users and APIs can work with.
From Readable Back to RAW
Now lets turn that string back in to a RAW value that SQLAlchemy can use to query the database.
In : column_id = binascii.a2b_hex('4cea48de887c2346e053aea4cc0af640')
In : values = Session.query(models.MyTable).filter_by(id=column_id).all()
In : values
Out: [<models.MyTable at 0x2b0bbbaaf438>]
There you have it.
Did you find this post useful or have questions or comments? Please let me know!