Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a column default to a PostgreSQL function using SQLAlchemy?

Tags:

All of my tables defined in SQLAlchemy have an id column of type UUID.

from sqlalchemy.ext.declarative import declarative_base from uuid import uuid4 Base = declarative_base()  class MyTable(Base):     id = Column(UUIDtype, default=uuid4, primary_key=True) 

Where UUIDtype is a special column type for the PostgreSQL UUID type. This successfully creates the UUID column in PostgreSQL, but only generates a default UUID value when inserting using SQLAlchemy. This is fine for some of my use cases, but I want to assign the column's default on the PostgreSQL side of things in case an insert occurs outside of SQLAlchemy.

The following SQL command places the proper default on the column:

ALTER TABLE my_table ALTER COLUMN id SET DEFAULT uuid_generate_v4() 

How can I assign this uuid_generate_v4() function as the column default through SQLAlchemy model definition? If the only option is through executing a raw SQL statement, is there a way for me to hook that statement's execution into the table creation process?

like image 315
Tanner Semerad Avatar asked Dec 12 '13 00:12

Tanner Semerad


People also ask

Can you use SQLAlchemy with PostgreSQL?

PostgreSQL supports sequences, and SQLAlchemy uses these as the default means of creating new primary key values for integer-based primary key columns.

Is psycopg2 faster than SQLAlchemy?

The psycopg2 is over 2x faster than SQLAlchemy on small table. This behavior is expected as psycopg2 is a database driver for postgresql while SQLAlchemy is general ORM library.

What are generic functions in SQL?

A generic function is a pre-established Function class that is instantiated automatically when called by name from the func attribute. Note that calling any name from func has the effect that a new Function instance is created automatically, given that name.


1 Answers

You should use server_default parameter for this.

id = Column(UUIDtype, server_default=text("uuid_generate_v4()"), primary_key=True) 

See Server Side Defaults for more information.

like image 74
van Avatar answered Sep 25 '22 06:09

van