Last active
December 20, 2015 22:19
-
-
Save sifue/6204643 to your computer and use it in GitHub Desktop.
org.joda.time.DateTimeをScala Slick 1.0.x で利用するためのTypeMapper。内部的にTimestampに変換している。また、比較演算子等も利用できる。ただし、日付リテラルは、MySQLのDATETIMEを前提としたものになっている。
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
import scala.slick.lifted._ | |
import java.util.Date | |
import org.joda.time.DateTime | |
import scala.slick.driver.{BasicDriver, BasicProfile} | |
import scala.slick.session.{PositionedResult, PositionedParameters} | |
import scala.language.implicitConversions | |
/** | |
* [[org.joda.time.DateTime]]を[[java.sql.Date]]にSlickにおいて暗黙変換して利用する | |
* | |
* 比較演算子等の利用も可能 | |
* MySQLのDATETIME型に入れられることを前提とした日付リテラルの変換を行う | |
* 利用は、 | |
* import DateTimeTypeMapper._ | |
* の一行を書き入れることで型としてDateTimeを利用できるようになる | |
* | |
* https://gist.github.com/dragisak/4756344 のやり方では格納はできるが、比較等はできないため作成 | |
* [[scala.slick.lifted.TypeMapper]] を実装 | |
* | |
*/ | |
object DateTimeTypeMapper { | |
implicit object DateTimeTypeMapper extends BaseTypeMapper[DateTime] { | |
def apply(profile: BasicProfile): DateTimeTypeMapperDelegate = new DateTimeTypeMapperDelegate | |
} | |
implicit def columnExtensionMethods[DateTime](c: Column[DateTime]): ColumnExtensionMethods[DateTime, DateTime] = | |
new ColumnExtensionMethods[DateTime, DateTime](c) | |
implicit def optionColumnExtensionMethods[DateTime](c: Column[Option[DateTime]]): ColumnExtensionMethods[DateTime, Option[DateTime]] = | |
new ColumnExtensionMethods[DateTime, Option[DateTime]](c) | |
} | |
/** | |
* [[scala.slick.lifted.TypeMapper]] のコメントに忠実に実装DataMapperの実装を用意 | |
*/ | |
class DateTimeTypeMapperDelegate extends TypeMapperDelegate[DateTime] { | |
private val zeroUnixTime = 0L | |
def sqlTypeName: String = BasicDriver.defaultSqlTypeName(this) | |
def zero: DateTime = new DateTime(new Date(zeroUnixTime)) | |
def sqlType: Int = java.sql.Types.TIMESTAMP | |
def setValue(v: DateTime, p: PositionedParameters): Unit = p.setTimestamp(valueToSQLType(v)) | |
def setOption(v: Option[DateTime], p: PositionedParameters): Unit = p.setTimestampOption(v.map(valueToSQLType)) | |
def nextValue(r: PositionedResult): DateTime = new DateTime(r.nextTimestamp()) | |
def updateValue(v: DateTime, r: PositionedResult): Unit = r.updateTimestamp(valueToSQLType(v)) | |
override def valueToSQLLiteral(value: DateTime): String = { | |
// For MySQL DATETIME format | |
"'" + (value.toString("yyyy/MM/dd HH:mm:ss")) + "'" | |
} | |
def valueToSQLType(value: DateTime): java.sql.Timestamp = { | |
new java.sql.Timestamp(value.getMillis) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment