1

我有一个试图转换为 Opaleye 的 sql 查询。

我将简化我的代码以专注于我的问题,即如何使用 Opaleye 进行模糊搜索

Haskell(带有一些现有的 Opaleye 结构)是

namesTable :: O.Table NamesColumnWrite NamesColumnRead
namesTable = O.Table "names" (pNames Names { id = O.optional "id"
                                            , licenseNumber = O.required "license_number"
                                            , fullName = O.required "full_name"
                                            })

import qualified Database.PostgreSQL.Simple as PGS

data Names' id' licenseNumber' fullName' =
    Names
        { id           :: id'
        , licenseNumber     :: licenseNumber'
        , fullName          :: fullName'
        } deriving (Show, Eq)

namesQuery :: Query NamesColumnRead
namesQuery = queryTable NamesTable

type NamesRead = Names' Int String String
type NamesWrite = Names' (Maybe Int) String String
type NamesColumnWrite = Names' (Maybe (O.Column O.PGInt4)) (O.Column O.PGText) (O.Column O.PGText)
type NamesColumnRead = Names' (O.Column O.PGInt4) (O.Column O.PGText) (O.Column O.PGText)

getNamesByFuzzyLicenseNumber :: PGS.Connection -> String -> IO [NamesRead]
getNamesByFuzzyLicenseNumber conn licNumber = do
  let query' = "SELECT id, license_number, full_name FROM get_names_by_fuzzy_license_number_fn(?)"
  PGS.query conn query' [licNumber]

而 Sql 是

CREATE OR REPLACE FUNCTION get_names_by_license_number_fuzzy_fn(p_license_number VARCHAR)
  RETURNS TABLE
    (id INT
    ,license_number VARCHAR
    ,full_name TEXT
    )
AS $$
  SELECT
    id,
    license_number,
    full_name
  FROM names
  WHERE license_number LIKE '%' || p_license_number || '%'
$$
LANGUAGE sql;

通过“模糊搜索”,我的意思是它搜索具有许可证号的任何行,该许可证号包含搜索参数p_license_number的值作为子字符串。

如何将此模糊搜索查询转换为 Opaleye?

这将涉及摆脱 Sql 文件并用getNamesByLicenseNumberHaskell Opaleye 查询替换。我希望答案可能是这样的

getNamesByLicenseNumber :: String -> Query NamesColumnRead
getNamesByLicenseNumber licNumber = proc () -> do
  names <- namesQuery -< ()
  restrict -< pgString licNumber .== licenseNumber (names :: NamesColumnRead)
  returnA -< names

除了模糊而不是严格匹配。

4

1 回答 1

0

我不确定您的问题到底是什么,因为您所拥有的看起来非常好。有两点我会改进。首先,将字符串作为参数传递给 aQueryArr而不是作为函数参数。其次使用like而不是.==.

getNamesByLicenseNumber :: QueryArr (Column PGText) NamesColumnRead
getNamesByLicenseNumber = proc licNumber -> do
  names <- namesQuery -< ()
  restrict -< licNumber `like` licenseNumber (names :: NamesColumnRead)
  returnA -< names

这是做你想做的吗?

于 2017-07-16T15:56:07.043 回答