2

I've inherited a Pylons app that uses SQLAlchemy. I know nothing about SQLAlchemy and very little about Pylons :)

I need to run some raw SQL from within the app. The SQLAlchemy currently seems to be working in the following way (example code):

import myapp.model as model
model.Session.query(model.KeyValue) # existing code
            .join(model.Key)
            .filter(model.Key.name == name)
            ).count() == 0, name

How do I get it to run raw SQL? I see that I need an execute() statement, but how exactly do I run it? The following both fail:

model.Session.execute('create table hello_world;')
model.Connection.execute("""
create table hello_world;
""")

What's the magic invocation? There's no reference to a Connection object in the existing code, and I'm not sure how to create one.

2 Answers 2

8

You can obtain connection that is used by Session by using its connection method:

connection = model.Session.connection()

Then you can issue your query:

connection.execute('create table hello_world;')

Note that in Pylons model.Session is not a sqlalchemy.orm.session.Session class. It's an instance of sqlalchemy.orm.scoping.ScopedSession. That's how it's created in model.meta module:

Session = scoped_session(sessionmaker())
1

My first impulse is to recommend trying the execute() method of an instance of Connection, instead of the execute() method of the class itself as your example code suggests that you're doing.

Are you working off of the Pylons Book examples ?

2
  • do you think I should try to create an explicit connection, as per the examples? I just wondered if there was a clever way, since I seem to have inherited code that's trying to do something clever.
    – AP257
    Sep 20, 2010 at 21:14
  • The first thing I would try would be to create an explicit connection, yes. If that doesn't work, then something excessively clever is definitely going on. Good luck with the inherited code. Sep 20, 2010 at 21:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.