Skip to content

Add aggregate expression for column collapse with separator #95

@romankonz

Description

@romankonz

The library exposes per-driver SQL builders for CONCAT, LEAST, SUBSTRING etc., but not the row-collapsing aggregate (GROUP_CONCAT / STRING_AGG). Add it.

API

public function getGroupConcatExpression(
    string $column,
    string $separator,
    bool $escapeValues = false,
): string;

Per-driver SQL

  • MySQL: GROUP_CONCAT(<col> SEPARATOR '<sep>')
  • Postgres: STRING_AGG(<col>::text, '<sep>')
  • SQLite: GROUP_CONCAT(<col>, '<sep>')

The separator is embedded as a SQL string literal (single quotes doubled) — it cannot be a bind parameter because MySQL's SEPARATOR clause requires a literal at parse time.

Value escaping ($escapeValues = true)

Raw GROUP_CONCAT is lossy when any value contains the separator — the result is unsplittable. When $escapeValues = true, wrap the column in two nested REPLACE() calls so backslashes in values become \\ and separator occurrences become \<sep>:

  • MySQL: GROUP_CONCAT(REPLACE(REPLACE(<col>, '\\', '\\\\'), '<sep>', '\\<sep>') SEPARATOR '<sep>')
  • Postgres: STRING_AGG(REPLACE(REPLACE(<col>::text, E'\\', E'\\\\'), '<sep>', E'\\<sep>'), '<sep>')
  • SQLite: same shape as MySQL (no E-string syntax)

Order matters: backslashes must be escaped before the separator, otherwise backslashes introduced by separator-escaping would be doubled.

Default is false — REPLACE on every row isn't free, and the simple form is fine when callers know their data won't contain the separator.

Decoding the escaped output is left to the consumer (walk the string, treat \X as literal X, split on unescaped <sep>).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions