module Sequel::SQL::StringAgg::DatasetMethods

These methods are added to datasets using the string_agg extension, for the purposes of correctly literalizing StringAgg expressions for the appropriate database type.

Public Instance Methods

string_agg_sql_append(sql, sa) click to toggle source

Append the SQL fragment for the StringAgg expression to the SQL query.

Calls superclass method
# File lib/sequel/extensions/string_agg.rb, line 87
def string_agg_sql_append(sql, sa)
  if defined?(super)
    return super
  end

  expr = sa.expr
  separator = sa.separator || ","
  order = sa.order_expr
  distinct = sa.is_distinct?

  case db_type = db.database_type
  when :postgres, :sqlanywhere
    f = Function.new(db_type == :postgres ? :string_agg : :list, expr, separator)
    if order
      f = f.order(*order)
    end
    if distinct
      f = f.distinct
    end
    literal_append(sql, f)
  # SEQUEL5: Remove cubrid
  when :mysql, :hsqldb, :cubrid, :h2
    sql << "GROUP_CONCAT("
    if distinct
      sql << "DISTINCT "
    end
    literal_append(sql, expr)
    if order
      sql << " ORDER BY "
      expression_list_append(sql, order)
    end
    sql << " SEPARATOR "
    literal_append(sql, separator)
    sql << ")"
  when :oracle, :db2
    if distinct
      raise Error, "string_agg with distinct is not implemented on #{db.database_type}"
    end
    literal_append(sql, Function.new(:listagg, expr, separator))
    if order
      sql << " WITHIN GROUP (ORDER BY "
      expression_list_append(sql, order)
      sql << ")"
    else
      sql << " WITHIN GROUP (ORDER BY 1)"
    end
  else
    raise Error, "string_agg is not implemented on #{db.database_type}"
  end
end