Method: Sequel::Dataset#window_sql_append

Defined in:
lib/sequel/dataset/sql.rb

#window_sql_append(sql, opts) ⇒ Object

Append literalization of windows (for window functions) to SQL string.

Raises:

[View source]

788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
# File 'lib/sequel/dataset/sql.rb', line 788

def window_sql_append(sql, opts)
  raise(Error, 'This dataset does not support window functions') unless supports_window_functions?
  space = false
  space_s = ' '

  sql << '('

  if window = opts[:window]
    literal_append(sql, window)
    space = true
  end

  if part = opts[:partition]
    sql << space_s if space
    sql << "PARTITION BY "
    expression_list_append(sql, Array(part))
    space = true
  end

  if order = opts[:order]
    sql << space_s if space
    sql << "ORDER BY "
    expression_list_append(sql, Array(order))
    space = true
  end

  if frame = opts[:frame]
    sql << space_s if space

    if frame.is_a?(String)
      sql << frame
    else
      case frame
      when :all
        frame_type = :rows
        frame_start = :preceding
        frame_end = :following
      when :rows, :range, :groups
        frame_type = frame
        frame_start = :preceding
        frame_end = :current
      when Hash
        frame_type = frame[:type]
        unless frame_type == :rows || frame_type == :range || frame_type == :groups
          raise Error, "invalid window :frame :type option: #{frame_type.inspect}"
        end
        unless frame_start = frame[:start]
          raise Error, "invalid window :frame :start option: #{frame_start.inspect}"
        end
        frame_end = frame[:end]
        frame_exclude = frame[:exclude]
      else
        raise Error, "invalid window :frame option: #{frame.inspect}"
      end

      sql << frame_type.to_s.upcase << " "
      sql << 'BETWEEN ' if frame_end
      window_frame_boundary_sql_append(sql, frame_start, :preceding)
      if frame_end
        sql << " AND "
        window_frame_boundary_sql_append(sql, frame_end, :following)
      end

      if frame_exclude
        sql << " EXCLUDE "

        case frame_exclude
        when :current
          sql << "CURRENT ROW"
        when :group
          sql << "GROUP"
        when :ties
          sql << "TIES"
        when :no_others
          sql << "NO OTHERS"
        else
          raise Error, "invalid window :frame :exclude option: #{frame_exclude.inspect}"
        end
      end
    end
  end

  sql << ')'
end