mapToSqlVariable method

Object? mapToSqlVariable(
  1. Object? dartValue
)

Maps a Dart object to a (possibly simpler) object that can be used as a parameter in raw sql queries.

Implementation

Object? mapToSqlVariable(Object? dartValue) {
  if (dartValue == null) return null;

  // These need special handling, all other types are a direct mapping
  if (dartValue is DateTime) {
    if (storeDateTimesAsText) {
      // sqlite3 assumes UTC by default, so we store the explicit UTC offset
      // along with the value. For UTC datetimes, there's nothing to change
      if (dartValue.isUtc) {
        return dartValue.toIso8601String();
      } else {
        final offset = dartValue.timeZoneOffset;
        // Quick sanity check: We can only store the UTC offset as `hh:mm`,
        // so if the offset has seconds for some reason we should refuse to
        // store that.
        if (offset.inSeconds - 60 * offset.inMinutes != 0) {
          throw ArgumentError.value(dartValue, 'dartValue',
              'Cannot be mapped to SQL: Invalid UTC offset $offset');
        }

        final hours = offset.inHours.abs();
        final minutes = offset.inMinutes.abs() - 60 * hours;

        // For local date times, add the offset as ` +hh:mm` in the end. This
        // format is understood by `DateTime.parse` and date time functions in
        // sqlite.
        final prefix = offset.isNegative ? ' -' : ' +';
        final formattedOffset = '${hours.toString().padLeft(2, '0')}:'
            '${minutes.toString().padLeft(2, '0')}';

        return '${dartValue.toIso8601String()}$prefix$formattedOffset';
      }
    } else {
      return dartValue.millisecondsSinceEpoch ~/ 1000;
    }
  }

  if (dartValue is bool && dialect == SqlDialect.sqlite) {
    return dartValue ? 1 : 0;
  }

  if (dartValue is DriftAny) {
    return dartValue.rawSqlValue;
  }

  return dartValue;
}