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.

216 lines
10 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 sys
  22. from datetime import datetime
  23. from openerp.osv import orm, fields
  24. import logging
  25. _logger = logging.getLogger(__name__)
  26. _loglvl = _logger.getEffectiveLevel()
  27. SEP = '|'
  28. class import_odbc_dbtable(orm.Model):
  29. _name = "import.odbc.dbtable"
  30. _description = 'Import Table Data'
  31. _order = 'exec_order'
  32. _columns = {
  33. 'name': fields.char('Datasource name', required=True, size=64),
  34. 'enabled': fields.boolean('Execution enabled'),
  35. 'dbsource_id': fields.many2one('base.external.dbsource', 'Database source', required=True),
  36. 'sql_source': fields.text('SQL', required=True, help='Column names must be valid "import_data" columns.'),
  37. 'model_target': fields.many2one('ir.model', 'Target object'),
  38. 'noupdate': fields.boolean('No updates', help="Only create new records; disable updates to existing records."),
  39. 'exec_order': fields.integer('Execution order', help="Defines the order to perform the import"),
  40. 'last_sync': fields.datetime('Last sync date',
  41. help="Datetime for the last succesfull sync."
  42. "\nLater changes on the source may not be replicated on the destination"),
  43. 'start_run': fields.datetime('Time started', readonly=True),
  44. 'last_run': fields.datetime('Time ended', readonly=True),
  45. 'last_record_count': fields.integer('Last record count', readonly=True),
  46. 'last_error_count': fields.integer('Last error count', readonly=True),
  47. 'last_warn_count': fields.integer('Last warning count', readonly=True),
  48. 'last_log': fields.text('Last run log', readonly=True),
  49. 'ignore_rel_errors': fields.boolean('Ignore relationship errors',
  50. help="On error try to reimport rows ignoring relationships."),
  51. 'raise_import_errors': fields.boolean('Raise import errors',
  52. help="Import errors not handled, intended for debugging purposes."
  53. "\nAlso forces debug messages to be written to the server log."),
  54. }
  55. _defaults = {
  56. 'enabled': True,
  57. 'exec_order': 10,
  58. }
  59. def _import_data(self, cr, uid, flds, data, model_obj, table_obj, log):
  60. """Import data and returns error msg or empty string"""
  61. def find_m2o(field_list):
  62. """"Find index of first column with a one2many field"""
  63. for i, x in enumerate(field_list):
  64. if len(x) > 3 and x[-3:] == ':id' or x[-3:] == '/id':
  65. return i
  66. return -1
  67. def append_to_log(log, level, obj_id='', msg='', rel_id=''):
  68. if '_id_' in obj_id:
  69. obj_id = '.'.join(obj_id.split('_')[:-2]) + ': ' + obj_id.split('_')[-1]
  70. if ': .' in msg and not rel_id:
  71. rel_id = msg[msg.find(': .')+3:]
  72. if '_id_' in rel_id:
  73. rel_id = '.'.join(rel_id.split('_')[:-2]) + ': ' + rel_id.split('_')[-1]
  74. msg = msg[:msg.find(': .')]
  75. log['last_log'].append('%s|%s\t|%s\t|%s' % (level.ljust(5), obj_id, rel_id, msg))
  76. _logger.debug(data)
  77. cols = list(flds) # copy to avoid side effects
  78. errmsg = str()
  79. if table_obj.raise_import_errors:
  80. model_obj.import_data(cr, uid, cols, [data], noupdate=table_obj.noupdate)
  81. else:
  82. try:
  83. model_obj.import_data(cr, uid, cols, [data], noupdate=table_obj.noupdate)
  84. except:
  85. errmsg = str(sys.exc_info()[1])
  86. if errmsg and not table_obj.ignore_rel_errors:
  87. # Fail
  88. append_to_log(log, 'ERROR', data, errmsg)
  89. log['last_error_count'] += 1
  90. return False
  91. if errmsg and table_obj.ignore_rel_errors:
  92. # Warn and retry ignoring many2one fields...
  93. append_to_log(log, 'WARN', data, errmsg)
  94. log['last_warn_count'] += 1
  95. # Try ignoring each many2one (tip: in the SQL sentence select more problematic FKs first)
  96. i = find_m2o(cols)
  97. if i >= 0:
  98. # Try again without the [i] column
  99. del cols[i]
  100. del data[i]
  101. self._import_data(cr, uid, cols, data, model_obj, table_obj, log)
  102. else:
  103. # Fail
  104. append_to_log(log, 'ERROR', data, 'Removed all m2o keys and still fails.')
  105. log['last_error_count'] += 1
  106. return False
  107. return True
  108. def import_run(self, cr, uid, ids=None, context=None):
  109. db_model = self.pool.get('base.external.dbsource')
  110. actions = self.read(cr, uid, ids, ['id', 'exec_order'])
  111. actions.sort(key=lambda x: (x['exec_order'], x['id']))
  112. # Consider each dbtable:
  113. for action_ref in actions:
  114. obj = self.browse(cr, uid, action_ref['id'])
  115. if not obj.enabled:
  116. continue # skip
  117. _logger.setLevel(obj.raise_import_errors and logging.DEBUG or _loglvl)
  118. _logger.debug('Importing %s...' % obj.name)
  119. # now() microseconds are stripped to avoid problem with SQL smalldate
  120. # TODO: convert UTC Now to local timezone
  121. # http://stackoverflow.com/questions/4770297/python-convert-utc-datetime-string-to-local-datetime
  122. model_name = obj.model_target.model
  123. model_obj = self.pool.get(model_name)
  124. xml_prefix = model_name.replace('.', '_') + "_id_"
  125. log = {'start_run': datetime.now().replace(microsecond=0),
  126. 'last_run': None,
  127. 'last_record_count': 0,
  128. 'last_error_count': 0,
  129. 'last_warn_count': 0,
  130. 'last_log': list()}
  131. self.write(cr, uid, [obj.id], log)
  132. # Prepare SQL sentence; replace "%s" with the last_sync date
  133. if obj.last_sync:
  134. sync = datetime.strptime(obj.last_sync, "%Y-%m-%d %H:%M:%S")
  135. else:
  136. sync = datetime.datetime(1900, 1, 1, 0, 0, 0)
  137. params = {'sync': sync}
  138. res = db_model.execute(cr, uid, [obj.dbsource_id.id],
  139. obj.sql_source, params, metadata=True)
  140. # Exclude columns titled "None"; add (xml_)"id" column
  141. cidx = [i for i, x in enumerate(res['cols']) if x.upper() != 'NONE']
  142. cols = [x for i, x in enumerate(res['cols']) if x.upper() != 'NONE'] + ['id']
  143. # Import each row:
  144. for row in res['rows']:
  145. # Build data row; import only columns present in the "cols" list
  146. data = list()
  147. for i in cidx:
  148. # TODO: Handle imported datetimes properly - convert from localtime to UTC!
  149. v = row[i]
  150. if isinstance(v, str):
  151. v = v.strip()
  152. data.append(v)
  153. data.append(xml_prefix + str(row[0]).strip())
  154. # Import the row; on error, write line to the log
  155. log['last_record_count'] += 1
  156. self._import_data(cr, uid, cols, data, model_obj, obj, log)
  157. if log['last_record_count'] % 500 == 0:
  158. _logger.info('...%s rows processed...' % (log['last_record_count']))
  159. # Finished importing all rows
  160. # If no errors, write new sync date
  161. if not (log['last_error_count'] or log['last_warn_count']):
  162. log['last_sync'] = log['start_run']
  163. level = logging.DEBUG
  164. if log['last_warn_count']:
  165. level = logging.WARN
  166. if log['last_error_count']:
  167. level = logging.ERROR
  168. _logger.log(level, 'Imported %s , %d rows, %d errors, %d warnings.' % (
  169. model_name, log['last_record_count'], log['last_error_count'],
  170. log['last_warn_count']))
  171. # Write run log, either if the table import is active or inactive
  172. if log['last_log']:
  173. log['last_log'].insert(0, 'LEVEL|== Line == |== Relationship ==|== Message ==')
  174. log.update({'last_log': '\n'.join(log['last_log'])})
  175. log.update({'last_run': datetime.now().replace(microsecond=0)})
  176. self.write(cr, uid, [obj.id], log)
  177. # Finished
  178. _logger.debug('Import job FINISHED.')
  179. return True
  180. def import_schedule(self, cr, uid, ids, context=None):
  181. cron_obj = self.pool.get('ir.cron')
  182. new_create_id = cron_obj.create(cr, uid, {
  183. 'name': 'Import ODBC tables',
  184. 'interval_type': 'hours',
  185. 'interval_number': 1,
  186. 'numbercall': -1,
  187. 'model': 'import.odbc.dbtable',
  188. 'function': 'import_run',
  189. 'doall': False,
  190. 'active': True
  191. })
  192. return {
  193. 'name': 'Import ODBC tables',
  194. 'view_type': 'form',
  195. 'view_mode': 'form,tree',
  196. 'res_model': 'ir.cron',
  197. 'res_id': new_create_id,
  198. 'type': 'ir.actions.act_window',
  199. }