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.

175 lines
6.5 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. import logging
  23. from openerp.osv import orm, fields
  24. from openerp.tools.translate import _
  25. import openerp.tools as tools
  26. _logger = logging.getLogger(__name__)
  27. CONNECTORS = []
  28. try:
  29. import sqlalchemy
  30. CONNECTORS.append(('sqlite', 'SQLite'))
  31. try:
  32. import pymssql
  33. CONNECTORS.append(('mssql', 'Microsoft SQL Server'))
  34. except:
  35. _logger.info('MS SQL Server not available. Please install "pymssql"\
  36. python package.')
  37. try:
  38. import MySQLdb
  39. CONNECTORS.append(('mysql', 'MySQL'))
  40. except:
  41. _logger.info('MySQL not available. Please install "mysqldb"\
  42. python package.')
  43. except:
  44. _logger.info('SQL Alchemy not available. Please install "slqalchemy"\
  45. python package.')
  46. try:
  47. import pyodbc
  48. CONNECTORS.append(('pyodbc', 'ODBC'))
  49. except:
  50. _logger.info('ODBC libraries not available. Please install "unixodbc"\
  51. and "python-pyodbc" packages.')
  52. try:
  53. import cx_Oracle
  54. CONNECTORS.append(('cx_Oracle', 'Oracle'))
  55. except:
  56. _logger.info('Oracle libraries not available. Please install "cx_Oracle"\
  57. python package.')
  58. import psycopg2
  59. CONNECTORS.append(('postgresql', 'PostgreSQL'))
  60. class base_external_dbsource(orm.Model):
  61. _name = "base.external.dbsource"
  62. _description = 'External Database Sources'
  63. _columns = {
  64. 'name': fields.char('Datasource name', required=True, size=64),
  65. 'conn_string': fields.text('Connection string', help="""
  66. Sample connection strings:
  67. - Microsoft SQL Server:
  68. mssql+pymssql://username:%s@server:port/dbname?charset=utf8
  69. - MySQL: mysql://user:%s@server:port/dbname
  70. - ODBC: DRIVER={FreeTDS};SERVER=server.address;Database=mydb;UID=sa
  71. - ORACLE: username/%s@//server.address:port/instance
  72. - PostgreSQL:
  73. dbname='template1' user='dbuser' host='localhost' port='5432' password=%s
  74. - SQLite: sqlite:///test.db
  75. """),
  76. 'password': fields.char('Password', size=40),
  77. 'connector': fields.selection(CONNECTORS, 'Connector',
  78. required=True,
  79. help="If a connector is missing from the\
  80. list, check the server log to confirm\
  81. that the required components were\
  82. detected."),
  83. }
  84. def conn_open(self, cr, uid, id1):
  85. #Get dbsource record
  86. data = self.browse(cr, uid, id1)
  87. #Build the full connection string
  88. connStr = data.conn_string
  89. if data.password:
  90. if '%s' not in data.conn_string:
  91. connStr += ';PWD=%s'
  92. connStr = connStr % data.password
  93. #Try to connect
  94. if data.connector == 'cx_Oracle':
  95. os.environ['NLS_LANG'] = 'AMERICAN_AMERICA.UTF8'
  96. conn = cx_Oracle.connect(connStr)
  97. elif data.connector == 'pyodbc':
  98. conn = pyodbc.connect(connStr)
  99. elif data.connector in ('sqlite', 'mysql', 'mssql'):
  100. conn = sqlalchemy.create_engine(connStr).connect()
  101. elif data.connector == 'postgresql':
  102. conn = psycopg2.connect(connStr)
  103. return conn
  104. def execute(self, cr, uid, ids, sqlquery, sqlparams=None, metadata=False,
  105. context=None):
  106. """Executes SQL and returns a list of rows.
  107. "sqlparams" can be a dict of values, that can be referenced in
  108. the SQL statement using "%(key)s" or, in the case of Oracle,
  109. ":key".
  110. Example:
  111. sqlquery = "select * from mytable where city = %(city)s and
  112. date > %(dt)s"
  113. params = {'city': 'Lisbon',
  114. 'dt': datetime.datetime(2000, 12, 31)}
  115. If metadata=True, it will instead return a dict containing the
  116. rows list and the columns list, in the format:
  117. { 'cols': [ 'col_a', 'col_b', ...]
  118. , 'rows': [ (a0, b0, ...), (a1, b1, ...), ...] }
  119. """
  120. data = self.browse(cr, uid, ids)
  121. rows, cols = list(), list()
  122. for obj in data:
  123. conn = self.conn_open(cr, uid, obj.id)
  124. if obj.connector in ["sqlite", "mysql", "mssql"]:
  125. #using sqlalchemy
  126. cur = conn.execute(sqlquery, sqlparams)
  127. if metadata:
  128. cols = cur.keys()
  129. rows = [r for r in cur]
  130. else:
  131. #using other db connectors
  132. cur = conn.cursor()
  133. cur.execute(sqlquery, sqlparams)
  134. if metadata:
  135. cols = [d[0] for d in cur.description]
  136. rows = cur.fetchall()
  137. conn.close()
  138. if metadata:
  139. return{'cols': cols, 'rows': rows}
  140. else:
  141. return rows
  142. def connection_test(self, cr, uid, ids, context=None):
  143. for obj in self.browse(cr, uid, ids, context):
  144. conn = False
  145. try:
  146. conn = self.conn_open(cr, uid, obj.id)
  147. except Exception, e:
  148. raise orm.except_orm(_("Connection test failed!"),
  149. _("Here is what we got instead:\n %s")
  150. % tools.ustr(e))
  151. finally:
  152. try:
  153. if conn:
  154. conn.close()
  155. except Exception:
  156. # ignored, just a consequence of the previous exception
  157. pass
  158. #TODO: if OK a (wizard) message box should be displayed
  159. raise orm.except_orm(_("Connection test succeeded!"),
  160. _("Everything seems properly set up!"))
  161. #EOF