的C預處理器(CPP)是歷史上與C(因此而得名)相關聯的,但它確實是一個通用的文本處理器可使用的(或虐待)爲別的東西。
請考慮這個名爲location.src的文件(稍後會詳細介紹)。
// C++ style comments works here
/* C style works also */
-- plain old SQL comments also work,
-- but you should avoid using '#' style of comments,
-- this will confuse the C pre-processor ...
#define LOCATION_LEN 25
/* Debug helper macro */
#include "debug.src"
DROP TABLE IF EXISTS test.locations;
CREATE TABLE test.locations
(
`location` VARCHAR(LOCATION_LEN) NOT NULL
);
DROP PROCEDURE IF EXISTS test.AddLocation;
delimiter $$
CREATE PROCEDURE test.AddLocation (IN location VARCHAR(LOCATION_LEN))
BEGIN
-- example of macro
ASSERT(length(location) > 0, "lost or something ?");
-- do something
select "Hi there.";
END
$$
delimiter ;
和文件debug.src,其中包括:
#ifdef HAVE_DEBUG
#define ASSERT(C, T) \
begin \
if (not (C)) then \
begin \
declare my_msg varchar(1000); \
set my_msg = concat("Assert failed, file:", __FILE__, \
", line: ", __LINE__, \
", condition ", #C, \
", text: ", T); \
signal sqlstate "HY000" set message_text = my_msg; \
end; \
end if; \
end
#else
#define ASSERT(C, T) begin end
#endif
當編譯:
cpp -E location.src -o location.sql
你得到你正在尋找的代碼,與CPP擴大的#define值。
當編譯:
cpp -E -DHAVE_DEBUG location.src -o location.sql
你得到同樣的,再加上斷言宏(貼作爲獎金,顯示什麼可以來完成)。
假設與HAVE_DEBUG在測試環境中部署了一個版本(5.5或更高版本,因爲信號時),結果是這樣的:
mysql> call AddLocation("Here");
+-----------+
| Hi there. |
+-----------+
| Hi there. |
+-----------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
mysql> call AddLocation("");
ERROR 1644 (HY000): Assert failed, file:location.src, line: 24, condition length(location) > 0, text: lost or something ?
注意怎樣的文件名,行號,條件點在源代碼中位置爲location.src的位置,這是assert被引發的地方,再次感謝C預處理器。
現在,有關 「的.src」 文件擴展名:
- 你可以使用任何東西。
- 擁有不同的文件擴展名有助於makefile等,並防止混淆。
編輯:最初發布爲.xql,爲清晰起見,重命名爲.src。這裏沒有涉及到xml查詢。
與任何工具一樣,使用cpp可以帶來好的結果,而以便攜方式維護LOCATION_LEN的用例看起來非常合理。 它也可能導致不好的事情,有太多的#include,嵌套的#ifdef地獄,宏等,最後混淆代碼,所以你的里程可能會有所不同。
有了這個答案,你會得到整個事情(#define
,#include
,#ifdef
,__FILE__
,__LINE__
,#C
,命令行選項來建立),所以我希望它應該涵蓋一切。
申報的嗎? http://dev.mysql.com/doc/refman/5.0/en/declare-local-variable.html – 2012-02-11 08:57:39
我寫了一些軟件來做這樣的事情 - 它是免費的,它在這裏http:// mysql-pre- processor.batcave.net/。只需將一些東西放入您選擇的慈善機構的桶中 – 2013-05-05 21:10:04