Skip to content

Commit f377958

Browse files
committed
[mssql] Fix conversion of time values
At least using the linux sql server driver, time fields are not correctly automatically converted to QTime variants. Instead they are returned as a raw byte array containing the value. Add special handling to ensure that these time values are read regardless. (there's already a test in place for this, which was failing on Linux)
1 parent 0729653 commit f377958

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

src/providers/mssql/qgsmssqlfeatureiterator.cpp

+20-2
Original file line numberDiff line numberDiff line change
@@ -321,10 +321,28 @@ bool QgsMssqlFeatureIterator::fetchFeature( QgsFeature &feature )
321321

322322
for ( int i = 0; i < mAttributesToFetch.count(); i++ )
323323
{
324-
QVariant v = mQuery->value( i );
324+
const QVariant originalValue = mQuery->value( i );
325325
QgsField fld = mSource->mFields.at( mAttributesToFetch.at( i ) );
326+
QVariant v = originalValue;
326327
if ( v.type() != fld.type() )
327-
v = QgsVectorDataProvider::convertValue( fld.type(), v.toString() );
328+
v = QgsVectorDataProvider::convertValue( fld.type(), originalValue.toString() );
329+
330+
// second chance for time fields -- time fields are not correctly handled by sql server driver on linux (maybe win too?)
331+
if ( v.isNull() && fld.type() == QVariant::Time && originalValue.isValid() && originalValue.type() == QVariant::ByteArray )
332+
{
333+
// time fields can be returned as byte arrays... woot
334+
const QByteArray ba = originalValue.toByteArray();
335+
if ( ba.length() >= 5 )
336+
{
337+
const int hours = ba.at( 0 );
338+
const int mins = ba.at( 2 );
339+
const int seconds = ba.at( 4 );
340+
v = QTime( hours, mins, seconds );
341+
if ( !v.isValid() ) // can't handle it
342+
v = QVariant( QVariant::Time );
343+
}
344+
}
345+
328346
feature.setAttribute( mAttributesToFetch.at( i ), v );
329347
}
330348

tests/src/python/test_provider_mssql.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -74,13 +74,13 @@ def testDateTimeTypes(self):
7474
f = next(vl.getFeatures(QgsFeatureRequest()))
7575

7676
date_idx = vl.fields().lookupField('date_field')
77-
assert isinstance(f.attributes()[date_idx], QDate)
77+
self.assertIsInstance(f.attributes()[date_idx], QDate)
7878
self.assertEqual(f.attributes()[date_idx], QDate(2004, 3, 4))
7979
time_idx = vl.fields().lookupField('time_field')
80-
assert isinstance(f.attributes()[time_idx], QTime)
80+
self.assertIsInstance(f.attributes()[time_idx], QTime)
8181
self.assertEqual(f.attributes()[time_idx], QTime(13, 41, 52))
8282
datetime_idx = vl.fields().lookupField('datetime_field')
83-
assert isinstance(f.attributes()[datetime_idx], QDateTime)
83+
self.assertIsInstance(f.attributes()[datetime_idx], QDateTime)
8484
self.assertEqual(f.attributes()[datetime_idx], QDateTime(
8585
QDate(2004, 3, 4), QTime(13, 41, 52)))
8686

0 commit comments

Comments
 (0)