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.

159 lines
6.3 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Daniel Reis
  5. # 2011
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as
  9. # published by the Free Software Foundation, either version 3 of the
  10. # License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. import os
  22. from osv import fields, osv
  23. from openerp.tools.translate import _
  24. import openerp.tools as tools
  25. import logging
  26. _logger = logging.getLogger(__name__)
  27. CONNECTORS = []
  28. try:
  29. import sqlalchemy
  30. import pymssql
  31. CONNECTORS.append( ('mssql', 'Microsoft SQL Server') )
  32. except:
  33. _logger.info('MS SQL Server not available. Please install "slqalchemy" and "pymssql" python package.')
  34. try:
  35. import sqlalchemy
  36. import MySQLdb
  37. CONNECTORS.append( ('mysql', 'MySQL') )
  38. except:
  39. _logger.info('MySQL not available. Please install "slqalchemy" and "mysqldb" python package.')
  40. try:
  41. import pyodbc
  42. CONNECTORS.append( ('pyodbc', 'ODBC') )
  43. except:
  44. _logger.info('ODBC libraries not available. Please install "unixodbc" and "python-pyodbc" packages.')
  45. try:
  46. import cx_Oracle
  47. CONNECTORS.append( ('cx_Oracle', 'Oracle') )
  48. except:
  49. _logger.info('Oracle libraries not available. Please install "cx_Oracle" python package.')
  50. import psycopg2
  51. CONNECTORS.append( ('postgresql', 'PostgreSQL') )
  52. try:
  53. import sqlalchemy
  54. CONNECTORS.append( ('sqlite', 'SQLite') )
  55. except:
  56. _logger.info('SQLAlchemy not available. Please install "slqalchemy" python package.')
  57. class base_external_dbsource(osv.osv):
  58. _name = "base.external.dbsource"
  59. _description = 'External Database Sources'
  60. _columns = {
  61. 'name': fields.char('Datasource name', required=True, size=64),
  62. 'conn_string': fields.text('Connection string', help="""\
  63. Sample connection strings:
  64. - Microsoft SQL Server: mssql+pymssql://username:%s@server:port/dbname?charset=utf8
  65. - MySQL: mysql://user:%s@server:port/dbname
  66. - ODBC: DRIVER={FreeTDS};SERVER=server.address;Database=mydb;UID=sa
  67. - ORACLE: username/%s@//server.address:port/instance
  68. - PostgreSQL: dbname='template1' user='dbuser' host='localhost' port='5432' password=%s
  69. - SQLite: sqlite:///test.db
  70. """),
  71. 'password': fields.char('Password' , size=40),
  72. 'connector': fields.selection(CONNECTORS, 'Connector', required=True,
  73. help = "If a connector is missing from the list, check the " \
  74. + "server log to confirm that the required componentes were detected."),
  75. }
  76. def conn_open(self, cr, uid, id1):
  77. #Get dbsource record
  78. data = self.browse(cr, uid, id1)
  79. #Build the full connection string
  80. connStr = data.conn_string
  81. if data.password:
  82. if '%s' not in data.conn_string:
  83. connStr += ';PWD=%s'
  84. connStr = connStr % data.password
  85. #Try to connect
  86. if data.connector == 'cx_Oracle':
  87. os.environ['NLS_LANG'] = 'AMERICAN_AMERICA.UTF8'
  88. conn = cx_Oracle.connect(connStr)
  89. elif data.connector == 'pyodbc':
  90. conn = pyodbc.connect(connStr)
  91. elif data.connector in ('sqlite','mysql','mssql'):
  92. conn = sqlalchemy.create_engine(connStr).connect()
  93. elif data.connector == 'postgresql':
  94. conn = psycopg2.connect(connStr)
  95. return conn
  96. def execute(self, cr, uid, ids, sqlquery, sqlparams=None, metadata=False, context=None):
  97. """Executes SQL and returns a list of rows.
  98. "sqlparams" can be a dict of values, that can be referenced in the SQL statement
  99. using "%(key)s" or, in the case of Oracle, ":key".
  100. Example:
  101. sqlquery = "select * from mytable where city = %(city)s and date > %(dt)s"
  102. params = {'city': 'Lisbon', 'dt': datetime.datetime(2000, 12, 31)}
  103. If metadata=True, it will instead return a dict containing the rows list and the columns list,
  104. in the format:
  105. { 'cols': [ 'col_a', 'col_b', ...]
  106. , 'rows': [ (a0, b0, ...), (a1, b1, ...), ...] }
  107. """
  108. data = self.browse(cr, uid, ids)
  109. rows, cols = list(), list()
  110. for obj in data:
  111. conn = self.conn_open(cr, uid, obj.id)
  112. if obj.connector in ["sqlite","mysql","mssql"]:
  113. #using sqlalchemy
  114. cur = conn.execute(sqlquery, sqlparams)
  115. if metadata: cols = cur.keys()
  116. rows = [r for r in cur]
  117. else:
  118. #using other db connectors
  119. cur = conn.cursor()
  120. cur.execute(sqlquery, sqlparams)
  121. if metadata: cols = [d[0] for d in cur.description]
  122. rows = cur.fetchall()
  123. conn.close()
  124. if metadata:
  125. return{'cols': cols, 'rows': rows}
  126. else:
  127. return rows
  128. def connection_test(self, cr, uid, ids, context=None):
  129. for obj in self.browse(cr, uid, ids, context):
  130. conn = False
  131. try:
  132. conn = self.conn_open(cr, uid, obj.id)
  133. except Exception, e:
  134. raise osv.except_osv(_("Connection test failed!"), _("Here is what we got instead:\n %s") % tools.ustr(e))
  135. finally:
  136. try:
  137. if conn: conn.close()
  138. except Exception:
  139. # ignored, just a consequence of the previous exception
  140. pass
  141. #TODO: if OK a (wizard) message box should be displayed
  142. raise osv.except_osv(_("Connection test succeeded!"), _("Everything seems properly set up!"))
  143. base_external_dbsource()