Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a unique lowercase functional index using SQLAlchemy on PostgreSQL?

This is the SQL I want to generate:

CREATE UNIQUE INDEX users_lower_email_key ON users (LOWER(email));

From the SQLAlchemy Index documentation I would expect this to work:

Index('users_lower_email_key', func.lower(users.c.email), unique=True)

But after I call metadata.create(engine) the table is created but this index is not. I've tried:

from conf import dsn, DEBUG

engine = create_engine(dsn.engine_info())

metadata = MetaData()
metadata.bind = engine

users = Table('users', metadata,
    Column('user_id', Integer, primary_key=True),
    Column('email', String),
    Column('first_name', String, nullable=False),
    Column('last_name', String, nullable=False),
    )

Index('users_lower_email_key', func.lower(users.c.email), unique=True)

metadata.create_all(engine)

Viewing the table definition in PostgreSQL I see that this index was not created.

\d users
                                   Table "public.users"
   Column   |       Type        |                        Modifiers
------------+-------------------+---------------------------------------------------------
 user_id    | integer           | not null default nextval('users_user_id_seq'::regclass)
 email      | character varying |
 first_name | character varying | not null
 last_name  | character varying | not null
Indexes:
    "users_pkey" PRIMARY KEY, btree (user_id)

How can I create my lower, unique index?

like image 652
skyler Avatar asked Sep 06 '13 20:09

skyler


1 Answers

I have no idea why you want to index an integer column in lower case; The problem is that the generated sql does not typecheck:

LINE 1: CREATE UNIQUE INDEX banana123 ON mytable (lower(col5))
                                                  ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
 'CREATE UNIQUE INDEX banana123 ON mytable (lower(col5))' {}

On the other hand, if you use an actual string type:

Column('col5string', String),
...
Index('banana123', func.lower(mytable.c.col5string), unique=True)

The index is created as expected. If, for some very strange reason, you are insistent about this absurd index, you just need to fix the types:

Index('lowercasedigits', func.lower(cast(mytable.c.col5, String)), unique=True)

Which produces perfectly nice:

CREATE UNIQUE INDEX lowercasedigits ON mytable (lower(CAST(col5 AS VARCHAR)))
like image 167
SingleNegationElimination Avatar answered Sep 26 '22 16:09

SingleNegationElimination