20181017000001_cti_generic_api2.rb 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. class CtiGenericApi2 < ActiveRecord::Migration[5.1]
  2. def up
  3. # return if it's a new setup
  4. return if !Setting.exists?(name: 'system_init_done')
  5. return if !column_exists?(:cti_logs, :initialized_at)
  6. return if column_exists?(:cti_logs, :initialized_at_cleanup)
  7. if ActiveRecord::Base.connection_config[:adapter] == 'mysql2'
  8. # disable the MySQL strict_mode for the current connection
  9. execute("SET sql_mode = ''")
  10. add_column :cti_logs, :initialized_at_cleanup, :timestamp, limit: 3, null: true, default: '0000-00-00 00:00:00'
  11. else
  12. add_column :cti_logs, :initialized_at_cleanup, :timestamp, limit: 3, null: true
  13. end
  14. Cti::Log.connection.schema_cache.clear!
  15. Cti::Log.reset_column_information
  16. # clenaup table records
  17. Cti::Log.order(created_at: :desc).limit(2000).each do |log|
  18. if log.initialized_at
  19. begin
  20. initialized_at = Time.zone.parse(log.initialized_at)
  21. log.update_column(:initialized_at_cleanup, initialized_at) # rubocop:disable Rails/SkipsModelValidations
  22. if initialized_at && log.start_at
  23. log.update_column(:duration_waiting_time, log.start_at.to_i - initialized_at.to_i) # rubocop:disable Rails/SkipsModelValidations
  24. else
  25. log.update_column(:duration_waiting_time, nil) # rubocop:disable Rails/SkipsModelValidations
  26. end
  27. rescue => e
  28. Rails.logger.error e
  29. end
  30. end
  31. if log.end_at && log.start_at
  32. log.update_column(:duration_talking_time, log.end_at.to_i - log.start_at.to_i) # rubocop:disable Rails/SkipsModelValidations
  33. else
  34. log.update_column(:duration_talking_time, nil) # rubocop:disable Rails/SkipsModelValidations
  35. end
  36. end
  37. remove_column(:cti_logs, :initialized_at)
  38. Cti::Log.connection.schema_cache.clear!
  39. Cti::Log.reset_column_information
  40. rename_column :cti_logs, :initialized_at_cleanup, :initialized_at
  41. Cti::Log.connection.schema_cache.clear!
  42. Cti::Log.reset_column_information
  43. end
  44. end