Sha256: fa60d3071ea3fdc8925ae594a6a5e1fdbabb145da466a5b62eef472957243e77

Contents?: true

Size: 1.08 KB

Versions: 4

Compression:

Stored size: 1.08 KB

Contents

# frozen_string_literal: true

module Decidim
  module ActionDelegator
    class JsonBuildObjectQuery
      def initialize(json_args, query_field, aliaz)
        @json_args = json_args
        @query_field = query_field
        @aliaz = aliaz
      end

      def to_sql
        Arel::Nodes::InfixOperation.new(
          "->>",
          json_build_object(json_args),
          cast(query_field, :text)
        ).as(aliaz).to_sql
      end

      private

      attr_reader :json_args, :query_field, :aliaz

      # Returns the equivalent of `JSON_BUILD_OBJECT (ARRAY)` in Arel
      def json_build_object(array)
        Arel::Nodes::NamedFunction.new(
          "JSON_BUILD_OBJECT",
          [array]
        )
      end

      # Returns the equivalent of `CAST ((<exprs>) AS <type>)` in Arel
      def cast(*exprs, type)
        Arel::Nodes::NamedFunction.new(
          "CAST",
          [Arel::Nodes::As.new(Arel::Nodes::Grouping.new(exprs), Arel.sql(type.to_s.upcase))]
        )
      end

      def coalesce(*exprs)
        Arel::Nodes::NamedFunction.new("COALESCE", exprs)
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
decidim-action_delegator-0.6.0 app/queries/decidim/action_delegator/json_build_object_query.rb
decidim-action_delegator-0.5.0 app/queries/decidim/action_delegator/json_build_object_query.rb
decidim-action_delegator-0.4.1 app/queries/decidim/action_delegator/json_build_object_query.rb
decidim-action_delegator-0.4 app/queries/decidim/action_delegator/json_build_object_query.rb