1 from types import StringTypes
3 from sqlalchemy import create_engine
4 from sqlalchemy.orm import sessionmaker
6 from sqlalchemy import Column, Integer, String
7 from sqlalchemy import ForeignKey
9 from sfa.util.sfalogging import logger
11 # this module is designed to be loaded when the configured db server is reachable
12 # OTOH model can be loaded from anywhere including the client-side
16 def __init__ (self, config):
18 # will be created lazily on-demand
20 # the former PostgreSQL.py used the psycopg2 directly and was doing
21 #self.connection.set_client_encoding("UNICODE")
22 # it's unclear how to achieve this in sqlalchemy, nor if it's needed at all
23 # http://www.sqlalchemy.org/docs/dialects/postgresql.html#unicode
24 # we indeed have /var/lib/pgsql/data/postgresql.conf where
25 # this setting is unset, it might be an angle to tweak that if need be
26 # try a unix socket first - omitting the hostname does the trick
27 unix_url = "postgresql+psycopg2://%s:%s@:%s/%s"%\
28 (config.SFA_DB_USER,config.SFA_DB_PASSWORD,config.SFA_DB_PORT,dbname)
29 # the TCP fallback method
30 tcp_url = "postgresql+psycopg2://%s:%s@%s:%s/%s"%\
31 (config.SFA_DB_USER,config.SFA_DB_PASSWORD,config.SFA_DB_HOST,config.SFA_DB_PORT,dbname)
32 for url in [ unix_url, tcp_url ] :
34 logger.debug("Trying db URL %s"%url)
35 self.engine = create_engine (url)
42 raise Exception,"Could not connect to database %s as %s with psycopg2"%(dbname,config.SFA_DB_USER)
45 # expects boolean True: debug is ON or False: debug is OFF
46 def debug (self, echo):
50 self.engine.execute ("select 1").scalar()
52 def global_session (self):
53 if self._session is None:
54 Session=sessionmaker ()
55 self._session=Session(bind=self.engine)
56 logger.info('alchemy.global_session created session %s'%self._session)
59 def close_global_session (self):
60 if self._session is None: return
61 logger.info('alchemy.close_global_session %s'%self._session)
65 # create a dbsession to be managed separately
67 Session=sessionmaker()
68 session=Session (bind=self.engine)
69 logger.info('alchemy.session created session %s'%session)
72 def close_session (self, session):
73 logger.info('alchemy.close_session closed session %s'%session)
77 from sfa.util.config import Config
79 alchemy=Alchemy (Config())
81 global_dbsession=alchemy.global_session()