convertCell function

dynamic convertCell(
  1. String type,
  2. dynamic value
)

If the value of the cell is null, returns null. Otherwise converts the string value to the correct type.

type A postgres column type stringValue The cell value

@example convertCell('bool', 'true')
=> true
@example convertCell('int8', '10')
=> 10
@example convertCell('_int4', '{1,2,3,4}')
=> [1,2,3,4]

Implementation

dynamic convertCell(String type, dynamic value) {
  // if data type is an array
  if (type[0] == '_') {
    final dataType = type.substring(1);
    return toArray(value, dataType);
  }

  final typeEnum = PostgresTypes.values
      .firstWhereOrNull((e) => e.toString() == 'PostgresTypes.$type');
  // If not null, convert to correct type.
  switch (typeEnum) {
    case PostgresTypes.bool:
      return toBoolean(value);
    case PostgresTypes.float4:
    case PostgresTypes.float8:
    case PostgresTypes.numeric:
      return toDouble(value);
    case PostgresTypes.int2:
    case PostgresTypes.int4:
    case PostgresTypes.int8:
    case PostgresTypes.oid:
      return toInt(value);
    case PostgresTypes.json:
    case PostgresTypes.jsonb:
      return toJson(value);
    case PostgresTypes.timestamp:
      return toTimestampString(
        value.toString(),
      ); // Format to be consistent with PostgREST
    case PostgresTypes.abstime: // To allow users to cast it based on Timezone
    case PostgresTypes.date: // To allow users to cast it based on Timezone
    case PostgresTypes.daterange:
    case PostgresTypes.int4range:
    case PostgresTypes.int8range:
    case PostgresTypes.money:
    case PostgresTypes.reltime: // To allow users to cast it based on Timezone
    case PostgresTypes.text:
    case PostgresTypes.time: // To allow users to cast it based on Timezone
    case PostgresTypes
        .timestamptz: // To allow users to cast it based on Timezone
    case PostgresTypes.timetz: // To allow users to cast it based on Timezone
    case PostgresTypes.tsrange:
    case PostgresTypes.tstzrange:
      return noop(value);
    default:
      // Return the value for remaining types
      return noop(value);
  }
}