provide more details when db connection is failing
[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 import ForeignKey
8
9 from sfa.util.sfalogging import logger
10
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
13
14 class Alchemy:
15
16     def __init__ (self, config):
17         dbname="sfa"
18         # will be created lazily on-demand
19         self._session = None
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 ] :
33             try:
34                 self.engine = create_engine (url)
35                 self.check()
36                 self.url=url
37                 return
38             except:
39                 pass
40         self.engine=None
41         logger.warning("Could not connect to database: db=%s, user=%s, host=%s, port=%s" % \
42                            (dbname, config.SFA_DB_USER, config.SFA_DB_HOST, config.SFA_DB_PORT))
43         logger.debug("Using password=%s"%config.SFA_DB_PASSWORD)
44         raise Exception,"Could not connect to database %s as %s"%(dbname,config.SFA_DB_USER)
45
46
47     # expects boolean True: debug is ON or False: debug is OFF
48     def debug (self, echo):
49         self.engine.echo=echo
50
51     def check (self):
52         self.engine.execute ("select 1").scalar()
53
54     def session (self):
55         if self._session is None:
56             Session=sessionmaker ()
57             self._session=Session(bind=self.engine)
58         return self._session
59
60     def close_session (self):
61         if self._session is None: return
62         self._session.close()
63         self._session=None
64
65 ####################
66 from sfa.util.config import Config
67
68 alchemy=Alchemy (Config())
69 engine=alchemy.engine
70 dbsession=alchemy.session()
71