-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add support for kotlinx-datetime serializers mapping to BSON #1462
Merged
Merged
Changes from 2 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
1cff21f
Add support for kotlinx-datetime serializers mapping to BSON
vbabanin edbf9a1
Correct the doc.
vbabanin eece6be
Merge branch 'master' into JAVA-5330
vbabanin 83fc3cf
Add kotlinx datatime as optional dependency.
vbabanin 755aad6
Update bson-kotlinx/src/main/kotlin/org/bson/codecs/kotlinx/DateTimeS…
vbabanin f51b3ed
Merge branch 'master' into JAVA-5330
vbabanin 92dfc2f
Remove additional class checks.
vbabanin 55e89d1
Update bson-kotlinx/src/main/kotlin/org/bson/codecs/kotlinx/DateTimeS…
rozza 1e7d258
Update bson-kotlinx/src/main/kotlin/org/bson/codecs/kotlinx/DateTimeS…
rozza 83cd3a1
Update bson-kotlinx/src/main/kotlin/org/bson/codecs/kotlinx/DateTimeS…
rozza e0735bb
Spotless fix
rozza File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
212 changes: 212 additions & 0 deletions
212
bson-kotlinx/src/main/kotlin/org/bson/codecs/kotlinx/DateTimeSerializers.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,212 @@ | ||
/* | ||
* Copyright 2008-present MongoDB, Inc. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package org.bson.codecs.kotlinx | ||
|
||
import java.time.ZoneOffset | ||
import kotlinx.datetime.Instant | ||
import kotlinx.datetime.LocalDate | ||
import kotlinx.datetime.LocalDateTime | ||
import kotlinx.datetime.LocalTime | ||
import kotlinx.datetime.TimeZone | ||
import kotlinx.datetime.UtcOffset | ||
import kotlinx.datetime.atDate | ||
import kotlinx.datetime.atStartOfDayIn | ||
import kotlinx.datetime.toInstant | ||
import kotlinx.datetime.toLocalDateTime | ||
import kotlinx.serialization.ExperimentalSerializationApi | ||
import kotlinx.serialization.KSerializer | ||
import kotlinx.serialization.SerializationException | ||
import kotlinx.serialization.descriptors.PrimitiveKind | ||
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor | ||
import kotlinx.serialization.descriptors.SerialDescriptor | ||
import kotlinx.serialization.encoding.Decoder | ||
import kotlinx.serialization.encoding.Encoder | ||
import kotlinx.serialization.modules.SerializersModule | ||
import kotlinx.serialization.modules.plus | ||
import org.bson.BsonDateTime | ||
|
||
/** | ||
* The default serializers module | ||
* | ||
* Handles: | ||
* - ObjectId serialization | ||
* - BsonValue serialization | ||
* - Instant serialization | ||
* - LocalDate serialization | ||
* - LocalDateTime serialization | ||
* - LocalTime serialization | ||
*/ | ||
@ExperimentalSerializationApi | ||
public val dateTimeSerializersModule: SerializersModule = | ||
InstantAsBsonDateTime.serializersModule + | ||
LocalDateAsBsonDateTime.serializersModule + | ||
LocalDateTimeAsBsonDateTime.serializersModule + | ||
LocalTimeAsBsonDateTime.serializersModule | ||
|
||
/** | ||
* Instant KSerializer. | ||
* | ||
* <p> | ||
* Encodes and decodes {@code Instant} objects to and from {@code BsonDateTime}. Data is extracted via {@link | ||
* Instant#fromEpochMilliseconds()} and stored to millisecond accuracy. </p> | ||
* | ||
* @since 5.2 | ||
*/ | ||
vbabanin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
@ExperimentalSerializationApi | ||
public object InstantAsBsonDateTime : KSerializer<Instant> { | ||
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("InstantAsBsonDateTime", PrimitiveKind.STRING) | ||
|
||
override fun serialize(encoder: Encoder, value: Instant) { | ||
when (encoder) { | ||
is BsonEncoder -> encoder.encodeBsonValue(BsonDateTime(value.toEpochMilliseconds())) | ||
else -> throw SerializationException("Instant is not supported by ${encoder::class}") | ||
} | ||
} | ||
|
||
override fun deserialize(decoder: Decoder): Instant { | ||
return when (decoder) { | ||
is BsonDecoder -> Instant.fromEpochMilliseconds(decoder.decodeBsonValue().asDateTime().value) | ||
else -> throw SerializationException("Instant is not supported by ${decoder::class}") | ||
} | ||
} | ||
|
||
@Suppress("UNCHECKED_CAST") | ||
public val serializersModule: SerializersModule = SerializersModule { | ||
contextual(Instant::class, InstantAsBsonDateTime as KSerializer<Instant>) | ||
} | ||
} | ||
|
||
/** | ||
* LocalDate KSerializer. | ||
* | ||
* <p>Encodes and decodes {@code LocalDate} objects to and from {@code BsonDateTime}.</p> | ||
* | ||
* <p>Converts the {@code LocalDate} values to and from {@code UTC}.</p> | ||
rozza marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* | ||
* @since 5.2 | ||
*/ | ||
@ExperimentalSerializationApi | ||
public object LocalDateAsBsonDateTime : KSerializer<LocalDate> { | ||
override val descriptor: SerialDescriptor = | ||
PrimitiveSerialDescriptor("LocalDateAsBsonDateTime", PrimitiveKind.STRING) | ||
|
||
override fun serialize(encoder: Encoder, value: LocalDate) { | ||
when (encoder) { | ||
is BsonEncoder -> { | ||
val epochMillis = value.atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds() | ||
encoder.encodeBsonValue(BsonDateTime(epochMillis)) | ||
} | ||
else -> throw SerializationException("LocalDate is not supported by ${encoder::class}") | ||
} | ||
} | ||
|
||
override fun deserialize(decoder: Decoder): LocalDate { | ||
return when (decoder) { | ||
is BsonDecoder -> | ||
Instant.fromEpochMilliseconds(decoder.decodeBsonValue().asDateTime().value) | ||
.toLocalDateTime(TimeZone.UTC) | ||
.date | ||
else -> throw SerializationException("LocalDate is not supported by ${decoder::class}") | ||
} | ||
} | ||
|
||
@Suppress("UNCHECKED_CAST") | ||
public val serializersModule: SerializersModule = SerializersModule { | ||
contextual(LocalDate::class, LocalDateAsBsonDateTime as KSerializer<LocalDate>) | ||
} | ||
} | ||
|
||
/** | ||
* LocalDateTime KSerializer. | ||
* | ||
* <p>Encodes and decodes {@code LocalDateTime} objects to and from {@code BsonDateTime}. Data is stored to millisecond | ||
* accuracy.</p> | ||
* | ||
* <p>Converts the {@code LocalDateTime} values to and from {@code UTC}.</p> | ||
* | ||
* @since 5.2 | ||
rozza marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*/ | ||
@ExperimentalSerializationApi | ||
public object LocalDateTimeAsBsonDateTime : KSerializer<LocalDateTime> { | ||
override val descriptor: SerialDescriptor = | ||
PrimitiveSerialDescriptor("LocalDateTimeAsBsonDateTime", PrimitiveKind.STRING) | ||
|
||
override fun serialize(encoder: Encoder, value: LocalDateTime) { | ||
when (encoder) { | ||
is BsonEncoder -> { | ||
val epochMillis = value.toInstant(UtcOffset(ZoneOffset.UTC)).toEpochMilliseconds() | ||
encoder.encodeBsonValue(BsonDateTime(epochMillis)) | ||
} | ||
else -> throw SerializationException("LocalDateTime is not supported by ${encoder::class}") | ||
} | ||
} | ||
|
||
override fun deserialize(decoder: Decoder): LocalDateTime { | ||
return when (decoder) { | ||
is BsonDecoder -> | ||
Instant.fromEpochMilliseconds(decoder.decodeBsonValue().asDateTime().value) | ||
.toLocalDateTime(TimeZone.UTC) | ||
else -> throw SerializationException("LocalDateTime is not supported by ${decoder::class}") | ||
} | ||
} | ||
|
||
@Suppress("UNCHECKED_CAST") | ||
public val serializersModule: SerializersModule = SerializersModule { | ||
contextual(LocalDateTime::class, LocalDateTimeAsBsonDateTime as KSerializer<LocalDateTime>) | ||
} | ||
} | ||
|
||
/** | ||
* LocalTime KSerializer. | ||
* | ||
* <p>Encodes and decodes {@code LocalTime} objects to and from {@code BsonDateTime}. Data is stored to millisecond | ||
* accuracy.</p> | ||
* | ||
* <p>Converts the {@code LocalTime} values to and from EpochDay at {@code UTC}.</p> | ||
rozza marked this conversation as resolved.
Show resolved
Hide resolved
|
||
* | ||
* @since 5.2 | ||
*/ | ||
@ExperimentalSerializationApi | ||
public object LocalTimeAsBsonDateTime : KSerializer<LocalTime> { | ||
override val descriptor: SerialDescriptor = | ||
PrimitiveSerialDescriptor("LocalTimeAsBsonDateTime", PrimitiveKind.STRING) | ||
|
||
override fun serialize(encoder: Encoder, value: LocalTime) { | ||
when (encoder) { | ||
is BsonEncoder -> { | ||
val epochMillis = | ||
value.atDate(LocalDate.fromEpochDays(0)).toInstant(UtcOffset(ZoneOffset.UTC)).toEpochMilliseconds() | ||
encoder.encodeBsonValue(BsonDateTime(epochMillis)) | ||
} | ||
else -> throw SerializationException("LocalTime is not supported by ${encoder::class}") | ||
} | ||
} | ||
|
||
override fun deserialize(decoder: Decoder): LocalTime { | ||
return when (decoder) { | ||
is BsonDecoder -> | ||
Instant.fromEpochMilliseconds(decoder.decodeBsonValue().asDateTime().value) | ||
.toLocalDateTime(TimeZone.UTC) | ||
.time | ||
else -> throw SerializationException("LocalTime is not supported by ${decoder::class}") | ||
} | ||
} | ||
|
||
@Suppress("UNCHECKED_CAST") | ||
public val serializersModule: SerializersModule = SerializersModule { | ||
contextual(LocalTime::class, LocalTimeAsBsonDateTime as KSerializer<LocalTime>) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This version is compatible with Kotlin versions 1.5 and later. The next version 0.5.0 requires Kotlin 1.9 or higher, as indicated by this commit:
Commit details on kotlinx-datetime
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can't take a hard dependency on this library - so this will need refactoring to make it optional. #1459 adds a check for kotlinx-json support, you could use that style to add an if statement for the
defaultSerializersModule
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I have refactored it to make the library optional, using the approach outlined in #1459 for checking kotlinx-datetime support. Thanks!