Skip to content

Commit

Permalink
Fix DateTimeOffset
Browse files Browse the repository at this point in the history
Store as blob like praeclarum/sqlite-net#933
Use ticks for the rare case that the offset is in seconds
  • Loading branch information
Joy-less committed Nov 29, 2024
1 parent 2d87edb commit db80593
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions SQLiteSharp/SQLite.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2008,7 +2008,7 @@ public static string SqlType(TableMapping.Column column) {
return "bigint";
}
else if (clrType == typeof(DateTimeOffset)) {
return "bigint";
return "blob";
}
else if (clrType.IsEnum) {
return column.StoreAsText ? "varchar" : "integer";
Expand Down Expand Up @@ -2285,7 +2285,7 @@ internal static void BindParameter(Sqlite3Statement stmt, int index, object? val
SQLite3.BindInt64(stmt, index, dateTimeValue.Ticks);
}
else if (value is DateTimeOffset dateTimeOffsetValue) {
SQLite3.BindInt64(stmt, index, dateTimeOffsetValue.UtcTicks);
SQLite3.BindBlob(stmt, index, DateTimeOffsetToBytes(dateTimeOffsetValue));
}
else if (value is byte[] byteArrayValue) {
SQLite3.BindBlob(stmt, index, byteArrayValue);
Expand Down Expand Up @@ -2348,7 +2348,7 @@ private class Binding {
return new DateTime(SQLite3.ColumnInt64(stmt, index));
}
else if (clrType == typeof(DateTimeOffset)) {
return new DateTimeOffset(SQLite3.ColumnInt64(stmt, index), TimeSpan.Zero);
return BytesToDateTimeOffset(SQLite3.ColumnBlob(stmt, index));
}
else if (clrType.IsEnum) {
if (type is SQLite3.ColType.Text) {
Expand Down Expand Up @@ -2407,6 +2407,18 @@ private class Binding {
}
}
}

internal static DateTimeOffset BytesToDateTimeOffset(byte[] bytes) {
long dateTicks = BitConverter.ToInt64(bytes, 0);
long offsetTicks = BitConverter.ToInt64(bytes, sizeof(long));
return new DateTimeOffset(new DateTime(dateTicks), TimeSpan.FromTicks(offsetTicks));
}
internal static byte[] DateTimeOffsetToBytes(DateTimeOffset dateTimeOffset) {
return [
.. BitConverter.GetBytes(dateTimeOffset.DateTime.Ticks),
.. BitConverter.GetBytes(dateTimeOffset.Offset.Ticks)
];
}
}

internal class FastColumnSetter {
Expand Down Expand Up @@ -2468,7 +2480,7 @@ internal class FastColumnSetter {
}
else if (clrType == typeof(DateTimeOffset)) {
return CreateNullableTypedSetterDelegate<T, DateTimeOffset>(column, (stmt, index) => {
return new DateTimeOffset(SQLite3.ColumnInt64(stmt, index), TimeSpan.Zero);
return SQLiteCommand.BytesToDateTimeOffset(SQLite3.ColumnBlob(stmt, index));
});
}
else if (clrType.IsEnum) {
Expand Down

0 comments on commit db80593

Please sign in to comment.