FEAT: Complex Data Type Support - DATETIMEOFFSET by gargsaumya · Pull Request #243 · microsoft/mssql-python
Work Item / Issue Reference
GitHub Issue: #<ISSUE_NUMBER>
Summary
This pull request adds comprehensive support for the SQL Server DATETIMEOFFSET type in the driver, including full round-trip handling of timezone-aware Python datetime objects. The changes span the C++ bindings, Python type mapping, and test coverage to ensure correct reading and writing of DATETIMEOFFSET values, as well as validation for timezone information.
DATETIMEOFFSET support in C++ bindings:
- Defined new constants and a
DateTimeOffsetstruct inddbc_bindings.cppto represent and handle the SQL ServerDATETIMEOFFSETtype and its C type mapping (SQL_SS_TIMESTAMPOFFSET,SQL_C_SS_TIMESTAMPOFFSET). [1] [2] - Implemented logic in parameter binding to convert Python timezone-aware
datetimeobjects into theDateTimeOffsetstruct, including extracting and validating timezone offsets. Naive datetimes are rejected for this type. - Added logic to fetch
DATETIMEOFFSETvalues from the database and convert them back into Pythondatetimeobjects with the correct timezone information.
Python type mapping and constants:
- Added
SQL_DATETIMEOFFSETandSQL_C_SS_TIMESTAMPOFFSETto the driver's constants inconstants.py. - Updated the cursor's type mapping logic to use
DATETIMEOFFSETfor timezone-awaredatetimeobjects, andTIMESTAMPfor naive ones.
Testing improvements:
- Introduced a new test,
test_datetimeoffset_read_write, which verifies correct round-trip handling ofDATETIMEOFFSETvalues, including various timezone offsets and microsecond precision, and ensures that naive datetimes are rejected. - Added necessary imports for timezone handling in the test module.
These changes ensure that the driver now robustly supports SQL Server's DATETIMEOFFSET type, providing accurate and safe handling of timezone-aware datetimes between Python and the database.