0

给定这样的持久模型定义:

mkPersist sqlSettings [persistLowerCase|
Person
    name String
    age Int
    deriving Show
|]

我正在寻找一种方法来获取此模型的字段定义。FieldDef看起来很有前途的数据类型,但是持久化不生成getPersonFields :: [FieldDef]函数,那怎么办呢?

如果这是一个 XY 问题 - 这是背景:我想返回某种元数据以防 json 解析错误。如果我尝试发布一个新人但 json 错误,我想回复如下内容:

{
    "result": "error",
    "code": 8,
    "message": "Could not parse payload as person",
    "fields": [
        {
            "name": "name",
            "type": "string"
        },
        {
            "name": "age",
            "type": "int"
        }
    ]
}
4

1 回答 1

2

一个示例显示它是如何完成的:

#!/usr/bin/env stack
{- stack
     --resolver lts-9.0
     --install-ghc
     runghc
     --package persistent
     --package persistent-sqlite
     --package persistent-template
-}

{-# LANGUAGE EmptyDataDecls             #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE GADTs                      #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE OverloadedStrings          #-}
{-# LANGUAGE QuasiQuotes                #-}
{-# LANGUAGE TemplateHaskell            #-}
{-# LANGUAGE TypeFamilies               #-}
import           Control.Monad.IO.Class  (liftIO)
import           Database.Persist
import           Database.Persist.Sqlite
import           Database.Persist.TH

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Person
    name String
    age Int Maybe
    deriving Show
BlogPost
    title String
    authorId PersonId
    deriving Show
|]

main :: IO ()
main = let efields = entityFields $ entityDef (undefined :: Maybe Person)
       in print efields

演示:

$ stack efield.hs
[FieldDef {fieldHaskell = HaskellName {unHaskellName = "name"}, fieldDB = DBName {unDBName = "name"}, fieldType = FTTypeCon Nothing "String", fieldSqlType = SqlString, fieldAttrs = [], fieldStrict = True, fieldReference = NoReference},FieldDef {fieldHaskell = HaskellName {unHaskellName = "age"}, fieldDB = DBName {unDBName = "age"}, fieldType = FTTypeCon Nothing "Int", fieldSqlType = SqlInt64, fieldAttrs = ["Maybe"], fieldStrict = True, fieldReference = NoReference}]
于 2017-10-08T06:23:29.810 回答