SQLObject: Creating table dynamically

October 25, 2008 § Leave a comment

I’ve been using SQLObject for a while now, and I’m 60/40 with it.

I am mostly happy of SQLObject because:

  • The documentation is easy to read.
  • Getting up to speed is ridiculously easy, in less than 5 minutes I have a ‘user’ MySQL table wrapped with class User.
  • The generated SQL is efficient, for all my needs.
  • The returned ResultSet can be sliced, that’s nice. 

Why I’m not happy with it:

  • The invisible ‘id‘ column, that always get created for every new table. I have multiple needs for ORM to just create the table as-is, explicitly (Like how SQLALchemy does).

Why I haven’t switched to SQLAlchemy:

  • I have, but not for all model classes.
  • My noobiness limits me on what I can do with SQLAlchemy. For example, I haven’t figure out how to add Column object to existing Table object (that was created dynamically).  

That being said, SQLObject is very useful if you want to create MySQL table dynamically. You can achieve this by using meta-programming.

Example:

def create_or_get_dynamic_mysql_table(name):
   try:
      # SQLObject cache all classes that already defined,
      # If 'name' already defined, just get it using findClass()
      dynamic_table_classname = findClass(name)
   except:
      # Create new 'name' class
      # If you see the 2nd param of classobj, 'name' class extends SQLObject class
      dynamic_table_classname = classobj( name, (sqlobject.SQLObject,), {} )

   return dynamic_table_classname

# Then Call the createTable method
table_class = create_or_get_dynamic_mysql_table('awesome')
table_class.createTable(if_not_exists=True)

References:

Advertisements

Tagged: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading SQLObject: Creating table dynamically at RAPD.

meta

%d bloggers like this: