mapToSqlLiteral method

String mapToSqlLiteral(
  1. Object? dart
)

Maps the dart value into a SQL literal that can be embedded in SQL queries.

Implementation

String mapToSqlLiteral(Object? dart) {
  if (dart == null) return 'NULL';

  // todo: Inline and remove types in the next major drift version
  if (dart is bool) {
    if (dialect == SqlDialect.sqlite) {
      return dart ? '1' : '0';
    } else {
      return dart ? 'true' : 'false';
    }
  } else if (dart is String) {
    // From the sqlite docs: (https://www.sqlite.org/lang_expr.html)
    // A string constant is formed by enclosing the string in single quotes
    // (').
    // A single quote within the string can be encoded by putting two single
    // quotes in a row - as in Pascal. C-style escapes using the backslash
    // character are not supported because they are not standard SQL.
    final escapedChars = dart.replaceAll('\'', '\'\'');
    return "'$escapedChars'";
  } else if (dart is num || dart is BigInt) {
    return dart.toString();
  } else if (dart is DateTime) {
    if (storeDateTimesAsText) {
      final encoded = mapToSqlVariable(dart).toString();
      return "'$encoded'";
    } else {
      return (dart.millisecondsSinceEpoch ~/ 1000).toString();
    }
  } else if (dart is Uint8List) {
    final String hexString = hex.encode(dart);

    if (dialect == SqlDialect.postgres) {
      // Postgres BYTEA hex format
      // https://www.postgresql.org/docs/current/datatype-binary.html#DATATYPE-BINARY-BYTEA-HEX-FORMAT
      return "'\\x$hexString'::bytea";
    } else {
      // BLOB literals are string literals containing hexadecimal data and
      // preceded by a single "x" or "X" character. Example: X'53514C697465'
      return "x'$hexString'";
    }
  } else if (dart is DriftAny) {
    return mapToSqlLiteral(dart.rawSqlValue);
  }

  throw ArgumentError.value(dart, 'dart',
      'Must be null, bool, String, int, DateTime, Uint8List or double');
}