Skip to content

Commit

Permalink
Support bytea sql literal in postgres (#2943)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmartos96 committed Apr 6, 2024
1 parent 37f120d commit 039838b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 14 deletions.
14 changes: 11 additions & 3 deletions drift/lib/src/runtime/types/mapping.dart
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,17 @@ final class SqlTypes {
return (dart.millisecondsSinceEpoch ~/ 1000).toString();
}
} else if (dart is Uint8List) {
// BLOB literals are string literals containing hexadecimal data and
// preceded by a single "x" or "X" character. Example: X'53514C697465'
return "x'${hex.encode(dart)}'";
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'${hex.encode(dart)}'";
}
} else if (dart is DriftAny) {
return mapToSqlLiteral(dart.rawSqlValue);
}
Expand Down
24 changes: 13 additions & 11 deletions extras/drift_postgres/test/types_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -26,19 +26,19 @@ void main() {
return row.read(expression)!;
}

group('custom types pass through', () {
void testWith<T extends Object>(CustomSqlType<T> type, T value) {
test('with variable', () async {
final variable = Variable(value, type);
expect(await eval(variable), value);
});
void testWith<T extends Object>(CustomSqlType<T>? type, T value) {
test('with variable', () async {
final variable = Variable(value, type);
expect(await eval(variable), value);
});

test('with constant', () async {
final constant = Constant(value, type);
expect(await eval(constant), value);
});
}
test('with constant', () async {
final constant = Constant(value, type);
expect(await eval(constant), value);
});
}

group('custom types pass through', () {
group('uuid', () => testWith(PgTypes.uuid, Uuid().v4obj()));
group(
'interval',
Expand All @@ -60,6 +60,8 @@ void main() {
);
});

group('bytea', () => testWith(null, Uint8List.fromList([1, 2, 3, 4, 5])));

test('compare datetimes', () async {
final time = DateTime.now();
final before = Variable(
Expand Down

0 comments on commit 039838b

Please sign in to comment.