gpt4 book ai didi

database - 如何在 haskell 中使用 HDBC 有效地检查条目是否存在?

转载 作者:搜寻专家 更新时间:2023-10-30 19:53:28 25 4
gpt4 key购买 nike

就像我在问题中提到的那样,我对要插入一些数据的表有唯一约束。我必须检查数据是否已经存在,如果不存在则将其插入。

这似乎是我做不到的。这是我的代码:

import System.Environment (getArgs)
import Database.HDBC
import Database.HDBC.Sqlite3
import Text.Regex.Posix
import qualified Data.ByteString.Char8 as B

getFrom bstr =
bstr =~ "From:.+@.+\\.(fr|com).?" :: B.ByteString

getTo bstr =
bstr =~ "To:.+@.+\\.(fr|com).?" :: B.ByteString

getSubject bstr =
bstr =~ "Subject:.+" :: B.ByteString

main = do
--[dbPath, rawMail] <- getArgs
bstr <- B.getContents
conn <- connectSqlite3 "bmsg.db"
let
sqNomDest = toSql $ getTo bstr
sqNomExped = toSql $ getFrom bstr
-- begin of the problematic part

-- I make a query to know if the entry if already present
qdbefore <- quickQuery' conn "SELECT d_id FROM dest WHERE maildest LIKE ?" [sqNomDest]
qebefore <- quickQuery' conn "SELECT e_id FROM exped WHERE mailexped LIKE ?" [sqNomExped]
-- then if not I insert it and else I return an arbitrary Int
case qdbefore of --my check is probably wrong since that snippet always go to return 0
[[SqlNull]] -> run conn "INSERT INTO dest(maildest) VALUES(?)" [sqNomDest] --unique on the column constraint so if I ran it alone on something already present it would raise an exeption
_ -> return 0
case qebefore of
[[SqlNull]] -> run conn "INSERT INTO exped(mailexped) VALUES(?)" [sqNomExped] --same here for the constraint
_ -> return 0
commit conn
--end of the problematic part

[[qd]] <- quickQuery' conn "SELECT d_id FROM dest WHERE maildest LIKE ?" [sqNomDest]
[[qe]] <- quickQuery' conn "SELECT e_id FROM exped WHERE mailexped LIKE ?" [sqNomExped]
run conn "INSERT INTO mails(d_id, e_id, sujet, mail) VALUES (?, ?, ?, ?)" [qd, qe, toSql $ getSubject bstr, toSql bstr]
commit conn
disconnect conn


-- CREATE TABLE dest
-- (
-- d_id INTEGER PRIMARY KEY,
-- maildest VARCHAR(64) NOT NULL UNIQUE
-- );

-- CREATE TABLE exped
-- (
-- e_id INTEGER PRIMARY KEY,
-- mailexped VARCHAR(64) NOT NULL UNIQUE
-- );

-- CREATE TABLE mails
-- (
-- m_id INTEGER PRIMARY KEY,
-- d_id INTEGER NOT NULL,
-- e_id INTEGER NOT NULL,
-- sujet VARCHAR(128),
-- mail TEXT NOT NULL,
-- CONSTRAINT fk_dest FOREIGN KEY (d_id) REFERENCES dest(d_id),
-- CONSTRAINT fk_exped FOREIGN KEY (e_id) REFERENCES exped(e_id)
-- );

没有错误,它编译了,但是当我给它一个不存在的电子邮件时模式匹配失败。

最佳答案

如果您的查询没有结果,您将得到一个空列表,而不是一个包含一行和一个空的列表——这就是为什么当您插入一个新事物时 case 失败的原因。对于失败的情况,只匹配一个空列表。

关于database - 如何在 haskell 中使用 HDBC 有效地检查条目是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16632986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com