2013-05-19 23 views
3

就像我在我的問題中提到的那樣,我在要插入一些數據的表上有一個唯一的約束。我必須檢查數據是否已經存在,如果沒有,則插入它。如何在haskell中使用HDBC有效檢查是否存在條目?

這是我似乎無法做到的。 這裏是我的代碼:

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:[email protected]+\\.(fr|com).?" :: B.ByteString 

getTo bstr = 
    bstr =~ "To:[email protected]+\\.(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) 
--); 

沒有錯誤,它編譯,但是當我給它的電子郵件,是不是已經存在了百通匹配失敗。

+0

我最終重寫了perl中的所有東西。如果有人有解決方案,請輸入。 –

回答

0

如果你的查詢沒有結果,你會得到一個空的列表,而不是一行一列的空列表 - 這就是爲什麼當你插入一個新事物時失敗的原因。對於失敗的案例,只需匹配一個空的列表。

相關問題