Merge branch 'master' into sqlalchemy
[sfa.git] / sfa / storage / alchemy.py
1 from types import StringTypes
2
3 from sqlalchemy import create_engine
4 from sqlalchemy.orm import sessionmaker
5
6 from sqlalchemy import Column, Integer, String
7 from sqlalchemy.orm import relationship, backref
8 from sqlalchemy import ForeignKey
9
10 from sfa.util.sfalogging import logger
11
12 # this module is designed to be loaded when the configured db server is reachable
13 # OTOH model can be loaded from anywhere including the client-side
14
15 class Alchemy:
16
17     def __init__ (self, config):
18         dbname="sfa"
19         # will be created lazily on-demand
20         self._session = None
21         # the former PostgreSQL.py used the psycopg2 directly and was doing
22         #self.connection.set_client_encoding("UNICODE")
23         # it's unclear how to achieve this in sqlalchemy, nor if it's needed at all
24         # http://www.sqlalchemy.org/docs/dialects/postgresql.html#unicode
25         # we indeed have /var/lib/pgsql/data/postgresql.conf where
26         # this setting is unset, it might be an angle to tweak that if need be
27         # try a unix socket first - omitting the hostname does the trick
28         unix_url = "postgresql+psycopg2://%s:%s@:%s/%s"%\
29             (config.SFA_DB_USER,config.SFA_DB_PASSWORD,config.SFA_DB_PORT,dbname)
30         # the TCP fallback method
31         tcp_url = "postgresql+psycopg2://%s:%s@%s:%s/%s"%\
32             (config.SFA_DB_USER,config.SFA_DB_PASSWORD,config.SFA_DB_HOST,config.SFA_DB_PORT,dbname)
33         for url in [ unix_url, tcp_url ] :
34             try:
35                 self.engine = create_engine (url)
36                 self.check()
37                 self.url=url
38                 return
39             except:
40                 pass
41         self.engine=None
42         raise Exception,"Could not connect to database"
43                 
44
45     # expects boolean True: debug is ON or False: debug is OFF
46     def debug (self, echo):
47         self.engine.echo=echo
48
49     def check (self):
50         self.engine.execute ("select 1").scalar()
51
52     def session (self):
53         if self._session is None:
54             Session=sessionmaker ()
55             self._session=Session(bind=self.engine)
56         return self._session
57
58     def close_session (self):
59         if self._session is None: return
60         self._session.close()
61         self._session=None
62
63 ####################
64 from sfa.util.config import Config
65
66 alchemy=Alchemy (Config())
67 engine=alchemy.engine
68 dbsession=alchemy.session()
69