> -----Original Message-----
> From: sqlalchemy@googlegroups.com [mailto:sqlalchemy@googlegroups.com]
> On Behalf Of Julian J. M.
> Sent: 16 June 2011 11:43
> To: sqlalchemy
> Subject: [sqlalchemy] Accessing several databases
> 
> Hello,
> 
> I'm intending to use sqalchemy with orm for loading and storing my
> application's project files. Each sqlite database would be a project
> file, that will have several tables.
> 
> I'd like to work with projects like this:
> 
> project1=AppProject("/tmp/pr1.sqlite");
> project2=AppProject("/tmp/pr2.sqlite");
> 
> item1 = project1.getItem(5) # item1 should be and object of a mapped
> class.
> item1.value="test"
> anotheritem = project1.getNewItem()
> anotheritem.value="this is new"
> # this should flush and commit the underlying session for project1,
> #modifying item with id 5, and adding a new one
> project1.commitEverything()
> 
> item2 = project2.getItem(8)
> item2.value = "another test"
> project2.commitEverything()
> 
> 
> The problem i'm facing is how to create the engine, metadata, mapper,
> session, and the orm classes for each AppProject instance.
> 
> I'm not sure if this is supported or even a good idea.
> 
> Thanks,
>     Julian J. M.
> 

I think this should be pretty easy with a separate SQLAlchemy Session
per project. You would define all your mappers and so on without any
reference to a specific database:

##############################################################
# your_db_module.py
import sqlalchemy as sa
import sqlalchemy.orm as saorm
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class ProjectItem(Base):
    __tablename__ = 'project_item'
    id = sa.Column(sa.Integer, autoincrement=True, primary_key=True)

    # other columns etc.



Then your AppProject class would look something like this:

##############################################################
# appproject.py
import sqlalchemy as sa
import sqlalchemy.orm as saorm

from your_db_module import ProjectItem

class AppProject(object):
    def __init__(self, filename):
        self.engine = sa.create_engine('sqlite://' + filename)
        self.session = saorm.Session(bind=self.engine)

    def get_item(self, id):
        return self.session.query(ProjectItem).get(id)



Hope that helps,

Simon

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

Reply via email to