Module: Sequel::SQL::StringAgg::DatasetMethods

Defined in:
lib/sequel/extensions/string_agg.rb

Overview

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

Instance Method Summary collapse

Instance Method Details

#string_agg_sql_append(sql, sa) ⇒ Object

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



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# 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)
  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