建立具名函式並宣告變數
你已經看過一個強大的除錯函式如何運作,現在來自己動手做一個吧。先定義函式簽章,也就是提供函式名稱、所有參數,以及傳回型別。之後的寫法就和 DO 函式相同。
本練習屬於課程
PostgreSQL 的交易與錯誤處理
練習說明
- 定義一個名為
debug_statement的函式,並以sql_stmt接收一個 SQL 敘述。 - 該函式的傳回型別應為
BOOLEAN。 - 函式應該執行所提供的 SQL 敘述,並攔截任何例外。
- 若有觸發除錯則傳回
True,否則傳回False。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
-- Define our function signature
___ ___ ___ ___ debug_statement(
sql_stmt TEXT
)
-- Declare our return type
___ ___ AS $$
DECLARE
exc_state TEXT;
exc_msg TEXT;
exc_detail TEXT;
exc_context TEXT;
BEGIN
BEGIN
-- Execute the statement passed in
___ sql_stmt;
EXCEPTION WHEN others THEN
GET STACKED DIAGNOSTICS
exc_state = RETURNED_SQLSTATE,
exc_msg = MESSAGE_TEXT,
exc_detail = PG_EXCEPTION_DETAIL,
exc_context = PG_EXCEPTION_CONTEXT;
INSERT into errors (msg, state, detail, context) values (exc_msg, exc_state, exc_detail, exc_context);
-- Return True to indicate the statement was debugged
___ ___;
END;
-- Return False to indicate the statement was not debugged
RETURN ___;
END;
$$ LANGUAGE plpgsql;
SELECT debug_statement('INSERT INTO patients (a1c, glucose, fasting) values (20, 89, TRUE);')