Adding back
authorTony Mack <tmack@paris.CS.Princeton.EDU>
Fri, 28 Sep 2012 19:16:16 +0000 (15:16 -0400)
committerTony Mack <tmack@paris.CS.Princeton.EDU>
Fri, 28 Sep 2012 19:16:16 +0000 (15:16 -0400)
PLC/Storage/Alchemy.py [new file with mode: 0644]

diff --git a/PLC/Storage/Alchemy.py b/PLC/Storage/Alchemy.py
new file mode 100644 (file)
index 0000000..5b0ed18
--- /dev/null
@@ -0,0 +1,84 @@
+from types import StringTypes
+from datetime import datetime
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from sqlalchemy.ext.declarative import declarative_base
+
+from PLC.Storage.Record import Record
+from PLC.Timestamp import Timestamp
+from PLC.Logger import logger
+
+Base=declarative_base()
+# this module is designed to be loaded when the configured db server is reachable
+# OTOH model can be loaded from anywhere including the client-side
+
+class Alchemy:
+
+    def __init__ (self, config):
+        dbname="planetlab"
+        # will be created lazily on-demand
+        self._session = None
+        # the former PostgreSQL.py used the psycopg2 directly and was doing
+        #self.connection.set_client_encoding("UNICODE")
+        # it's unclear how to achieve this in sqlalchemy, nor if it's needed at all
+        # http://www.sqlalchemy.org/docs/dialects/postgresql.html#unicode
+        # we indeed have /var/lib/pgsql/data/postgresql.conf where
+        # this setting is unset, it might be an angle to tweak that if need be
+        # try a unix socket first - omitting the hostname does the trick
+        unix_url = "postgresql+psycopg2://%s:%s@:%s/%s"%\
+            (config.DB_USER,config.DB_PASSWORD,config.DB_PORT,dbname)
+        # the TCP fallback method
+        tcp_url = "postgresql+psycopg2://%s:%s@%s:%s/%s"%\
+            (config.DB_USER,config.DB_PASSWORD,config.DB_HOST,config.DB_PORT,dbname)
+        for url in [ unix_url, tcp_url ] :
+            try:
+                self.engine = create_engine (url)
+                self.check()
+                self.url=url
+                return
+            except:
+                pass
+        self.engine=None
+        raise Exception,"Could not connect to database"
+                
+
+    # expects boolean True: debug is ON or False: debug is OFF
+    def debug (self, echo):
+        self.engine.echo=echo
+
+    def check (self):
+        self.engine.execute ("select 1").scalar()
+
+    def session (self):
+        if self._session is None:
+            Session=sessionmaker ()
+            self._session=Session(bind=self.engine)
+        return self._session
+
+    def close_session (self):
+        if self._session is None: return
+        self._session.close()
+        self._session=None
+
+#    # only intended for debugging
+#    def inspect (self, logger, message=""):
+#        logger.info("%s -- Inspecting AlchemyObj -- attrs"%message)
+#        for k in dir(self):
+#            if not k.startswith('_'):
+#                logger.info ("  %s: %s"%(k,getattr(self,k)))
+#        logger.info("%s -- Inspecting AlchemyObj -- __dict__"%message)
+#        d=self.__dict__
+#        for (k,v) in d.iteritems():
+#            logger.info("[%s]=%s"%(k,v))
+
+
+
+
+####################
+from PLC.Config import Config
+
+alchemy=Alchemy (Config())
+engine=alchemy.engine
+dbsession=alchemy.session()
+