development

MySQL 저장 프로 시저를 어떻게 디버깅합니까?

big-blog 2020. 7. 22. 07:34
반응형

MySQL 저장 프로 시저를 어떻게 디버깅합니까?


저장 프로 시저 디버깅을위한 현재 프로세스는 매우 간단합니다. 저장 프로 시저가 실행될 때 변수 값을 삽입하는 "디버그"라는 테이블을 만듭니다. 이를 통해 스크립트의 특정 시점에서 변수의 값을 볼 수 있지만 MySQL 저장 프로 시저를 디버깅하는 더 좋은 방법이 있습니까?


나는 당신과 매우 비슷한 일을합니다.

일반적으로 DEBUG 매개 변수를 기본적으로 false로 설정하고 런타임에 true로 설정할 수 있습니다. 그런 다음 디버그 명령문을 "If DEBUG"블록으로 랩하십시오.

또한 프로세스와 타이밍을 검토 할 수 있도록 많은 작업과 함께 로깅 테이블을 사용합니다. 내 디버그 코드도 거기에 출력됩니다. 호출 매개 변수 이름, 간단한 설명, 영향을받는 행 수 (적절한 경우), 설명 필드 및 타임 스탬프를 포함합니다.

좋은 디버깅 도구는 모든 SQL 플랫폼의 슬픈 실패 중 하나입니다.


debug_msg콘솔에 디버그 메시지를 간단히 출력하기 위해 다음 절차를 호출 할 수 있습니다.

DELIMITER $$

DROP PROCEDURE IF EXISTS `debug_msg`$$
DROP PROCEDURE IF EXISTS `test_procedure`$$

CREATE PROCEDURE debug_msg(enabled INTEGER, msg VARCHAR(255))
BEGIN
  IF enabled THEN
    select concat('** ', msg) AS '** DEBUG:';
  END IF;
END $$

CREATE PROCEDURE test_procedure(arg1 INTEGER, arg2 INTEGER)
BEGIN
  SET @enabled = TRUE;

  call debug_msg(@enabled, 'my first debug message');
  call debug_msg(@enabled, (select concat_ws('','arg1:', arg1)));
  call debug_msg(TRUE, 'This message always shows up');
  call debug_msg(FALSE, 'This message will never show up');
END $$

DELIMITER ;

그런 다음 다음과 같이 테스트를 실행하십시오.

CALL test_procedure(1,2)

결과는 다음과 같습니다.

** DEBUG:
** my first debug message
** DEBUG:
** arg1:1
** DEBUG:
** This message always shows up

그렇습니다. 이런 종류의 도구 인 MySQL Debugger가 있습니다.
여기에 이미지 설명을 입력하십시오


MySQL에는 저장 프로 시저 / 함수 및 스크립트 를 디버깅하기위한 GUI 도구 가 있습니다 . dbForge Studio for MySQL에서 제공하는 적절한 도구는 다양한 기능과 안정성을 제공합니다.


MySQL 저장 프로 시저를 디버깅하는 방법

불쌍한 디버거 :

  1. 두 개의 열이 LOGTABLE라는 테이블을 생성 id INT하고 log VARCHAR(255).

  2. id 열을 자동 증가시킵니다.

  3. 이 절차를 사용하십시오.

    delimiter //
    DROP PROCEDURE `log_msg`//
    CREATE PROCEDURE `log_msg`(msg VARCHAR(255))
    BEGIN
        insert into logtable select 0, msg;
    END
    
  4. 이 코드를 메시지를 테이블에 기록하려는 위치에 놓으십시오.

    call log_msg(concat('myvar is: ', myvar, ' and myvar2 is: ', myvar2));
    

It's a nice quick and dirty little logger to figure out what is going on.


Debugger for mysql was good but its not free. This is what i use now:

DELIMITER GO$

DROP PROCEDURE IF EXISTS resetLog

GO$

Create Procedure resetLog() 
BEGIN   
    create table if not exists log (ts timestamp default current_timestamp, msg varchar(2048)) engine = myisam; 
    truncate table log;
END; 

GO$

DROP PROCEDURE IF EXISTS doLog 

GO$

Create Procedure doLog(in logMsg nvarchar(2048))
BEGIN  
  insert into log (msg) values(logMsg);
END;

GO$

Usage in stored procedure:

call dolog(concat_ws(': ','@simple_term_taxonomy_id',  @simple_term_taxonomy_id));

usage of stored procedure:

call resetLog ();
call stored_proc();
select * from log;

Another way is presented here

http://gilfster.blogspot.co.at/2006/03/debugging-stored-procedures-in-mysql.html

with custom debug mySql procedures and logging tables.

You can also just place a simple select in your code and see if it is executed.

SELECT 'Message Text' AS `Title`; 

