BigW Consortium Gitlab

date_time.rb 1.32 KB
Newer Older
1 2 3 4 5 6 7 8 9
module Gitlab
  module Database
    module DateTime
      # Find the first of the `end_time_attrs` that isn't `NULL`. Subtract from it
      # the first of the `start_time_attrs` that isn't NULL. `SELECT` the resulting interval
      # along with an alias specified by the `as` parameter.
      #
      # Note: For MySQL, the interval is returned in seconds.
      #       For PostgreSQL, the interval is returned as an INTERVAL type.
10
      def subtract_datetimes(query_so_far, start_time_attrs, end_time_attrs, as)
James Lopez committed
11
        diff_fn = subtract_datetimes_diff(query_so_far, start_time_attrs, end_time_attrs)
12 13 14

        query_so_far.project(diff_fn.as(as))
      end
15

16
      def subtract_datetimes_diff(query_so_far, start_time_attrs, end_time_attrs)
17 18 19 20 21 22 23 24 25 26 27 28
        if Gitlab::Database.postgresql?
          Arel::Nodes::Subtraction.new(
            Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(end_time_attrs)),
            Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(start_time_attrs)))
        elsif Gitlab::Database.mysql?
          Arel::Nodes::NamedFunction.new(
            "TIMESTAMPDIFF",
            [Arel.sql('second'),
             Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(start_time_attrs)),
             Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(end_time_attrs))])
        end
      end
29 30 31
    end
  end
end