Support mapping BLOBs to literals

This commit is contained in:
Simon Binder 2019-09-29 15:18:11 +02:00
parent 059fc69893
commit 308167dc12
No known key found for this signature in database
GPG Key ID: 7891917E4147B8C0
4 changed files with 31 additions and 4 deletions

View File

@ -53,7 +53,7 @@ TODO: Describe ffi port
### Minor changes
- a `Constant<String>` can now be written to SQL, it used to throw before. This is useful
if you need default values for strings columns.
if you need default values for strings columns. This also works for `BLOBS`.
- new `LazyDatabase` when you want to construct a database asynchronously (for instance, if
you first need to find a file before you can open a database).

View File

@ -1,5 +1,7 @@
import 'dart:typed_data';
import 'package:convert/convert.dart';
part 'custom_type.dart';
/// A type that can be mapped from Dart to sql. The generic type parameter here
@ -118,12 +120,14 @@ class BlobType extends SqlType<Uint8List> {
mapFromDatabaseResponse(response) => response as Uint8List;
@override
String mapToSqlConstant(content) {
throw UnimplementedError("Blobs can't be mapped to sql literals");
String mapToSqlConstant(Uint8List content) {
// BLOB literals are string literals containing hexadecimal data and
// preceded by a single "x" or "X" character. Example: X'53514C697465'
return "x'${hex.encode(content)}'";
}
@override
mapToSqlVariable(content) => content;
mapToSqlVariable(Uint8List content) => content;
}
class RealType extends SqlType<double> {

View File

@ -13,6 +13,7 @@ environment:
dependencies:
meta: ^1.0.0
convert: ^2.1.1
collection: ^1.0.0
synchronized: ^2.1.0
pedantic: ^1.0.0

View File

@ -0,0 +1,22 @@
import 'dart:convert';
import 'package:moor/moor.dart';
import 'package:test/test.dart';
void main() {
test('maps without transormation', () {
const type = BlobType();
final data = Uint8List.fromList(List.generate(256, (i) => i));
expect(type.mapToSqlVariable(data), data);
expect(type.mapFromDatabaseResponse(data), data);
});
test('writes blob literals', () {
const type = BlobType();
const hex = '67656E6572616C206B656E6F626921';
final data = Uint8List.fromList(utf8.encode('general kenobi!'));
expect(type.mapToSqlConstant(data), equalsIgnoringCase("x'$hex'"));
});
}