Module: Findbug::AdapterHelper
- Defined in:
- lib/findbug/adapter_helper.rb
Class Method Summary collapse
- .adapter_name ⇒ Object
-
.date_trunc_sql(interval, column) ⇒ Object
Returns adapter-specific SQL to truncate a timestamp column to an interval.
-
.json_column_type ⇒ Object
Returns the appropriate column type symbol for JSON storage.
-
.json_default(value) ⇒ Object
Returns an adapter-appropriate column default for a JSON field.
- .mysql? ⇒ Boolean
- .postgresql? ⇒ Boolean
- .sqlite? ⇒ Boolean
Class Method Details
.adapter_name ⇒ Object
5 6 7 8 9 |
# File 'lib/findbug/adapter_helper.rb', line 5 def self.adapter_name ActiveRecord::Base.connection.adapter_name.downcase rescue StandardError "postgresql" end |
.date_trunc_sql(interval, column) ⇒ Object
Returns adapter-specific SQL to truncate a timestamp column to an interval. interval: ‘minute’, ‘hour’, or ‘day’ (anything else falls back to ‘hour’) column: SQL column name, e.g. ‘captured_at’
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/findbug/adapter_helper.rb', line 54 def self.date_trunc_sql(interval, column) bucket = %w[minute hour day].include?(interval) ? interval : "hour" if postgresql? "date_trunc('#{bucket}', #{column})" elsif mysql? case bucket when "minute" then "DATE_FORMAT(#{column}, '%Y-%m-%d %H:%i:00')" when "day" then "DATE(#{column})" else "DATE_FORMAT(#{column}, '%Y-%m-%d %H:00:00')" end else # SQLite and unknown adapters case bucket when "minute" then "strftime('%Y-%m-%d %H:%M:00', #{column})" when "day" then "DATE(#{column})" else "strftime('%Y-%m-%d %H:00:00', #{column})" end end end |
.json_column_type ⇒ Object
Returns the appropriate column type symbol for JSON storage. :jsonb on PostgreSQL, :json on MySQL, :text on SQLite.
26 27 28 29 30 31 32 33 34 |
# File 'lib/findbug/adapter_helper.rb', line 26 def self.json_column_type if postgresql? :jsonb elsif mysql? :json else :text end end |
.json_default(value) ⇒ Object
Returns an adapter-appropriate column default for a JSON field.
PostgreSQL jsonb accepts a Hash/Array directly. MySQL JSON columns don’t support DEFAULT values (pre-8.0.13), so we return nil. SQLite text columns need a JSON-encoded String.
41 42 43 44 45 46 47 48 49 |
# File 'lib/findbug/adapter_helper.rb', line 41 def self.json_default(value) if postgresql? value elsif mysql? nil else value.to_json end end |
.mysql? ⇒ Boolean
16 17 18 |
# File 'lib/findbug/adapter_helper.rb', line 16 def self.mysql? adapter_name.include?("mysql") end |
.postgresql? ⇒ Boolean
11 12 13 14 |
# File 'lib/findbug/adapter_helper.rb', line 11 def self.postgresql? name = adapter_name name.include?("postgresql") || name.include?("postgis") end |
.sqlite? ⇒ Boolean
20 21 22 |
# File 'lib/findbug/adapter_helper.rb', line 20 def self.sqlite? adapter_name.include?("sqlite") end |