module Sequel::SQL::StringAgg::DatasetMethods

  1. lib/sequel/extensions/string_agg.rb

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

Methods

Public Instance

  1. string_agg_sql_append

Public Instance methods

string_agg_sql_append(sql, sa)

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

[show source]
    # File lib/sequel/extensions/string_agg.rb
 87 def string_agg_sql_append(sql, sa)
 88   if defined?(super)
 89     return super
 90   end
 91 
 92   expr = sa.expr
 93   separator = sa.separator || ","
 94   order = sa.order_expr
 95   distinct = sa.is_distinct?
 96 
 97   case db_type = db.database_type
 98   when :sqlite
 99     raise Error, "string_agg(DISTINCT) is not supported with a non-comma separator on #{db.database_type}" if distinct && separator != ","
100 
101     args = [expr]
102     args << separator unless distinct
103     f = Function.new(:group_concat, *args)
104     if order
105       f = f.order(*order)
106     end
107     if distinct
108       f = f.distinct
109     end
110     literal_append(sql, f)
111   when :postgres, :sqlanywhere
112     f = Function.new(db_type == :postgres ? :string_agg : :list, expr, separator)
113     if order
114       f = f.order(*order)
115     end
116     if distinct
117       f = f.distinct
118     end
119     literal_append(sql, f)
120   when :mysql, :hsqldb, :h2
121     sql << "GROUP_CONCAT("
122     if distinct
123       sql << "DISTINCT "
124     end
125     literal_append(sql, expr)
126     if order
127       sql << " ORDER BY "
128       expression_list_append(sql, order)
129     end
130     sql << " SEPARATOR "
131     literal_append(sql, separator)
132     sql << ")"
133   when :oracle, :db2
134     if distinct
135       raise Error, "string_agg with distinct is not implemented on #{db.database_type}"
136     end
137     literal_append(sql, Function.new(:listagg, expr, separator))
138     if order
139       sql << " WITHIN GROUP (ORDER BY "
140       expression_list_append(sql, order)
141       sql << ")"
142     else
143       sql << " WITHIN GROUP (ORDER BY 1)"
144     end
145   else
146     raise Error, "string_agg is not implemented on #{db.database_type}"
147   end
148 end