SQLAlchemy Tips

From GNU MediaGoblin Wiki
Jump to navigation Jump to search

Some tips for hacking around with the MediaGoblin databases and SQLAlchemy.

First off, read all of http://docs.sqlalchemy.org/en/latest/orm/tutorial.html – great tutorial.

Then, to use MediaGoblin database classes/tables from your python interpreter, you can start up bin/python2 -i (if you use Emacs, you can hand it /path/to/mediagoblin/bin/python2 -i when it asks which python to start) and begin with this boilerplate:

from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)
# Use an in-memory table, and have all SQL statements echoed back in
# the interpreter for debuggability

from mediagoblin.db.base import Session
Session.configure(bind=engine)
session=Session()

# Some of the tables need to have some entries in order for the rest
# to be usable:
from mediagoblin.db.models import FOUNDATIONS as MAIN_FOUNDATIONS
for Model,rows in MAIN_FOUNDATIONS.items():
    for parameters in rows:
        new_row = Model(**parameters)
	session.add(new_row)

from mediagoblin.db.base import Base
from mediagoblin.db.models import * # User, MediaEntry, etc
Base.metadata.create_all(engine) # creates all tables

Now try it out:

session.query(User).all()       # An empty list

goblinda=User(username='goblinda',email='gob@lin.da')
session.add(goblinda)
session.query(User).all()       # Now has an entry =D