2014-12-08 39 views
4

在Haskell中使用Groundhog库时,我期待实现一个在后端是Postgresql时使用“uuid”的列类型,否则只需将“varchar”用于任何其他后端。根据Groundhog.Core中的评论,这应该是可能的,但我不完全确定如何从proxy db解开dbType,并且在groundhog示例中没有这样的例子,因为在这些示例中已经对列类型进行了硬编码。如何基于Haskell Groundhog的数据库类型指定不同的列类型?

我想在Postgresql的大小写匹配方面提供一些帮助,一旦排序完成,我将解决其余问题。下面是我在哪里:

instance PrimitivePersistField UUID where 
    toPrimitivePersistValue _ uuid = PersistString $ show uuid 
    fromPrimitivePersistValue _ (PersistString a) = fromJust $ UUIDmethods.fromString a 

instance PersistField UUID where 
    persistName _ = "UUID" 
    toPersistValues = primToPersistValue 
    fromPersistValues = primFromPersistValue 
    dbType db _ = case db of 
    Postgresql _ -> DbTypePrimitive (DbOther $ OtherTypeDef [Left "uuid"]) False Nothing Nothing 
    _ -> DbTypePrimitive (DbOther $ OtherTypeDef [Left "varchar"]) False Nothing Nothing 

而且在编译此出现:

Couldn't match expected type ‘proxy db’ 
       with actual type ‘Postgresql’ 
    Relevant bindings include 
     db :: proxy db (bound at basicGroundhog.hs:34:10) 
     dbType :: proxy db -> UUID -> DbType 
     (bound at basicGroundhag.hs:34:3) 
    In the pattern: Postgresql _ 
    In a case alternative: 
     Postgresql _ 
      -> DbTypePrimitive 
       (DbOther $ OtherTypeDef [Left "uuid"]) False Nothing Nothing 
    In the expression: 
     case db of { 
     Postgresql _ 
      -> DbTypePrimitive 
       (DbOther $ OtherTypeDef [Left "uuid"]) False Nothing Nothing 
     _ -> DbTypePrimitive 
       (DbOther $ OtherTypeDef [Left "varchar"]) False Nothing Nothing } 

回答

1

您可以在运行时与backendName检查数据库。最好将DbString作为默认情况,以便groundhog可以选择更合适的类型。没有最大长度声明的Varchar在MySQL中无效。

dbType db _ = case backendName db of 
    "postgresql" -> DbTypePrimitive (DbOther $ OtherTypeDef [Left "uuid"]) False Nothing Nothing 
    _ -> DbTypePrimitive DbString False Nothing Nothing 
+0

谢谢,正是我所需要的。 – MalucoMarinero 2014-12-09 21:33:13