Named functions बनाना और variables घोषित करना
अब जब आपने एक शक्तिशाली debugging function को काम करते देखा है, तो आइए अपना खुद का बनाते हैं. पहले, function signature परिभाषित करके शुरू कीजिए, जिसमें function का नाम, कोई भी parameters, और return type आता है. इसके बाद, यह DO function जैसा ही होता है.
यह अभ्यास पाठ्यक्रम का हिस्सा है
PostgreSQL में Transactions और Error Handling
अभ्यास निर्देश
debug_statementनाम का एक function परिभाषित करें जो एक SQL statement कोsql_stmtके रूप में लेता है.- function का return type
BOOLEANहोना चाहिए. - function दिए गए SQL statement को execute करे और कोई भी exception catch करे.
- यदि यह debugging trigger करता है तो function
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);')