parsePgTextArray static method

List<String?> parsePgTextArray(
  1. String text
)

Parse a PostgreSQL text-format array literal ({A,B,"c d",NULL}) into a List of element strings.

Implementation

static List<String?> parsePgTextArray(String text) {
  final inner = text.substring(1, text.length - 1);
  if (inner.isEmpty) return <String?>[];

  final elements = <String?>[];
  final current = StringBuffer();
  var inQuotes = false;
  var wasQuoted = false;
  for (var i = 0; i < inner.length; i++) {
    final ch = inner[i];
    if (inQuotes) {
      if (ch == r'\') {
        i++;
        if (i < inner.length) current.write(inner[i]);
      } else if (ch == '"') {
        inQuotes = false;
      } else {
        current.write(ch);
      }
    } else if (ch == '"') {
      inQuotes = true;
      wasQuoted = true;
    } else if (ch == ',') {
      final raw = current.toString();
      elements.add(!wasQuoted && raw == 'NULL' ? null : raw);
      current.clear();
      wasQuoted = false;
    } else {
      current.write(ch);
    }
  }
  final raw = current.toString();
  elements.add(!wasQuoted && raw == 'NULL' ? null : raw);
  return elements;
}