2014-12-08 79 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