我有一个试图转换为 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 文件并用getNamesByLicenseNumber
Haskell Opaleye 查询替换。我希望答案可能是这样的
getNamesByLicenseNumber :: String -> Query NamesColumnRead
getNamesByLicenseNumber licNumber = proc () -> do
names <- namesQuery -< ()
restrict -< pgString licNumber .== licenseNumber (names :: NamesColumnRead)
returnA -< names
除了模糊而不是严格匹配。