No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

sqlutils.py 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import re
  4. import logging as logger
  5. import sqlalchemy as sqla
  6. from django.conf import settings
  7. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Lodel.settings")
  8. ENGINES = {'mysql': {
  9. 'driver': 'pymysql',
  10. 'encoding': 'utf8'
  11. },
  12. 'postgresql': {
  13. 'driver': 'psycopg2',
  14. 'encoding': 'utf8',
  15. },
  16. 'sqlite': {
  17. 'driver': 'pysqlite',
  18. 'encoding': 'utf8',
  19. },
  20. }
  21. sqlcfg = settings.LODEL2SQLWRAPPER
  22. def getEngine(ename = 'default', sqlalogging = None):
  23. """ Return a sqlalchemy engine
  24. @param read bool: If True return the read engine, else
  25. return the write one
  26. @return a sqlachemy engine instance
  27. @todo Put the check on db config in SqlWrapper.checkConf()
  28. """
  29. #Loading confs
  30. cfg = sqlcfg['db'][ename]
  31. edata = ENGINES[cfg['ENGINE']] #engine infos
  32. conn_str = ""
  33. if cfg['ENGINE'] == 'sqlite':
  34. #Sqlite connection string
  35. conn_str = '%s+%s:///%s'%( cfg['ENGINE'],
  36. edata['driver'],
  37. cfg['NAME'])
  38. else:
  39. #Mysql and Postgres connection string
  40. user = cfg['USER']
  41. user += (':'+cfg['PASSWORD'] if 'PASSWORD' in cfg else '')
  42. if 'HOST' not in cfg:
  43. logger.info('Not HOST in configuration, using localhost')
  44. host = 'localhost'
  45. else:
  46. host = cfg['HOST']
  47. host += (':'+cfg['PORT'] if 'PORT' in cfg else '')
  48. conn_str = '%s+%s://'%(cfg['ENGINE'], edata['driver'])
  49. conn_str += '%s@%s/%s'%(user,host,cfg['NAME'])
  50. ret = sqla.create_engine(conn_str, encoding=edata['encoding'], echo=sqlalogging)
  51. logger.debug("Getting engine :"+str(ret))
  52. return ret
  53. def meta(engine):
  54. res = sqla.MetaData()
  55. res.reflect(bind=engine)
  56. return res