I got this idea from

http://forums.mysql.com/read.php?99,78155,78225#msg-78225

Also somebody created a template for custom debug procedures on GitHub.

See here

http://www.bluegecko.net/mysql/debugging-stored-procedures/ https://github.com/CaptTofu/Stored-procedure-debugging-routines

Was mentioned here

How to catch any exception in triggers and store procedures for mysql?


I just simply place select statements in key areas of the stored procedure to check on current status of data sets, and then comment them out (--select...) or remove them before production.


MySQL Connector/Net 6.6 has a feature to Debug Stored Procedures and Functions

Installing the Debugger

To enable the stored procedure debugger:

  • For Connector/Net 6.6: Install Connector/Net 6.6 and choose the Complete option.
  • For Connector/Net 6.7 and later: Install the product MySQL for Visual Studio, to which the stored procedure debugger belongs.

Starting the Debugger

To start the debugger, follow these steps:

  • Choose a connection in the Visual Studio Server Explorer.
  • Expand the Stored Procedures folder. Only stored procedures can be debugged directly. To debug a user-defined function, create a stored
    procedure that calls the function.
  • Click on a stored procedure node, then right-click and from the context menu choose Debug Routine.

I'm late to the party, but brought more beer:

http://ocelot.ca/blog/blog/2015/03/02/the-ocelotgui-debugger/ and https://github.com/ocelot-inc/ocelotgui

I tried, and it seems pretty stable, supporting Breakpoints and Variable inspection.

It's not a complete suite (just 4,1 Mb) but helped me a lot!

How it works: It integrates with your mysql client (I'm using Ubuntu 14.04), and after you execute:

$install
$setup yourFunctionName

It installs a new database at your server, that control the debugging process. So:

$debug yourFunctionName('yourParameter')

will give you a chance to step by step walk your code, and "refreshing" your variables you can better view what is going on inside your code.

Important Tip: while debugging, maybe you will change (re-create the procedure). After a re-creation, execute: $exit and $setup before a new $debug

This is an alternative to "insert" and "log" methods. Your code remains free of additional "debug" instructions.

Screenshot:

오셀롯 브레이크 포인트 스테핑


MySql Connector/NET also includes a stored procedure debugger integrated in visual studio as of version 6.6, You can get the installer and the source here: http://dev.mysql.com/downloads/connector/net/

Some documentation / screenshots: https://dev.mysql.com/doc/visual-studio/en/visual-studio-debugger.html

You can follow the annoucements here: http://forums.mysql.com/read.php?38,561817,561817#msg-561817

UPDATE: The MySql for Visual Studio was split from Connector/NET into a separate product, you can pick it (including the debugger) from here https://dev.mysql.com/downloads/windows/visualstudio/1.2.html (still free & open source).

DISCLAIMER: I was the developer who authored the Stored procedures debugger engine for MySQL for Visual Studio product.


The first and stable debugger for MySQL is in dbForge Studio for MySQL


I had use two different tools to debug procedures and functions:

  1. dbForge - many functional mysql GUI.
  2. MyDebugger - specialized tool for debugging ... handy tool for debugging.vote http://tinyurl.com/voteimg

두꺼비 mysql. 프리웨어 버전이 있습니다 http://www.quest.com/toad-for-mysql/


에 해당하는 답변 MySQL의 버전에 대해 확실하지 @ 브래드 공원으로, 그러나 광산은 5.6, 따라서 약간의 조정이 작동했다 :

debug_msg함수 (프로 시저가 아님) 인 함수 만들고 텍스트 (문자 제한 없음)를 반환 한 다음 함수를 SELECT debug_msg(params) AS my_res_set, 아래 코드로 호출하십시오 .

CREATE DEFINER=`root`@`localhost` FUNCTION `debug_msg`(`enabled` INT(11), `msg` TEXT) RETURNS text CHARSET latin1
    READS SQL DATA
BEGIN
    IF enabled=1 THEN
    return concat('** DEBUG:', "** ", msg);
    END IF;
END

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `proc_func_call`(
 IN RegionID VARCHAR(20),
 IN RepCurrency INT(11),
 IN MGID INT(11),
 IN VNC VARCHAR(255)
)
BEGIN
    SET @enabled = TRUE;
    SET @mainQuery = "SELECT * FROM Users u";
    SELECT `debug_msg`(@enabled, @mainQuery) AS `debug_msg1`;
    SET @lastQuery = CONCAT(@mainQuery, " WHERE u.age>30);
    SELECT `debug_msg`(@enabled, @lastQuery) AS `debug_msg2`;
END $$
DELIMITER

참고 URL : https://stackoverflow.com/questions/273437/how-do-you-debug-mysql-stored-procedures

반응형