前篇介紹了MySQL如何從SQL語句轉換成一個內部對象。本文是前篇的延續,將更加詳細的介紹WHERE語句對應的Item對象。
1. Item對象@MySQL Internal
MySQL Internals Manual較為詳細的介紹了Item對象。Item對象經常被稱作"thingamabob"(A thingamabob is a noun used to describe items that either you can't remember the name of or that don't actually exist.)。Item是一個類,每一個Item實例都:(1)代表一個SQL語句里的對象;(2)有取值;(3)有數據類型指針。
下面列出的的SQL相關的對象都是一個Item對象,或者繼承至Item:(1)一段字符; (2)數據表的某列; (3)一個局部或全局變量; (4)一個存儲過程的變量; (5) 一個用戶參數; (6)一個函數/存儲過程(這包括運算符+、||、=、like等) 。例如下面的SQL語句:
SELECT UPPER(column1) FROM t WHERE column2 = @x;
MySQL需要一系列的Item來描述上面的SQL:一個描述column1對象,描述UPPER函數的對象,還有描述WHERE語句的幾個相關的Item對象。Item對象可以理解做一個特殊的數據對象。MySQL的Item對象定義在./sql/item.h中,其子類都定義在./sql/item*.h中,例如item_cmpfunc.h, item_func.h。在MySQL Server層代碼中有大量操作和使用Item對象的代碼,建議閱讀的時候,慢慢理解。
2. WHERE對應的Item對象
本節將介紹MySQL中如何使用Item對象描述一個WHERE條件。下面從簡單到復雜,逐個介紹:
2.1 WHERE id >= 1 and id < 3
2.2 WHERE id = 1 or id >10
2.3 WHERE id >= 0 and id < 2 or id = 20
驗證:
(gdb) p ((Item_cond *)conds)->functype()
$5 = Item_func::COND_OR_FUNC
打印WHERE(也就是Item_cond_or) List中的第一個元素:
(gdb) p ((Item_cond *)(((Item_cond *)conds)->list->first->info))->functype()
$17 = Item_func::COND_AND_FUNC
第二個元素
(gdb) p ((Item_cond *)(((Item_cond *)conds)->list->first->next->info))->functype()
$18 = Item_func::EQ_FUNC
2.4 WHERE (id = 10 or … ) and id >= 15
WHERE (id = 10 or id < 3 ) and id >= 15
(gdb) p ((Item_cond_or *)((Item_cond_and *)conds)->list->first->info)->list->first
$39 = (list_node *) 0x7facfc005698
(gdb) p ((Item_cond_or *)((Item_cond_and *)conds)->list->first->info)->list->first->info
$40 = (void *) 0x7facfc005150
(gdb) p (Item *)$40
$41 = (Item *) 0x7facfc005150
(gdb) p ((Item *)$40)->type()
$42 = Item::FUNC_ITEM
(gdb) p ((Item_func *)$40)->functype()
$43 = Item_func::EQ_FUNC
(gdb) p ((Item_func_eq *)$40)->arg_count
$44 = 2
(gdb) p ((Item_func_eq *)$40)->args[0]
$45 = (Item *) 0x7facfc004fe0
2.5 WHERE id >= 15 or (id > 1 and id ?< 10)
(gdb) p ((Item *)conds)->type()
$47 = Item::COND_ITEM
(gdb) p ((Item_cond *)conds)->functype()
$48 = Item_func::COND_OR_FUNC
(gdb) p ((Item_cond_or *)conds)->list->first->next->info
$56 = (void *) 0x7facfc0058b8
(gdb) p ((Item *)$56)->type()
$57 = Item::COND_ITEM
(gdb) p ((Item_cond *)$56)->functype()
$58 = Item_func::COND_AND_FUNC
2.6 WHERE id >= 15 or ( … and ( … or … ))
WHERE id >= 15 or ( id > 1 and ( id < 4 or id = 0 ))
3. Item對象的繼承關系圖
3.1 Item_bool_func的繼承關系圖
3.2 完整Item對象繼承關系圖
完整的Item繼承關系圖非常復雜,下面是縮略圖:(完整圖,1.8MB,謹慎打開)
這是一幅龐大關系圖,使用doxygen+graphviz繪制(如何使用doxygen;如何配置doxygen生成MySQL文檔)。
參考
MySQL source code
MySQL Internal Manual
覺得文章有用?立即:
和朋友一起 共學習 共進步!
猜您喜歡