convertStringValueToProvidedType<T> method

T? convertStringValueToProvidedType<T>(
  1. String? value, [
  2. int? columnLength
])

Implementation

T? convertStringValueToProvidedType<T>(String? value, [int? columnLength]) {
  if (value == null) {
    return null;
  }

  if (T == String || T == dynamic) {
    return value as T;
  }

  if (T == bool) {
    if (_value == mysqlColumnTypeTiny && columnLength == 1) {
      return int.parse(value) > 0 as T;
    } else {
      throw MySQLProtocolException(
        "Can not convert MySQL type $_value to requested type bool",
      );
    }
  }

  // convert to int
  if (T == int) {
    switch (_value) {
      // types convertible to dart int
      case mysqlColumnTypeTiny:
      case mysqlColumnTypeShort:
      case mysqlColumnTypeLong:
      case mysqlColumnTypeLongLong:
      case mysqlColumnTypeInt24:
      case mysqlColumnTypeYear:
        return int.parse(value) as T;
      default:
        throw MySQLProtocolException(
          "Can not convert MySQL type $_value to requested type int",
        );
    }
  }

  if (T == double) {
    switch (_value) {
      case mysqlColumnTypeTiny:
      case mysqlColumnTypeShort:
      case mysqlColumnTypeLong:
      case mysqlColumnTypeLongLong:
      case mysqlColumnTypeInt24:
      case mysqlColumnTypeFloat:
      case mysqlColumnTypeDouble:
        return double.parse(value) as T;
      default:
        throw MySQLProtocolException(
          "Can not convert MySQL type $_value to requested type double",
        );
    }
  }

  if (T == num) {
    switch (_value) {
      case mysqlColumnTypeTiny:
      case mysqlColumnTypeShort:
      case mysqlColumnTypeLong:
      case mysqlColumnTypeLongLong:
      case mysqlColumnTypeInt24:
      case mysqlColumnTypeFloat:
      case mysqlColumnTypeDouble:
        return num.parse(value) as T;
      default:
        throw MySQLProtocolException(
          "Can not convert MySQL type $_value to requested type num",
        );
    }
  }

  throw MySQLProtocolException(
    "Can not convert MySQL type ${T.runtimeType} to requested type int",
  );
}