Automatic prefix on all tables

1,477 views
Skip to first unread message

F. Poirotte

unread,
Feb 11, 2010, 4:42:11 PM2/11/10
to sqlalchemy
Hi,

First, many thanks to everyone who helped make SQLAlchemy such a great
module.

I'm currently using the declarative syntax and I would like to know
weither it's possible or not to automatically add a prefix on all
tables, without having to specify it on each and every table
separately.
That is, I would like to define the tables using __tablename__ =
"sometable", but the metadata to create the tables (and references in
foreign keys, etc.) as "someprefix_sometable".

This seems similar to what .with_prefix() or column_prefix provide,
though it would operate on tables instead of columns.

I found this thread which seems to be similar to what I'm trying to
achieve, but would prefer a definitive answer (that thread has been
left unanswered) : http://groups.google.com/group/sqlalchemy/browse_thread/thread/caf89dddd246e8ca/b66ff46a0eaeb543

Thank you for your help.

Cheers,
François.

Michael Bayer

unread,
Feb 11, 2010, 5:09:18 PM2/11/10
to sqlal...@googlegroups.com

that thread has to do with copying tables which is not what you're looking
for here. Usually I tell people to create a Table object using a def
that passes in the new name. But since you want the table renamed using
declarative + __tablename__, you'd need to use a metaclass:

class RenameTables(DeclarativeMeta):
def __init__(cls, classname, bases, dict_):
if '__tablename__' in dict_:
cls.__tablename__ = dict_['__tablename__'] = "prefix_" +
cls.__tablename__
return DeclarativeMeta.__init__(cls, classname, bases, dict_)


Base = declarative_base(metaclass=RenameTables)


class Usr(Base):
__tablename__ = 'users'

id = Column(Integer, primary_key = True)
name = Column(String)

you can also put RenameTables on individual classes with __metaclass__ if
thats what you want.


>
> Thank you for your help.
>
> Cheers,

> Fran�ois.
>
> --
> You received this message because you are subscribed to the Google Groups
> "sqlalchemy" group.
> To post to this group, send email to sqlal...@googlegroups.com.
> To unsubscribe from this group, send email to
> sqlalchemy+...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/sqlalchemy?hl=en.
>
>

Reply all
Reply to author
Forward
0 new messages