Skip to content

Commit 2e843cb

Browse files
committed
Add precision to time, datetime, and timestamp field types
1 parent 57b8df1 commit 2e843cb

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

ext/mysql2/result.c

+15-3
Original file line numberDiff line numberDiff line change
@@ -287,17 +287,29 @@ static VALUE rb_mysql_result_fetch_field_type(VALUE self, unsigned int idx) {
287287
rb_field_type = rb_sprintf("double(%ld,%d)", field->length, field->decimals);
288288
break;
289289
case MYSQL_TYPE_TIME: // MYSQL_TIME
290-
rb_field_type = rb_str_new_cstr("time");
290+
if (field->decimals == 0) {
291+
rb_field_type = rb_str_new_cstr("time");
292+
} else {
293+
rb_field_type = rb_sprintf("time(%d)", field->decimals);
294+
}
291295
break;
292296
case MYSQL_TYPE_DATE: // MYSQL_TIME
293297
case MYSQL_TYPE_NEWDATE: // MYSQL_TIME
294298
rb_field_type = rb_str_new_cstr("date");
295299
break;
296300
case MYSQL_TYPE_DATETIME: // MYSQL_TIME
297-
rb_field_type = rb_str_new_cstr("datetime");
301+
if (field->decimals == 0) {
302+
rb_field_type = rb_str_new_cstr("datetime");
303+
} else {
304+
rb_field_type = rb_sprintf("datetime(%d)", field->decimals);
305+
}
298306
break;
299307
case MYSQL_TYPE_TIMESTAMP: // MYSQL_TIME
300-
rb_field_type = rb_str_new_cstr("timestamp");
308+
if (field->decimals == 0) {
309+
rb_field_type = rb_str_new_cstr("timestamp");
310+
} else {
311+
rb_field_type = rb_sprintf("timestamp(%d)", field->decimals);
312+
}
301313
break;
302314
case MYSQL_TYPE_DECIMAL: // char[]
303315
case MYSQL_TYPE_NEWDECIMAL: // char[]

spec/mysql2/result_spec.rb

+16
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,22 @@
199199
expect(result.field_types).to eql(expected_types)
200200
end
201201

202+
it "should return precision for timestamps" do
203+
result = @client.query(
204+
"SELECT now(), " \
205+
"cast(now() as datetime(3)), " \
206+
"cast(now() as datetime(6))",
207+
)
208+
209+
expected_types = %w[
210+
timestamp
211+
datetime(3)
212+
datetime(6)
213+
]
214+
215+
expect(result.field_types).to eql(expected_types)
216+
end
217+
202218
it "should return json type on mysql 8.0" do
203219
next unless /8.\d+.\d+/ =~ @client.server_info[:version]
204220

0 commit comments

Comments
 (0)