mariadb_json_columns.rb 1.3 KB

1234567891011121314151617181920212223242526272829303132333435
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. require 'active_record/connection_adapters/abstract_mysql_adapter'
  3. ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter.class_eval do
  4. private
  5. alias_method :column_definitions_original, :column_definitions
  6. def column_definitions(table_name)
  7. result = column_definitions_original(table_name)
  8. if mariadb?
  9. result.each do |row|
  10. next if row[:Type] != 'longtext'
  11. next if !mariadb_column_json?(table_name, row[:Field])
  12. row[:Type] = 'json'
  13. end
  14. end
  15. result
  16. end
  17. # https://github.com/zammad/zammad/issues/4148
  18. # JSON columns in mariadb are listed as longtext, so we need to check
  19. # the constraint checks to find out if the column was created as json.
  20. # Based on this detection we will hack the type so rails will handle
  21. # values properly as json values.
  22. def mariadb_column_json?(table_name, field_name)
  23. field = quote(field_name)
  24. scope = quoted_scope(table_name)
  25. execute_and_free("SELECT 1 FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS WHERE TABLE_NAME = #{scope[:name]} AND CONSTRAINT_SCHEMA = #{scope[:schema]} AND CONSTRAINT_NAME = #{field} AND CHECK_CLAUSE LIKE '%json_valid%'") do |r|
  26. return r.to_a.present?
  27. end
  28. end
  29. end