Skip to content

Commit

Permalink
Autodetect type from parameter value. (#154)
Browse files Browse the repository at this point in the history
  • Loading branch information
isoos authored Oct 12, 2023
1 parent 9f79852 commit 0287791
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
16 changes: 16 additions & 0 deletions lib/src/v3/query_description.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,22 @@ class InternalQueryDescription implements PgSql {
return value;
} else if (knownType != null) {
return PgTypedParameter(knownType, value);
} else if (value == null) {
return PgTypedParameter(PgDataType.voidType, value);
} else if (value is String) {
return PgTypedParameter(PgDataType.varChar, value);
} else if (value is bool) {
return PgTypedParameter(PgDataType.boolean, value);
} else if (value is int && value.bitLength <= 16) {
return PgTypedParameter(PgDataType.smallInteger, value);
} else if (value is int && value.bitLength <= 32) {
return PgTypedParameter(PgDataType.integer, value);
} else if (value is int && value.bitLength <= 64) {
return PgTypedParameter(PgDataType.bigInteger, value);
} else if (value is double) {
return PgTypedParameter(PgDataType.double, value);
} else if (value is DateTime) {
return PgTypedParameter(PgDataType.timestampWithoutTimezone, value);
} else {
throw ArgumentError.value(
value,
Expand Down
17 changes: 11 additions & 6 deletions test/variable_tokenizer_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@ void main() {
PgTypedParameter(PgDataType.text, 'z'),
],
);
expect(() => desc.bindParameters({'x': 4, 'y': true, 'z': 'z'}),
throwsArgumentError,
reason: 'No data type given for z');
expect(desc.bindParameters({'x': 4, 'y': true, 'z': 'z'}), [
PgTypedParameter(PgDataType.bigInteger, 4),
PgTypedParameter(PgDataType.boolean, true),
PgTypedParameter(PgDataType.varChar, 'z'),
]);

// Make sure we can still bind by index
expect(
Expand All @@ -42,9 +44,12 @@ void main() {
],
);
expect(
() => desc.bindParameters([1, true, 3]),
throwsArgumentError,
reason: 'No data type given for third parameter',
desc.bindParameters([1, true, 3]),
[
PgTypedParameter(PgDataType.bigInteger, 1),
PgTypedParameter(PgDataType.boolean, true),
PgTypedParameter(PgDataType.smallInteger, 3),
],
);
});

Expand Down

0 comments on commit 0287791

Please sign in to comment.